Object-Oriented Concepts PDF
Document Details
Tags
Summary
This document provides a brief overview of object-oriented concepts, including a history of the paradigm, analysis, design, and programming. It discusses key concepts and programming languages.
Full Transcript
Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Object-Oriented Concepts A Brief History The object-oriented paradigm took its shape from the initial concept of a new programming approach, while the interest in design and analysis methods came much later....
Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Object-Oriented Concepts A Brief History The object-oriented paradigm took its shape from the initial concept of a new programming approach, while the interest in design and analysis methods came much later. The first object–oriented language was Simula (Simulation of real systems) that was developed in 1960 by researchers at the Norwegian Computing Center. In 1970, Alan Kay and his research group at Xerox PARK created a personal computer named Dynabook and the first pure object-oriented programming language (OOPL) - Smalltalk, for programming the Dynabook. In the 1980s, Grady Booch published a paper titled Object Oriented Design that mainly presented a design for the programming language, Ada. In the ensuing editions, he extended his ideas to a complete object–oriented design method. In the 1990s, Coad incorporated behavioral ideas to object-oriented methods. The other significant innovations were Object Modelling Techniques (OMT) by James Rumbaugh and Object-Oriented Software Engineering (OOSE) by Ivar Jacobson. Object-Oriented Analysis Object–Oriented Analysis (OOA) is the procedure of identifying software engineering requirements and developing software specifications in terms of a software system’s object model, which comprises of interacting objects. The main difference between object-oriented analysis and other forms of analysis is that in object-oriented approach, requirements are organized around objects, which integrate both data and functions. They are modelled after real-world objects that the system interacts with. In traditional analysis methodologies, the two aspects - functions and data - are considered separately. Grady Booch has defined OOA as, “Object-oriented analysis is a method of analysis that examines requirements from the perspective of the classes and objects found in the vocabulary of the problem domain”. The primary tasks in object-oriented analysis (OOA) are − Identifying objects Organizing the objects by creating object model diagram Defining the internals of the objects, or object attributes Defining the behavior of the objects, i.e., object actions Describing how the objects interact Page | 35 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 The common models used in OOA are use cases and object models. Object-Oriented Design Object–Oriented Design (OOD) involves implementation of the conceptual model produced during object-oriented analysis. In OOD, concepts in the analysis model, which are technology−independent, are mapped onto implementing classes, constraints are identified and interfaces are designed, resulting in a model for the solution domain, i.e., a detailed description of how the system is to be built on concrete technologies. The implementation details generally include − Restructuring the class data (if necessary), Implementation of methods, i.e., internal data structures and algorithms, Implementation of control, and Implementation of associations. Grady Booch has defined object-oriented design as “a method of design encompassing the process of object-oriented decomposition and a notation for depicting both logical and physical as well as static and dynamic models of the system under design”. Object-Oriented Programming Object-oriented programming (OOP) is a programming paradigm based upon objects (having both data and methods) that aims to incorporate the advantages of modularity and reusability. Objects, which are usually instances of classes, are used to interact with one another to design applications and computer programs. The important features of object–oriented programming are − Bottom–up approach in program design Programs organized around objects, grouped in classes Focus on data with methods to operate upon object’s data Interaction between objects through functions Reusability of design through creation of new classes by adding features to existing classes Some examples of object-oriented programming languages are C++, Java, Smalltalk, Delphi, C#, Perl, Python, Ruby, and PHP. Grady Booch has defined object–oriented programming as “a method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of some class, and whose classes are all members of a hierarchy of classes united via inheritance relationships”. Page | 36 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 In the following section, we will look into the basic concepts and terminologies of object–oriented systems. Objects and Classes The concepts of objects and classes are intrinsically linked with each other and form the foundation of object–oriented paradigm. Object An object is a real-world element in an object–oriented environment that may have a physical or a conceptual existence. Each object has − Identity that distinguishes it from other objects in the system. State that determines the characteristic properties of an object as well as the values of the properties that the object holds. Behavior that represents externally visible activities performed by an object in terms of changes in its state. Objects can be modelled according to the needs of the application. An object may have a physical existence, like a customer, a car, etc.; or an intangible conceptual existence, like a project, a process, etc. Class A class represents a collection of objects having same characteristic properties that exhibit common behavior. It gives the blueprint or description of the objects that can be created from it. Creation of an object as a member of a class is called instantiation. Thus, object is an instance of a class. The constituents of a class are − A set of attributes for the objects that are to be instantiated from the class. Generally, different objects of a class have some difference in the values of the attributes. Attributes are often referred as class data. A set of operations that portray the behavior of the objects of the class. Operations are also referred as functions or methods. Example Let us consider a simple class, Circle, that represents the geometrical figure circle in a two–dimensional space. The attributes of this class can be identified as follows − x–coord, to denote x–coordinate of the center y–coord, to denote y–coordinate of the center a, to denote the radius of the circle Page | 37 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Some of its operations can be defined as follows − findArea(), method to calculate area findCircumference(), method to calculate circumference scale(), method to increase or decrease the radius During instantiation, values are assigned for at least some of the attributes. If we create an object my_circle, we can assign values like x-coord : 2, y-coord : 3, and a : 4 to depict its state. Now, if the operation scale() is performed on my_circle with a scaling factor of 2, the value of the variable a will become 8. This operation brings a change in the state of my_circle, i.e., the object has exhibited certain behavior. Encapsulation and Data Hiding Encapsulation Encapsulation is the process of binding both attributes and methods together within a class. Through encapsulation, the internal details of a class can be hidden from outside. It permits the elements of the class to be accessed from outside only through the interface provided by the class. Data Hiding Typically, a class is designed such that its data (attributes) can be accessed only by its class methods and insulated from direct outside access. This process of insulating an object’s data is called data hiding or information hiding. Example In the class Circle, data hiding can be incorporated by making attributes invisible from outside the class and adding two more methods to the class for accessing class data, namely − setValues(), method to assign values to x-coord, y-coord, and a getValues(), method to retrieve values of x-coord, y-coord, and a Here the private data of the object my_circle cannot be accessed directly by any method that is not encapsulated within the class Circle. It should instead be accessed through the methods setValues() and getValues(). Message Passing Any application requires a number of objects interacting in a harmonious manner. Objects in a system may communicate with each other using message passing. Page | 38 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Suppose a system has two objects: obj1 and obj2. The object obj1 sends a message to object obj2, if obj1 wants obj2 to execute one of its methods. The features of message passing are − Message passing between two objects is generally unidirectional. Message passing enables all interactions between objects. Message passing essentially involves invoking class methods. Objects in different processes can be involved in message passing. Inheritance Inheritance is the mechanism that permits new classes to be created out of existing classes by extending and refining its capabilities. The existing classes are called the base classes/parent classes/super-classes, and the new classes are called the derived classes/child classes/subclasses. The subclass can inherit or derive the attributes and methods of the super-class(es) provided that the super-class allows so. Besides, the subclass may add its own attributes and methods and may modify any of the super- class methods. Inheritance defines an “is – a” relationship. Example From a class Mammal, a number of classes can be derived such as Human, Cat, Dog, Cow, etc. Humans, cats, dogs, and cows all have the distinct characteristics of mammals. In addition, each has its own particular characteristics. It can be said that a cow “is – a” mammal. Types of Inheritance Single Inheritance − A subclass derives from a single super-class. Multiple Inheritance − A subclass derives from more than one super-classes. Multilevel Inheritance − A subclass derives from a super-class which in turn is derived from another class and so on. Hierarchical Inheritance − A class has a number of subclasses each of which may have subsequent subclasses, continuing for a number of levels, so as to form a tree structure. Hybrid Inheritance − A combination of multiple and multilevel inheritance so as to form a lattice structure. The following figure depicts the examples of different types of inheritance. Page | 39 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Polymorphism Polymorphism is originally a Greek word that means the ability to take multiple forms. In object-oriented paradigm, polymorphism implies using operations in different ways, depending upon the instance they are operating upon. Polymorphism allows objects with different internal structures to have a common external interface. Polymorphism is particularly effective while implementing inheritance. Example Page | 40 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Let us consider two classes, Circle and Square, each with a method findArea(). Though the name and purpose of the methods in the classes are same, the internal implementation, i.e., the procedure of calculating area is different for each class. When an object of class Circle invokes its findArea() method, the operation finds the area of the circle without any conflict with the findArea() method of the Square class. Generalization and Specialization Generalization and specialization represent a hierarchy of relationships between classes, where subclasses inherit from super-classes. Generalization In the generalization process, the common characteristics of classes are combined to form a class in a higher level of hierarchy, i.e., subclasses are combined to form a generalized super-class. It represents an “is – a – kind – of” relationship. For example, “car is a kind of land vehicle”, or “ship is a kind of water vehicle”. Specialization Specialization is the reverse process of generalization. Here, the distinguishing features of groups of objects are used to form specialized classes from existing classes. It can be said that the subclasses are the specialized versions of the super-class. The following figure shows an example of generalization and specialization. Links and Association Link A link represents a connection through which an object collaborates with other objects. Rumbaugh has defined it as “a physical or conceptual connection between objects”. Through a link, one object may invoke the methods or navigate through another object. A link depicts the relationship between two or more objects. Association Page | 41 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Association is a group of links having common structure and common behavior. Association depicts the relationship between objects of one or more classes. A link can be defined as an instance of an association. Degree of an Association Degree of an association denotes the number of classes involved in a connection. Degree may be unary, binary, or ternary. A unary relationship connects objects of the same class. A binary relationship connects objects of two classes. A ternary relationship connects objects of three or more classes. Cardinality Ratios of Associations Cardinality of a binary association denotes the number of instances participating in an association. There are three types of cardinality ratios, namely − One–to–One − A single object of class A is associated with a single object of class B. One–to–Many − A single object of class A is associated with many objects of class B. Many–to–Many − An object of class A may be associated with many objects of class B and conversely an object of class B may be associated with many objects of class A. Aggregation or Composition Aggregation or composition is a relationship among classes by which a class can be made up of any combination of objects of other classes. It allows objects to be placed directly within the body of other classes. Aggregation is referred as a “part–of” or “has–a” relationship, with the ability to navigate from the whole to its parts. An aggregate object is an object that is composed of one or more other objects. Example In the relationship, “a car has–a motor”, car is the whole object or the aggregate, and the motor is a “part–of” the car. Aggregation may denote − Physical containment − Example, a computer is composed of monitor, CPU, mouse, keyboard, and so on. Conceptual containment − Example, shareholder has–a share. Benefits of Object Model Now that we have gone through the core concepts pertaining to object orientation, it would be worthwhile to note the advantages that this model has to offer. Page | 42 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 The benefits of using the object model are − It helps in faster development of software. It is easy to maintain. Suppose a module develops an error, then a programmer can fix that particular module, while the other parts of the software are still up and running. It supports relatively hassle-free upgrades. It enables reuse of objects, designs, and functions. It reduces development risks, particularly in integration of complex systems. OBJECT MODELLING USING UML Model A model captures aspects important for some application while omitting (or abstracting) the rest. A model in the context of software development can be graphical, textual, mathematical, or program code-based. Models are very useful in documenting the design and analysis results. Models also facilitate the analysis and design procedures themselves. Graphical models are very popular because they are easy to understand and construct. UML is primarily a graphical modeling tool. However, it often requires text explanations to accompany the graphical models. Need for a model An important reason behind constructing a model is that it helps manage complexity. Once models of a system have been constructed, these can be used for a variety of purposes during software development, including the following: Analysis Specification Code generation Design Visualize and understand the problem and the working of a system Testing, etc. In all these applications, the UML models can not only be used to document the results but also to arrive at the results themselves. Since a model can be used for a variety of purposes, it is reasonable to expect that the model would vary depending on the purpose for which it is being constructed. For example, a model developed for initial analysis and specification should be very different from the one used for design. A model that is being used for analysis and specification would not show any of the design decisions that would be made later on during the design stage. On the other Page | 43 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 hand, a model used for design purposes should capture all the design decisions. Therefore, it is a good idea to explicitly mention the purpose for which a model has been developed, along with the model. Unified Modelling Language (UML) UML, as the name implies, is a modelling language. It may be used to visualize, specify, construct, and document the artifacts of a software system. It provides a set of notations (e.g. rectangles, lines, ellipses, etc.) to create a visual model of the system. Like any other language, UML has its own syntax (symbols and sentence formation rules) and semantics (meanings of symbols and sentences). Also, we should clearly understand that UML is not a system design or development methodology, but can be used to document object-oriented and analysis results obtained using some methodology. Origin of UML In the late 1980s and early 1990s, there was a proliferation of object-oriented design techniques and notations. Different software development houses were using different notations to document their object-oriented designs. These diverse notations used to give rise to a lot of confusion. UML was developed to standardize the large number of object-oriented modeling notations that existed and were used extensively in the early 1990s. The principles ones in use were: Object Management Technology [Rumbaugh 1991] Booch’s methodology [Booch 1991] Object-Oriented Software Engineering [Jacobson 1992] Odell’s methodology [Odell 1992] Shaler and Mellor methodology [Shaler 1992] It is needless to say that UML has borrowed many concepts from these modeling techniques. Especially, concepts from the first three methodologies have been heavily drawn upon. UML was adopted by Object Management Group (OMG) as a de facto standard in 1997. OMG is an association of industries which tries to facilitate early formation of standards. We shall see that UML contains an extensive set of notations and suggests construction of many types of diagrams. It has successfully been used to model both large and small problems. The elegance of UML, its adoption by OMG, and a strong industry backing Page | 44 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 have helped UML find widespread acceptance. UML is now being used in a large number of software development projects worldwide. UML Diagrams UML can be used to construct nine different types of diagrams to capture five different views of a system. Just as a building can be modeled from several views (or perspectives) such as ventilation perspective, electrical perspective, lighting perspective, heating perspective, etc.; the different UML diagrams provide different perspectives of the software system to be developed and facilitate a comprehensive understanding of the system. Such models can be refined to get the actual implementation of the system. The UML diagrams can capture the following five views of a system: User’s view Structural view Behavioral view Implementation view Environmental view Fig. 12.1: Different types of diagrams and views supported in UML User’s view: This view defines the functionalities (facilities) made available by the system to its users. The users’ view captures the external users’ view of the system in terms of the functionalities offered by the system. The users’ view is a black-box view Page | 45 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 of the system where the internal structure, the dynamic behavior of different system components, the implementation etc. are not visible. The users’ view is very different from all other views in the sense that it is a functional model compared to the object model of all other views. The users’ view can be considered as the central view and all other views are expected to conform to this view. This thinking is in fact the crux of any user centric development style. Structural view: The structural view defines the kinds of objects (classes) important to the understanding of the working of a system and to its implementation. It also captures the relationships among the classes (objects). The structural model is also called the static model, since the structure of a system does not change with time. Behavioral view: The behavioral view captures how objects interact with each other to realize the system behavior. The system behavior captures the time-dependent (dynamic) behavior of the system. Implementation view: This view captures the important components of the system and their dependencies. Environmental view: This view models how the different components are implemented on different pieces of hardware. USE CASE DIAGRAM Use Case Model The use case model for any system consists of a set of “use cases”. Intuitively, use cases represent the different ways in which a system can be used by the users. A simple way to find all the use cases of a system is to ask the question: “What the users can do using the system?” Thus for the Library Information System (LIS), the use cases could be: issue-book query-book return-book create-member add-book, etc Use cases correspond to the high-level functional requirements. The use cases partition the system behavior into transactions, such that each transaction performs some useful action from the user’s point of view. To complete each transaction may involve either a single message or multiple message exchanges between the user and the system to complete. Page | 46 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Purpose of use cases The purpose of a use case is to define a piece of coherent behavior without revealing the internal structure of the system. The use cases do not mention any specific algorithm to be used or the internal data representation, internal structure of the software, etc. A use case typically represents a sequence of interactions between the user and the system. These interactions consist of one mainline sequence. The mainline sequence represents the normal interaction between a user and the system. The mainline sequence is the most occurring sequence of interaction. For example, the mainline sequence of the withdraw cash use case supported by a bank ATM drawn, complete the transaction, and get the amount. Several variations to the main line sequence may also exist. Typically, a variation from the mainline sequence occurs when some specific conditions hold. For the bank ATM example, variations or alternate scenarios may occur, if the password is invalid or the amount to be withdrawn exceeds the amount balance. The variations are also called alternative paths. A use case can be viewed as a set of related scenarios tied together by a common goal. The mainline sequence and each of the variations are called scenarios or instances of the use case. Each scenario is a single path of user events and system activity through the use case. Representation of Use Cases Use cases can be represented by drawing a use case diagram and writing an accompanying text elaborating the drawing. In the use case diagram, each use case is represented by an ellipse with the name of the use case written inside the ellipse. All the ellipses (i.e. use cases) of a system are enclosed within a rectangle which represents the system boundary. The name of the system being modeled (such as Library Information System) appears inside the rectangle. The different users of the system are represented by using the stick person icon. Each stick person icon is normally referred to as an actor. An actor is a role played by a user with respect to the system use. It is possible that the same user may play the role of multiple actors. Each actor can participate in one or more use cases. The line connecting the actor and the use case is called the communication relationship. It indicates that the actor makes use of the functionality provided by the use case. Both the human users and the external systems can be represented by stick person icons. When a stick person icon represents an external system, it is annotated by the stereotype. Example 1: Tic-Tac-Toe Computer Game Tic-tac-toe is a computer game in which a human player and the computer make alternative moves on a 3×3 square. A move consists of marking previously unmarked square. The player who first places three consecutive marks along a straight line on the square (i.e. along a row, column, or diagonal) wins the game. As soon as either the Page | 47 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 human player or the computer wins, a message congratulating the winner should be displayed. If neither player manages to get three consecutive marks along a straight line, but all the squares on the board are filled up, then the game is drawn. The computer always tries to win a game. The use case model for the Tic-tac-toe problem is shown in fig. 13.1. This software has only one use case “play move”. Note that the use case “get-user-move” is not used here. The name “get-user-move” would be inappropriate because the use cases should be named from the user’s perspective. Fig. 13.1: Use case model for tic-tac-toe game Text Description Each ellipse on the use case diagram should be accompanied by a text description. The text description should define the details of the interaction between the user and the computer and other aspects of the use case. It should include all the behavior associated with the use case in terms of the mainline sequence, different variations to the normal behavior, the system responses associated with the use case, the exceptional conditions that may occur in the behavior, etc. The behavior description is often written in a conversational style describing the interactions between the actor and the system. The text description may be informal, but some structuring is recommended. The following are some of the information which may be included in a use case text description in addition to the mainline sequence, and the alternative scenarios. Contact persons: This section lists the personnel of the client organization with whom the use case was discussed, date and time of the meeting, etc. Actors: In addition to identifying the actors, some information about actors using this use case which may help the implementation of the use case may be recorded. Pre-condition: The preconditions would describe the state of the system before the use case execution starts. Page | 48 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Post-condition: This captures the state of the system after the use case has successfully completed. Non-functional requirements: This could contain the important constraints for the design and implementation, such as platform and environment conditions, qualitative statements, response time requirements, etc. Exceptions, error situations: This contains only the domain-related errors such as lack of user’s access rights, invalid entry in the input fields, etc. Obviously, errors that are not domain related, such as software errors, need not be discussed here. Sample dialogs: These serve as examples illustrating the use case. Specific user interface requirements: These contain specific requirements for the user interface of the use case. For example, it may contain forms to be used, screen shots, interaction style, etc. Document references: This part contains references to specific domain-related documents which may be useful to understand the system operation Example 2: A supermarket needs to develop the following software to encourage regular customers. For this, the customer needs to supply his/her residence address, telephone number, and the driving license number. Each customer who registers for this scheme is assigned a unique customer number (CN) by the computer. A customer can present his CN to the checkout staff when he makes any purchase. In this case, the value of his purchase is credited against his CN. At the end of each year, the supermarket intends to award surprise gifts to 10 customers who make the highest total purchase over the year. Also, it intends to award a 22 caret gold coin to every customer whose purchase exceeded Rs.10,000. The entries against the CN are the reset on the day of every year after the prize winners’ lists are generated. The use case model for the Supermarket Prize Scheme is shown in fig. 13.2. As discussed earlier, the use cases correspond to the high-level functional requirements. From the problem description, we can identify three use cases: “register-customer”, “register-sales”, and “select-winners”. As a sample, the text description for the use case “register-customer” is shown. Page | 49 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Fig. 13.2 Use case model for Supermarket Prize Scheme Text description U1: register-customer: Using this use case, the customer can register himself by providing the necessary details. Scenario 1: Mainline sequence 1. Customer: select register customer option. 2. System: display prompt to enter name, address, and telephone number. Customer: enter the necessary values. 4. System: display the generated id and the message that the customer has been successfully registered. Scenario 2: at step 4 of mainline sequence 1. System: displays the message that the customer has already registered. Scenario 2: at step 4 of mainline sequence 1. System: displays the message that some input information has not been entered. The system displays a prompt to enter the missing value. The description for other use cases is written in a similar fashion. Page | 50 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Utility of use case diagrams From use case diagram, it is obvious that the utility of the use cases are represented by ellipses. They along with the accompanying text description serve as a type of requirements specification of the system and form the core model to which all other models must conform. But, what about the actors (stick person icons)? One possible use of identifying the different types of users (actors) is in identifying and implementing a security mechanism through a login system, so that each actor can involve only those functionalities to which he is entitled to. Another possible use is in preparing the documentation (e.g. users’ manual) targeted at each category of user. Further, actors help in identifying the use cases and understanding the exact functioning of the system. Factoring of use cases It is often desirable to factor use cases into component use cases. Actually, factoring of use cases are required under two situations. First, complex use cases need to be factored into simpler use cases. This would not only make the behavior associated with the use case much more comprehensible, but also make the corresponding interaction diagrams more tractable. Without decomposition, the interaction diagrams for complex use cases may become too large to be accommodated on a single sized (A4) paper. Secondly, use cases need to be factored whenever there is common behavior across different use cases. Factoring would make it possible to define such behavior only once and reuse it whenever required. It is desirable to factor out common usage such as error handling from a set of use cases. This makes analysis of the class design much simpler and elegant. However, a word of caution here. Factoring of use cases should not be done except for achieving the above two objectives. From the design point of view, it is not advantageous to break up a use case into many smaller parts just for the sake of it. UML offers three mechanisms for factoring of use cases as follows: 1. Generalization Use case generalization can be used when one use case that is similar to another, but does something slightly differently or something more. Generalization works the same way with use cases as it does with classes. The child use case inherits the behavior and meaning of the parent use case. The notation is the same too (as shown in fig. 13.3). It is important to remember that the base and the derived use cases are separate use cases and should have separate text descriptions. Page | 51 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Fig. 13.3: Representation of use case generalization Includes The includes relationship in the older versions of UML (prior to UML 1.1) was known as the uses relationship. The includes relationship involves one use case including the behavior of another use case in its sequence of events and actions. The includes relationship occurs when a chunk of behavior that is similar across a number of use cases. The factoring of such behavior will help in not repeating the specification and implementation across different use cases. Thus, the includes relationship explores the issue of reuse by factoring out the commonality across use cases. It can also be gainfully employed to decompose a large and complex use cases into more manageable parts. As shown in fig. 13.4 the includes relationship is represented using a predefined stereotype.In the includes relationship, a base use case compulsorily and automatically includes the behavior of the common use cases. As shown in example fig. 13.5, issue-book and renew-book both include check- reservation use case. The base use case may include several use cases. In such cases, it may interleave their associated common use cases together. The common use case becomes a separate use case and the independent text description should be provided for it. Fig. 13.4 Representation of use case inclusion Page | 52 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Fig. 13.5: Example use case inclusion Extends The main idea behind the extends relationship among the use cases is that it allows you to show optional system behavior. An optional system behavior is extended only under certain conditions. This relationship among use cases is also predefined as a stereotype as shown in fig. 13.6. The extends relationship is similar to generalization. But unlike generalization, the extending use case can add additional behavior only at an extension point only when certain conditions are satisfied. The extension points are points within the use case where variation to the mainline (normal) action sequence may occur. The extends relationship is normally used to capture alternate paths or scenarios. Fig. 13.6: Example use case extension Organization of use cases Page | 53 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 When the use cases are factored, they are organized hierarchically. The high-level use cases are refined into a set of smaller and more refined use cases as shown in fig. 13.7. Top-level use cases are super-ordinate to the refined use cases. The refined use cases are sub-ordinate to the top-level use cases. Note that only the complex use cases should be decomposed and organized in a hierarchy. It is not necessary to decompose simple use cases. The functionality of the super-ordinate use cases is traceable to their sub-ordinate use cases. Thus, the functionality provided by the super-ordinate use cases is composite of the functionality of the sub-ordinate use cases. In the highest level of the use case model, only the fundamental use cases are shown. The focus is on the application context. Therefore, this level is also referred to as the context diagram. In the context diagram, the system limits are emphasized. In the top-level diagram, only those use cases with which external users of the system. The subsystem-level use cases specify the services offered by the subsystems. Any number of levels involving the subsystems may be utilized. In the lowest level of the use case hierarchy, the class- level use cases specify the functional fragments or operations offered by the classes. CLASS DIAGRAMS A class diagram describes the static structure of a system. It shows how a system is structured rather than how it behaves. The static structure of a system comprises of a number of class diagrams and their dependencies. The main constituents of a class diagram are classes and their relationships: generalization, aggregation, association, and various kinds of dependencies. Classes The classes represent entities with common features, i.e. attributes and operations. Classes are represented as solid outline rectangles with compartments. Classes have a mandatory name compartment where the name is written centered in boldface. The class name is usually written using mixed case convention and begins with an uppercase. The class names are usually chosen to be singular nouns. Classes have optional attributes and operations compartments. A class may appear on several diagrams. Its attributes and operations are suppressed on all but one diagram. Attributes An attribute is a named property of a class. It represents the kind of data that an object might contain. Attributes are listed with their names, and may optionally contain specification of their type, an initial value, and constraints. The type of the attribute is written by appending a colon and the type name after the attribute name. Typically, the first letter of a class name is a small letter. An example for an attribute is given. bookName : String Page | 54 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Operation Operation is the implementation of a service that can be requested from any object of the class to affect behaviour. An object’s data or state can be changed by invoking an operation of the object. A class may have any number of operations or no operation at all. Typically, the first letter of an operation name is a small letter. Abstract operations are written in italics. The parameters of an operation (if any), may have a kind specified, which may be ‘in’, ‘out’ or ‘inout’. An operation may have a return type consisting of a single return type expression. An example for an operation is given. issueBook(in bookName):Boolean Association Associations are needed to enable objects to communicate with each other. An association describes a connection between classes. The association relation between two objects is called object connection or link. Links are instances of associations. A link is a physical or conceptual connection between object instances. For example, suppose Amit has borrowed the book Graph Theory. Here, borrowed is the connection between the objects Amit and Graph Theory book. Mathematically, a link can be considered to be a tuple, i.e. an ordered list of object instances. An association describes a group of links with a common structure and common semantics. For example, consider the statement that Library Member borrows Books. Here, borrows is the association between the class Library Member and the class Book. Usually, an association is a binary relation (between two classes). However, three or more different classes can be involved in an association. A class can have an association relationship with itself (called recursive association). In this case, it is usually assumed that two different objects of the class are linked by the association relationship. Association between two classes is represented by drawing a straight line between the concerned classes. Fig. 14.1 illustrates the graphical representation of the association relation. The name of the association is written alongside the association line. An arrowhead may be placed on the association line to indicate the reading direction of the association. The arrowhead should not be misunderstood to be indicating the direction of a pointer implementing an association. On each side of the association relation, the multiplicity is noted as an individual number or as a value range. The multiplicity indicates how many instances of one class are associated with each other. Value ranges of multiplicity are noted by specifying the minimum and maximum value, separated by two dots, e.g. 1.5. An asterisk is a wild card and means many (zero or more). The association of fig. 14.1 should be read as “Many books may be borrowed by a Library Member”. Observe that associations (and links) appear as verbs in the problem Page | 55 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 statement. Fig. 14.1: Association between two classes Associations are usually realized by assigning appropriate reference attributes to the classes involved. Thus, associations can be implemented using pointers from one object class to another. Links and associations can also be implemented by using a separate class that stores which objects of a class are linked to which objects of another class. Some CASE tools use the role names of the association relation for the corresponding automatically generated attribute. Aggregation Aggregation is a special type of association where the involved classes represent a whole-part relationship. The aggregate takes the responsibility of forwarding messages to the appropriate parts. Thus, the aggregate takes the responsibility of delegation and leadership. When an instance of one object contains instances of some other objects, then aggregation (or composition) relationship exists between the composite object and the component object. Aggregation is represented by the diamond symbol at the composite end of a relationship. The number of instances of the component class aggregated can also be shown as in fig. 14.2 Fig. 14.2: Representation of aggregation Aggregation relationship cannot be reflexive (i.e. recursive). That is, an object cannot contain objects of the same class as itself. Also, the aggregation relation is not symmetric. That is, two classes A and B cannot contain instances of each other. However, the aggregation relationship can be transitive. In this case, aggregation may consist of an arbitrary number of levels. Page | 56 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Composition Composition is a stricter form of aggregation, in which the parts are existence- dependent on the whole. This means that the life of the parts closely ties to the life of the whole. When the whole is created, the parts are created and when the whole is destroyed, the parts are destroyed. A typical example of composition is an invoice object with invoice items. As soon as the invoice object is created, all the invoice items in it are created and as soon as the invoice object is destroyed, all invoice items in it are also destroyed. The composition relationship is represented as a filled diamond drawn at the composite-end. An example of the composition relationship is shown in fig. 14.3 Fig 14.3: Representation of composition Association vs. Aggregation vs. Composition Association is the most general (m:n) relationship. Aggregation is a stronger relationship where one is a part of the other. Composition is even stronger than aggregation, ties the lifecycle of the part and the whole together. Association relationship can be reflexive (objects can have relation to itself), but aggregation cannot be reflexive. Moreover, aggregation is anti-symmetric (If B is a part of A, A cannot be a part of B). Composition has the property of exclusive aggregation i.e. an object can be a part of only one composite at a time. For example, a Frame belongs to exactly one Window whereas in simple aggregation, a part may be shared by several objects. For example, a Wall may be a part of one or more Room objects. In addition, in composition, the whole has the responsibility for the disposition of all its parts, i.e. for their creation and destruction. in general, the lifetime of parts and composite coincides parts with non-fixed multiplicity may be created after composite itself parts might be explicitly removed before the death of the composite For example, when a Frame is created, it has to be attached to an enclosing Window. Similarly, when the Window is destroyed, it must in turn destroy its Frame parts. Inheritance vs. Aggregation/Composition Inheritance describes ‘is a’ / ‘is a kind of’ relationship between classes (base class - derived class) whereas aggregation describes ‘has a’ relationship between classes. Inheritance means that the object of the derived class inherits the Page | 57 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 properties of the base class; aggregation means that the object of the whole has objects of the part. For example, the relation “cash payment is a kind of payment” is modeled using inheritance; “purchase order has a few items” is modeled using aggregation. Inheritance is used to model a “generic-specific” relationship between classes whereas aggregation/composition is used to model a “whole-part” relationship between classes. Inheritance means that the objects of the subclass can be used anywhere the super class may appear, but not the reverse; i.e. wherever we could use instances of ‘payment’ in the system, we could substitute it with instances of ‘cash payment’, but the reverse cannot be done. Inheritance is defined statically. It cannot be changed at run-time. Aggregation is defined dynamically and can be changed at run-time. Aggregation is used when the type of the object can change over time. For example, consider this situation in a business system. A BusinessPartner might be a Customer or a Supplier or both. Initially we might be tempted to model it as in Fig 14.4(a). But in fact, during its lifetime, a business partner might become a customer as well as a supplier, or it might change from one to the other. In such cases, we prefer aggregation instead (see Fig 14.4(b). Here, a business partner is a Customer if it has an aggregated Customer object, a Supplier if it has an aggregated Supplier object and a "Customer_Supplier" if it has both. Here, we have only two types. Hence, we are able to model it as inheritance. But what if there were several different types and combinations thereof? The inheritance tree would be absolutely incomprehensible. Also, the aggregation model allows the possibility for a business partner to be neither - i.e. has neither a customer nor a supplier object aggregated with it. Page | 58 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Fig. 14.4 a) Representation of BusinessPartner, Customer, Supplier relationship using inheritance Fig. 14.4 b) Representation of BusinessPartner, Customer, Supplier relationship using aggregation The advantage of aggregation is the integrity of encapsulation. The operations of an object are the interfaces of other objects which imply low implementation dependencies. The significant disadvantage of aggregation is the increase in the number of objects and their relationships. On the other hand, inheritance allows for an easy way to modify implementation for reusability. But the significant disadvantage is that it breaks encapsulation, which implies implementation dependence. INTERACTION DIAGRAMS Interaction diagrams are models that describe how group of objects collaborate to realize some behavior. Typically, each interaction diagram realizes the behavior of a single use case. An interaction diagram shows a number of example objects and the messages that are passed between the objects within the use case. There are two kinds of interaction diagrams: sequence diagrams and collaboration diagrams. These two diagrams are equivalent in the sense that any one diagram can be derived automatically from the other. However, they are both useful. These two actually portray different perspectives of behavior of the system and different types Page | 59 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 of inferences can be drawn from them. The interaction diagrams can be considered as a major tool in the design methodology. Sequence Diagram A sequence diagram shows interaction among objects as a two dimensional chart. The chart is read from top to bottom. The objects participating in the interaction are shown at the top of the chart as boxes attached to a vertical dashed line. Inside the box the name of the object is written with a colon separating it from the name of the class and both the name of the object and the class are underlined. The objects appearing at the top signify that the object already existed when the use case execution was initiated. However, if some object is created during the execution of the use case and participates in the interaction (e.g. a method call), then the object should be shown at the appropriate place on the diagram where it is created. The vertical dashed line is called the object’s lifeline. The lifeline indicates the existence of the object at any particular point of time. The rectangle drawn on the lifetime is called the activation symbol and indicates that the object is active as long as the rectangle exists. Each message is indicated as an arrow between the life line of two objects. The messages are shown in chronological order from the top to the bottom. That is, reading the diagram from the top to the bottom would show the sequence in which the messages occur. Each message is labeled with the message name. Some control information can also be included. Two types of control information are particularly valuable. A condition (e.g. [invalid]) indicates that a message is sent, only if the condition is true. An iteration marker shows the message is sent many times to multiple receiver objects as would happen when a collection or the elements of an array are being iterated. The basis of the iteration can also be indicated e.g. [for every book object]. The sequence diagram for the book renewal use case for the Library Automation Software is shown in fig. 15.1. The development of the sequence diagram in the development methodology would help us in determining the responsibilities of the different classes; i.e. what methods should be supported by each class. Page | 60 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Fig. 15.1: Sequence diagram for the renew book use case Collaboration Diagram A collaboration diagram shows both structural and behavioral aspects explicitly. This is unlike a sequence diagram which shows only the behavioral aspects. The structural aspect of a collaboration diagram consists of objects and the links existing between them. In this diagram, an object is also called a collaborator. The behavioral aspect is described by the set of messages exchanged among the different collaborators. The link between objects is shown as a solid line and can be used to send messages between two objects. The message is shown as a labeled arrow placed near the link. Messages are prefixed with sequence numbers because they are only way to describe the relative sequencing of the messages in this diagram. The collaboration diagram for the example of fig. 15.1 is shown in fig. 15.2. The use of the collaboration diagrams in our development process would be to help us to determine which classes are associated with which other classes. Page | 61 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Fig 15.2: Collaboration diagram for the renew book use case ACTIVITY AND STATE CHART DIAGRAM The activity diagram is possibly one modeling element which was not present in any of the predecessors of UML. No such diagrams were present either in the works of Booch, Jacobson, or Rumbaugh. It is possibly based on the event diagram of Odell through the notation is very different from that used by Odell. The activity diagram focuses on representing activities or chunks of processing which may or may not correspond to the methods of classes. An activity is a state with an internal action and one or more outgoing transitions which automatically follow the termination of the internal activity. If an activity has more than one outgoing transitions, then these must be identified through conditions. An interesting feature of the activity diagrams is the swim lanes. Swim lanes enable you to group activities based on who is performing them, e.g. academic department vs. hostel office. Thus swim lanes subdivide activities based on the responsibilities of some components. The activities in a swim lane can be assigned to some model elements, e.g. classes or some component, etc. Activity diagrams are normally employed in business process modeling. This is carried out during the initial stages of requirements analysis and specification. Activity diagrams can be very useful to understand complex processing activities involving many components. Later these diagrams can be used to develop interaction diagrams which help to allocate activities (responsibilities) to classes. The student admission process in a university is shown as an activity diagram in fig. 16.1. This shows the part played by different components of the Institute in the admission procedure. After the fees are received at the account section, parallel Page | 62 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 activities start at the hostel office, hospital, and the Department. After all these activities complete (this synchronization is represented as a horizontal line), the identity card can be issued to a student by the Academic section. Fig. 16.1: Activity diagram for student admission procedure at a university Activity diagrams vs. Procedural flow charts Activity diagrams are similar to the procedural flow charts. The difference is that activity diagrams support description of parallel activities and synchronization aspects involved in different activities. STATE CHART DIAGRAM A state chart diagram is normally used to model how the state of an object changes in its lifetime. State chart diagrams are good at describing how the behavior of an object changes across several use case executions. However, if we are interested in modeling some behavior that involves several objects collaborating with each other, state chart diagram is not appropriate. State chart diagrams are based on the finite state machine (FSM) formalism. A FSM consists of a finite number of states corresponding to those of the object being modeled. The object undergoes state changes when specific events occur. The FSM formalism existed long before the object-oriented technology and has been used for a wide variety of applications. Apart from modeling, it has even been used in theoretical computer science as a generator for regular languages. Page | 63 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 A major disadvantage of the FSM formalism is the state explosion problem. The number of states becomes too many and the model too complex when used to model practical systems. This problem is overcome in UML by using state charts. The state chart formalism was proposed by David Harel. A state chart is a hierarchical model of a system and introduces the concept of a composite state (also called nested state). Actions are associated with transitions and are considered to be processes that occur quickly and are not interruptible. Activities are associated with states and can take longer. An activity can be interrupted by an event. The basic elements of the state chart diagram are as follows: Initial state- This is represented as a filled circle. Final state- This is represented by a filled circle inside a larger circle. State- These are represented by rectangles with rounded corners. Transition- A transition is shown as an arrow between two states. Normally, the name of the event which causes the transition is places alongside the arrow. A guard to the transition can also be assigned. A guard is a Boolean logic condition. The transition can take place only if the grade evaluates to true. The syntax for the label of the transition is shown in 3 parts: event [guard]/action. An example state chart for the order object of the Trade House Automation software is shown in fig. 16.2. Page | 64 Software System & Design Unit - II Semester I B. Tech (CSE) 2028 Fig. 16.2: State chart diagram for an order object Activity diagram vs. State chart diagram Both activity and state chart diagrams model the dynamic behavior of the system. Activity diagram is essentially a flowchart showing flow of control from activity to activity. A state chart diagram shows a state machine emphasizing the flow of control from state to state. An activity diagram is a special case of a state chart diagram in which all or most of the states are activity states and all or most of the transitions are triggered by completion of activities in the source state (An activity is an ongoing non-atomic execution within a state machine). Activity diagrams may stand alone to visualize, specify, and document the dynamics of a society of objects or they may be used to model the flow of control of an operation. State chart diagrams may be attached to classes, use cases, or entire systems in order to visualize, specify, and document the dynamics of an individual object. Page | 65