Вы находитесь на странице: 1из 56

CIS380 OOAA Free Book Part 1

Unified Modeling Language (UML)


UML brought into existence in Jan 1997 Provides a basis for constructing, configuring, and deploying computer systems The Unified Modeling Language (UML) is composed of nine diagrams: 1) Use case diagram, 2) Sequence diagram, 3) Collaboration diagram, 4) Statechart diagram, 5) Activity diagram, 6) Class diagram, 7) object diagram, 8) Component diagram, and 9) Deployment diagram. The diagrams highlighted are covered in this class.

Functional Modeling
Functional models describe business processes and the interaction of an information system with its environment. In object-oriented systems development, two types of models are used to describe functionality: activity diagrams (logical modeling of business processes and workflows) and use cases (describe basic functions of information system). A requirements definition defines what the system is to do. Activity diagrams and use cases document and organize the requirements that are obtained during the analysis phase. Process models depict how a business system operates (illustrate the activities that are performed and how objects (data) move among them). Use case is the driver for the rest of the other diagrams. A use case illustrates the activities performed by the users of the system providing an external view of a business process (the users view of process). Activity diagrams and use cases are logical models that describe activities without suggesting how they are conducted (technology neutral should not indicate if computerized or manual). The physical details are defined during design when the logical models are refined into physical models. As a first step, the project team gathers requirements from users. Then using the gathered requirements, the project team models the overall business process using activity diagrams (note: in this class the overall system and subsystems are modeled using a data flow diagram and activity diagrams are used to model processes or subprocesses). These diagrams identify activities which are used to pinpoint the use cases that occur in the business. Next, use-case descriptions and use case diagrams

are prepared for each use case. Once the activity diagrams and use-case descriptions are prepared, systems analysts transform them into a use-case diagram. Then, class diagrams are created to provide a structural model of the business problem domain. Business process models describe different activities that support a business process, which typically cut across functional departments (and from an object-oriented perspective cut across multiple objects). One problem with process models (from object-oriented perspective) is that they reinforce a functional decomposition mindset. But, used properly they are a powerful tool for communicating an analysts understanding of requirements with the user. Activity diagrams can be viewed as sophisticated data flow diagrams (I think more like sophisticated flowcharts). Unlike data flow diagrams, activity diagrams include notation that addresses the modeling of parallel, concurrent activities and complex decision processes. Can be used to model high or low level business processes (we will use data flow diagram to model high and intermediate processes and activity diagrams to do lower level processes).

Use Case
Origin of Use Cases Ivar Jacobson in 1992 at Ericsson in Sweden Jacobson used use cases as part of overall system development Use cases part of UML (Unified Modeling Language) Use cases are discrete activities that the users perform such as sell CDs, order CDs, and accept returned CDs. (Notice verb/object naming convention). More specifically: Use cases are text descriptions of interactions between some outside actor and a computer system. Use case diagrams are graphical depictions of the relationship Documented in a way that users can easily interpret Written in user language Use cases drive not only requirements gathering, but the entire software development circle Keep small number of use cases Use case diagrams show relationships Definition A use case represents a series of interactions between an outside entity and the system which ends by providing business value.

Actors and Roles Definition: An actor is an outside entity that interacts with the system. Associations exist between an actor and a use case, between use cases, and between actors. Generalization when several uses cases have something in common that can be abstracted into another higher-level use case. Two actors can be generalized into a super actor such as the Customer Service Rep and Field Service Rep can be generalized as a Service Rep. Extend - Use case association <<extend>> indicates a relationship in which a special use case extends an original use case and is useful when certain special use cases would clutter up the original use case (it changes the interaction with the actor in some tangible way that would be cumbersome to include in the original use case). For example in Figure 2.12, Schedule Recurring Customer Appointment extends the functionality of the Schedule Customer Appointment. In this case, the actor might need to input the number of recurring appointments or the date recurring appointments should stop recurring. This interaction would not be in the original use case. The extending use case is a special case of the extended use case and would not exist without the extended use case.

Include - The <<include>> association allows use case designers to avoid duplicating steps across multiple use cases. For example in Figure 2.12, Enter Costume Order, Schedule Customer Appointment, and Enter Uniform Order have some similar steps that can be drawn out into a separate use case called Schedule Designer. These separate use cases may also have common pieces that could become separate use cases with include associations back to the owning use cases.

Note: the author warns against using these techniques so I would not rely on these techniques too extensively. Granularity You can describe a system in a few or a great many use cases. The fewer the use cases, the coarser the granularity of each use case. The granularity you choose for documenting requirements must facilitate division of work among analysts. Remember: too fine a granularity may not be able to provide true business value in one use case and make it difficult to grasp a business concept (too much information so one cannot see total picture). Too coarse a granularity increases complexity (design at too high a level to be informative) and decreases readability. Identify Triggers and Preconditions In developing use cases, determining the use case trigger (the impulse or event that initiates a use case) is an important task in developing use cases. Preconditions describe a mandatory state of the system for inception of the use case. There are three parts of a use case that can be easily confused: an include association, a precondition, and an assumption. When include association does not provide value to an actor, it is only an intermediate step used by use cases. Use cases provide simple descriptions of a systems functions from a birds-eye view of the users, showing what the users can do and how the system should respond to users actions. Note: Nonfunctional requirements, such as reliability and performance requirements, are documented outside the use case through more traditional requirements documents. Use cases are the primary drivers for all the UML diagramming techniques communicating on a higher level what the system needs to do. Other techniques build on use cases by presenting use case functionality in a different way. Each use case describes only one function (one and only one role that users have in system). However, a use case may contain several paths that a user can take while interacting with a system. For example, when searching for a book the search may be conducted using subject, author, or title. Each possible execution path through a use case is referred to as a scenario (an instantiation of a specific use case).

A good place to look for potential us cases is the activity diagram representation of a business process with activities in activity diagram becoming use cases. (Note: instead of activity diagram, we will use data flow diagram to identify use cases in this class). It is possible that multiple users will play the same role, as such use cases should be associated with the roles played by users and not with the users themselves. A use-case description has three basic parts: overview information, relationships, and flow of events. a Use Case Name (should be a noun verb phrase) and a Use Case should be provided a use-case ID number. The primary actor is usually the trigger of the use case and a single sentence description (the essence of use case) is also provided. A use case may have multiple stakeholders (have an interest in use case) and use cases list each stakeholder with each ones interest in the use case. Each use case typically has a trigger (causes use case to begin) which may be external (customer placing order) or temporal (book overdue). There are four basic types of relationships: association, extend, include, and generalization. An association relationship documents the communication that takes place between the use case and the actors that use the use case. All actors involved in use case are documented with the association relationship. An extend relationship represents the extension of functionality of the use case to incorporate optional behavior. For example, a make appointment use case conditionally uses a create new patient use case which is not part of the normal flow of events and should be modeled with an extend relationship and an alternate/exceptional flow description. An include relationship enables functional decomposition (breaking up of a complex use case into several simpler ones). The include relationship also enables parts of use cases to be reused by creating them as separate use cases.

The generalization relationship allows use cases to support inheritance. For example, the make appointment use case could be changed (to allow greater specialization) such that a new patient would interact with make new patient appointment use case and an old patient would interact with a make old patient appointment use case. Then the common (generalized) behavior would be placed in a generalized make payment arrangements use case. (i.e. make old patient appt and make new patient Appt would inherit the make payment arrangements use case). Finally, the individual steps within a business process are described in a use case description. There are three different categories of steps (flows of events) that can be documented: normal flow of events, subflows, and alternate, or exceptional, flows. Note: in some cases, the normal flow of events should be decomposed into a set of subflows to keep the normal flow of events as simple as possible. Subflows are often based on the control flow logic in the activity diagram representation of the business process. Alternately, a subflow could be replaced with a separate use case that could be incorporated via the include relationship. Note: Alternate or exceptional flows are ones that happen but are not the norm. As with subflows, alternate flows can be replaced by separate use case and could be integrated via the extend relationship. Guidelines for writing use case flow of events: a) write each individual step in the form subject-verb-direct object and, optionally preposition-indirect object (SVDPI sentence). b) make clear who or what is the initiator of the action and who is the receiver of the action in each step. Normally, the initiator is the subject and the receiver the direct object. Example the patient provides the receptionist with his her name and address. c) write each step at same level of abstraction (each step should make about the same amount of progress toward completing the use case). d) each use case represents a transaction and should comprise four parts: 1) execution of use case is initiated by a request to the system (input); 2) system ensures that request (data) is valid; 3) system processes the request (and the data) which may change its internal state (process); and 4) system sends the primary actor the result of processing (output). IPO

Note: follow KISS principle and avoid use cases that are too complex (decompose into set of use cases or decompose normal flow into subflows. Additionally, care must be taken to not decompose too much. Most decomposition should be done with classes. Finally, because steps are written in simple English for steps being repeated simply write: Repeat steps A through E. The use case diagram summarizes in one picture all the use cases for the part of the system being modeled and is drawn early in SDLC. A use-case diagram illustrates in a very simple way the main functions of system and the different kinds of users that will interact with it. An actor is not a specific user. Instead it represents a role that a user can play (stick figure used) or another system the current system interacts (rectangle containing <<actor>> and name of the system used). Actors can provide input, receive output or both. Use cases are connected to actors through association relationships which are depicted through a line between actor and use case. Communication is normally twoway but if one-way a solid arrowhead is used to show direction of the flow of information. Also an asterisk (*) can be used at either end (or both ends) to show multiplicity (eg. patient can make many appointments or system can make appointments for many patients). A use case which is depicted by an oval is a major process that the system will perform which benefits actor(s) in some way and is labeled with verb-noun phrase. There are times when a use case includes, extends, or generalizes another use case in the diagram and these are shown using include, extend, and generalization relationships. To increase the ease of understanding a higher-level use case is drawn above the lower-level ones.

Real Estate Management Example

Activity diagram
Sequence diagrams, state transition diagrams, and activity diagrams are dynamic modeling tools which can help a system analyst understand how objects behave and interact with the system. An activity diagram resembles a horizontal flow chart and shows the order in which the actions take place. They also can display multiple use cases in the form of a grid, where classes are shown as vertical bars and actions appear as horizontal arrows. Activity diagrams show the procedural flow of control between two or more class objects while processing an activity and, when used with lower-level system processes, are associated to a use case. In fact, an activity diagram is used to visually represent the behavior which is described in the use case specification. Activity diagrams describe the state of activities by showing the sequence of activities performed and can show activities that are conditional or parallel. When to Use: Activity Diagrams Activity diagrams should be used in conjunction with other modeling techniques such as interaction diagrams and state diagrams. The main reason to use activity diagrams is to model the workflow behind the system being designed. Activity Diagrams are also useful for: analyzing a use case by describing what actions need to take place and

when they should occur; describing a complicated sequential algorithm; and modeling applications with parallel processes. However, activity diagrams should not take the place of interaction diagrams and state diagrams. This is because activity diagrams do not give detail about how objects behave or how objects collaborate. Elements of an Activity diagram Activities should have a name that begins with a verb and ends with a noun (e.g. make appointment). The only difference between an action and an activity is that an activity can be decomposed further and an action represents a simple nondecomposable piece of the overall behavior being modeled. Activities and actions typically modify or transform objects. Object nodes model these objects in an activity diagram (portrayed as rectangles with the name of the object written inside the rectangle -- name of a class, a noun). Object nodes represent the flow of information from one activity to another. There are two different types of flows within an activity diagram: control and object. Control flows model the paths of execution through a business process (portrayed as solid line). Object flows show the actual objects that flow into and out of the actions or activities (depicted as a dashed line with arrowhead showing direction of flow. An individual object flow must be attached to an action or activity on one end and an object node on the other end. There are seven different types of control nodes in an activity diagram: 1) initial activity (small, filled in circle that portrays beginning of a set of actions or activities), 2) final-activity (used to stop process being modeled circle surrounding small filled in circle {bulls eye}, 3) final-flow (similar to final activity node except it stops a specific path of execution through a business process but allows parallel paths to continue), 4) decision (represents test condition), 5) merge (used to bring back together multiple mutually exclusive paths), 6) fork (used to split behavior of business process into multiple parallel flows), and 7) join (brings back together concurrent flows in a business process). Note: each path exiting decision node must be labeled with a guard condition which represents the value of the test for a particular path. Note: If merge node causes diagram to become confusing, a decision node can serve double duty and act as merge node too. Swimlanes break up an activity diagram to illustrate the responsibilities of objects or individuals performing the activity. Vertical (top-down) or horizontal (left-to-right) swimlanes can be used. When modeling high-level business processes or workflows only the most important decisions should be included. Also, the guard conditions associated with outflows of

decision nodes should form a complete set, and only forks and joins of important parallel activities should be shown. Minimize line crossings in activity diagram to enhance readability. Avoid miracle activities (outflow but no inflow) or black hole activities (inflow but no outflow). Element and its description Initial Activity: This shows the starting point or first activity of the flow. Denoted by a solid circle. This is similar to the notation used for Initial State. Activity: Represented by a rectangle with rounded (almost oval) edges. Decisions: Similar to flowcharts, a logic where a decision is to be made is depicted by a diamond, with the options written on either sides of the arrows emerging from the diamond, within box brackets. Signal: When an activity sends or receives a message, that activity is called a signal. Signals are of two types: Input signal (Message receiving activity) shown by a concave polygon and Output signal (Message sending activity) shown by a convex polygon. Concurrent Activities: Some activities occur simultaneously or in parallel. Such activities are called concurrent activities. For example, listening to the lecturer and looking at the blackboard is a parallel activity. This is represented by a horizontal split (thick dark line) and the two concurrent activities next to each other, and the horizontal line again to show the end of the parallel activity. Final Activity: The end of the Activity diagram is shown by a bull's eye symbol, also called as a final activity. Symbol

How to Draw: Activity Diagrams Activity diagrams show the flow of activities through the system. Diagrams are read from top to bottom and have branches and forks to describe conditions and parallel

activities. A fork is used when multiple activities are occurring at the same time. The diagram below shows a fork after activity1. This indicates that both activity2 and activity3 are occurring at the same time. After activity2 there is a branch. The branch describes what activities will take place based on a set of conditions. All branches at some point are followed by a merge to indicate the end of the conditional behavior started by that branch. After the merge all of the parallel activities must be combined by a join started before transitioning into the final activity state.

Below is a possible activity diagram for processing an order. The diagram shows the flow of actions in the system's workflow. Once the order is received the activities split into two parallel sets of activities. One side fills and sends the order while the other handles the billing. On the Fill Order side, the method of delivery is decided conditionally. Depending on the condition either the Overnight Delivery activity or the Regular Delivery activity is performed. Finally the parallel activities combine to close the order.

Swim Lanes Activity diagrams provide another ability, to clarify which actor performs which activity. When modeling workflows of business processes it is helpful to partition the activity within the diagram into groups. Each group will represent the business organization responsible for those activities. The group is called a swim lane. Consider the Activity diagram in previous figure. Were we to break down the activities further, we can break up the activity of overnight delivery to "checking customer information, " while checking, wait for computer starting, inform the overnight delivery person, and so forth. The activity of regular delivery would involve check customer information, wait for delivery person stop by, inform the person of the requirement, and finally give the order. In this, you can see that two more actors are involved, one is the overnight delivery person, and the other is the regular delivery person. If you wish to distinguish in an Activity diagram the activities carried out by individual actors, vertical columns are first made, separated by thick vertical black lines, termed "swim lanes," and name each of these columns with the name of the actor involved. You place each of the activities below the actor performing these activities and then show how these activities are connected.

CIS380 OOAA Free Book Part 2

Relationships Among Objects and Classes


Hierarchy
A characteristic of the object-oriented paradigm is to allow classes to be ordered in hierarchies. We distinguish three forms of ordering: Subclassing Subtyping Superclass Subclassing is a dependency relationship among classes as modules. Subclassing is a syntactic relationship. It supports reusability. New behaviors can be defined by leveraging off existing ones. Subclassing is usually obtained by inheritance, an implementation mechanism for sharing code and representation. Inheritance is a language feature provided to build new classes by incremental modification of one or more existing classes. A descendant is a class derived from one (single inheritance) or several (multiple inheritance) parent classes (its parents). A descendant may add new properties, modify existing properties (redefinition), or even remove properties from its parent classes. Both classes share their similarities while preserving their differences. Usually, all classes are derived from an implicit or explicit root class that defines standard methods such as equality or copy. The set of all classes derived directly or indirectly from a given class, called the root class, forms a hierarchy. Subtyping is a semantic relationship among classes as types. Intuitively, a subtype is one whose objects provide all the behavior of objects of another type, the supertype , plus something extra. Subtyping supports the conformance of an object to a set of types related by a subtyping relationship. As for subclassing, a class can be a subtype of more than one class (multiple subtyping). The subtype relationship is based on the idea of substitution. Since objects of a supertype share the properties of their parents, they can be used wherever an object of the type of the parent can appear. Superclass is a class from which other classes are derived. A superclass is also called a parent class or base class. The classes that are derived from a superclass are known as child classes, derived classes, or subclasses. We can also say that a class A extends class B when A is a subclass of B.

Inheritance
Enables an object to derive one of more of its attributes from another object.

Example. A is-a B Inheritance is a relationship among classes where one class shares the structure or behavior defined in one or more other classes. Inheritance defines an "is a" hierarchy in which a subclass inherits from a superclass. A subclass typically augments or restricts the existing structure and behavior of the superclass. The contents of the superclass will appear in the subclass. An inheritance relationship is represented by a line with an arrow pointing to the superclass in a class diagram. With single inheritance, each subclass has exactly one superclass. Multiple inheritance allows a subclass to be derived from more than one superclass. Multiple inheritance is used if there is not a single appropriate superclass. The need for multiple inheritance is still being debated. Its potential for great complexity must be considered against its benefits. Two problems of multiple inheritance: 1) Name collisions - when two or more different superclasses use the same name for some element of the interfaces (such as instance variables or methods). 2) Repeated inheritance - when a class is an ancestor of another in more than one way.

Types of relationships: Aggregation and Composition


Aggregation - Exists when an object forms part of another object. e.g. A has-a B has-parts relationship -- is built from or composed of, another; describes the relationship between the "whole" and its component "parts"; more detailed relations can occur requires relationship -- depends on, uses, or implies the knowledge (e.g., derived state) or existence of another (e.g., a precondition or entrance criteria) Aggregation An aggregate is an object that is made up of other objects Therefore aggregation is a has-a relationship A car has a chassis In software, an aggregate object contains references to other objects as instance data The aggregate object is defined in part by the objects that make it up

This is a special kind of dependency the aggregate usually relies on the objects that compose it Special form of association representing part-whole or has-a relationship. Distinguishes the whole (aggregate class) from its parts (component class). No relationship in the lifetime of the aggregate and the components (can exist separately). Advantages of Aggregation simplicity (one object, not many) safety (via encapsulation of the sub-objects) specialization (of the interface) structure (isomorphic to real-world) substitution (replacing sub-objects)

Types of Aggregation static aggregation o the number and organization of the sub-objects are predefined and unvarying dynamic aggregation o the number and/or organization of the sub-objects varies during the lifetime of the aggregation Aggregation Aggregation is a special form of association that connotes a whole/part relationship. The contained object may participate in more than one aggregation relationship, and exits independently of the whole. Figure 1 shows how it is drawn and implemented.

Whole
Figure 1

Part
Aggregation

A whole cannot be its own part. Therefore instances cannot form cycles of aggregations. A single object cannot be an aggregate of itself, two objects cannot be aggregates of each other, and three objects cannot form a ring of aggregation. See Figure 2.

Y
Figure 2 Composition

Illegal cycles of aggregation between instances

Stronger form of aggregation Implies exclusive ownership of the component class by the aggregate class. The lifetime of the components is entirely included in the lifetime of the aggregate (a component can not exist without its aggregate).

Composition is a special form of aggregation, as shown in Figure 3. Again, notice that the implementation is indistinguishable from association. public class Owner { private Ward itsWard; }

Owner
Figure 3

Ward
Composition

The same rule applies to composition that applied to aggregation. There can be no cycles of instances. An owner cannot be its own ward. However, UML provides quite a bit more definition.

An instance of a ward cannot be owned simultaneously by two owners. Note, however, that an owner can transfer ownership of a ward to another owner. The owner is responsible for the lifetime of the ward. If the owner is destroyed, the ward must be destroyed with it. If the owner is copied, the ward must be copied with it.

This website has useful information


http://www.cs.gordon.edu/courses/cs211/lectures-2005/Relationships.pdf Work Cited Martin, Robert C. UML JAVA Programmers. Prentice Hall Professional Technical Reference. New Jersey 07458: Arrington, C. T. Enterprise Java UML. John Wiley & Sons Inc Bowen, Gregory M. SemanticNet Notation: http://members.aol.com/kaizensepg/semantic-net.htm#configuration type#configuration-type

Explanation of Relations Relationship & Goal/Rationale


Has-parts relationship whole-part Identify how the pieces are related to the big picture and to each other Define the composition, the components that make up the whole, may be implemented internally or through delegation

Biological (Wetware) Example


Biology (living organisms) has-parts: zology (animal, fauna) + botany (plant, flora) + microbiology + mycology + other

Hardware Example
automobile has-parts: wheels {4} + doors {2..5} + hood {1} + trunk {0..1} HMMWV has-attributes: light highly mobile

a bird has parts: head == crest + crown + bill + has-parts: throat + auricular region + eyes diesel engine body == breast + scapulars + abdomen four-wheel-drive automatic wings == upper wing coverts + transmission primary feathers + secondary feathers 1.25-ton truck baseline feet [tarsus] chassis tail [rectrix] configuration-type Hummer is-a {civilian version} HMMWV requires: rubber tires and headlights and license tags and title and meeting {safety and emissions and inspection} requirements excludes weaponry [winch]

requires relationship

predator requires prey (for food) prey requires predator (to manage Identify implicit or explicit population size and control disease) assumptions or pre-conditions (things symbiotic or cooperative relationships: that must be TRUE for the concept to parasitism a parasite obtains benefits work or be correct) from a host which it usually injures Identify dependencies (e.g., using commensalism - one obtains food or relationship) other benefits from the other without Dependency may be based at the damage or benefit context level, concept (spec), or content mutualism - mutually beneficial (body, implementation) brown-headed cowbird Excludes x = requires (not x) requires host-nest (e.g., Robins or Catbirds) is-a parasitic egg-layer [exhibits brood parasitism, usually lays one egg in multiple nests, possibly different species, hosts raise chick] louse (genus = Odontophorus) requires host where genus = Phasianidae (e.g., Ring-Necked Pheasant) is-a relationship Maryland-State-Bird is-a Baltimore Oriole is-a Northern Oriole is-a Oriole

example, instance or instantiation, instance-class relationship this-Bird is-a Baltimore Oriole that Hum-Vee is-a M1046 Shows that an object or [it is also an instance of Maryland-State- therefore attribute is an instance of a has-parts TOW Carrier and class of similar individuals or Bird] concepts Identify what makes an individual or example unique

my-car is-a <a 2003 Toyota Corolla> with VIN = xxxxxxxxx is-a car

parent-of relationship

Note: "Inheritance" is more straight forward in biological examples, but require both a father and a mother (at parent-child relationship or least for higher species). Similarities in inheritance relationship features and creating of subspecies can Identify the "roots" of the occur from population isolation and concepts, foundational theories or laws (e.g., that the gene-pool restriction. A number of current concept was based on) notations are used to document genetic relationships. Common charts used in Genealogy include: Describe evolution, history, Descendant chart (parent-of) earlier versions, genealogy, Pedigree chart (has-parents, family derivation, tailoring, tree with individual as root) adaptation Fan chart (same as pedigree, but individual at hub with generations drawn in concentric half circles) Relative chart (both ways near relatives) Timeline (dates on x-axis, names on y-axis)

Note: "Inheritance" in nonbiological systems is not usually as straight forward. Single inheritance (one "parent"), and multiple inheritance, are common and the mechanism may change each "generation." "Inheritance" in non-biological systems is not necessarily the same as the feature found in some programming languages. HMMWV parent-of Hummer Hummer (H1) parent-of H2 [although in concept not content] parent-of H3 Ford Mustang a-kind-of car a-kind-of vehicle descendant-of model-T descendant-of horseless carriage descendant-of stage coach HMMWV sibling Jeep where {jeep.wheelbase = 80-inch and jeep.capacity = 1/4-ton and period = World War II} scout-car has-subclasses: Jeep VW Thing aka German Squad Car HMMWV rail-car has-subclasses: boxcar when cargo = freight reefer when cargo = perishables tanker when cargo = liquid gondola when cargo = bulk commodities parlor car when cargo = passenger dining car when cargo = restaurant caboose when cargo = train crew tender when cargo = fuel and water

sibling relationship

A typical field guide identifies: (1) key features that are consistently present within a species and critical in has-subclasses relationship (opposite of a-kind-of) shows differentiating it from other species; (2) similar species, which may be easily the metaclass and all confused with the species. subclassses Identify differences and varieties Identify the key identifiers or attributes that distinguish similar things in peer-to-peer or class-class relationships Individuals or subclasses within a class Northern-Oriole (American) hassubclasses (i.e., has subspecies): Baltimore Oriole (I. galbula galbula) male has a solid black head and the female usually has an olive-brown back and orange-yellow underside Bullock's Oriole (I. galbula bullockii) the male has a black crown and black line through the eye and the female has a Identify the trade-offs between yellowish head and breast alternatives

Combining Relations
this-object is-a Craftsman brand 13-15mm metric un-insolated double-open-ended hand-wrench [class] with the owner's drivers license number engraved on the handle wrench has-attributes: manufacturer has-subclasses: hand-wrench multiple-inheritance a-kind-of hand-tool has-attributes: wrench-handle = o insolated [metal] | o un-insolated [metal] | o other has-subclasses: o adjustable monkey-wrench - one fixed and one adjustable jaw at right angles to a straight handle crescent-wrench - adjustable open-end socket wrench a-kind-of ratchet (aka ratchet wrench, or ratchet) a bar and removable socket fixed where size = constant, units = inches | mm Allen wrench - L-shaped hexagonal metal bar [double] open-end wrench [double] closed-end wrench combo-wrench where openend.size = closed-end.size

tool-box has-parts: box lid tray contents {0..n} tools has-attributes: size + color + construction material + manufacturer + other

o o

tools can-be pliers & screw-drivers & wrenches & other hand-tool a-kind-of tool where power = "muscle grease"

pliers a-kind-of hand-tool hasparts: {2} handles {2} jaws pivot point {1 or adjustable} pliers-type pliers-type can-be [standard] where jaws = grip Vice Grip (Brand) where pivot point = adjustable and handle.type = locking electrical where jaw.type = pincer (cutting edge) needle-nose where jaws = narrow small-toothed grip

power-wrench a-kind-of ratchet has-subclasses: o Air wrench [context] requires air compressor + hose [content] requires quick-connect o Electric wrench [context] requires electric power + cables [content] requires polarized plug or 3-prong plug o Battery wrench [content] rechargeable requires charger replaceable requires batteries

pipe wrench a-kind-of monkey wrench [for gripping and turning a cylindrical object] monkey wrench sibling crescent wrench with {adjustable jaw not at right angle to handle}

http://lglwww.epfl.ch/Team/SB/PhD/html/phd.e.html

Relationships among Objects-continued


Two kinds of hierarchies are of particular interest in object-oriented analysis and design: Links (seniority) Aggregation (parent/child)

A link is a physical or conceptual connection between objects. Objects collaborate with each other through links. A link denotes the specific association through which one object applies the services of another. Message passing between two objects is usually unidirectional, although it can be bi-directional. Links denote a peer-to-peer or client-supplier relationship. Aggregation denotes a whole-part relationship. Aggregation can encapsulate parts as secrets of the whole (information hiding). Links can permit looser coupling among objects. The types of relations include: Association Inheritance Aggregation Association Association suggests bi-directional navigation. Two classes which refer to the other. The most general form of relationship and the most semantically weak. Cardinality of association indicates the number of times each instance of a class appears. Association denotes a semantic dependency and does not state a direction, nor does it state the exact way in which one class relates to another (unlike most of the other class relationships). The creation of an association allows us to capture the participants in a semantic relationship, their roles, and cardinality. An association is represented by an unadorned line in class diagrams. This is a use of a data member which does not correspond to aggregation.

An association is drawn as an edge connecting two classes. Either end of the edge may be decorated with an identifying name and an arty, indicating how many associated objects there may be. Associations may be One-One, One-Many, or Many-Many.

Aggregation Aggregation is a whole/part relationship. Containment by value is a type of physical containment. The contained part does not exist independently of the enclosing object. When the whole object is destroyed, its parts are also destroyed. A less direct kind of aggregation is containment by reference. The contained part is not physically in the whole, it must be accessed by reference. The objects are not so tightly coupled (one may be destroyed without the other being affected). Only containment by reference may be cyclic (eg. A shareholder owns stocks, but does not physically contain the stocks. The lifetime of the objects is independent although they are conceptually a whole/part relationship. When choosing between inheritance or aggregation remember that there must be an "is a" relationship for inheritance.

Links denote peer-to-peer or client/server relationships. Aggregation denotes the whole/part hierarchy

Aggregation need not describe physical containment. The whole/part relationship may be of a conceptual nature. Consider a bank account's owner. A person is not a physical part of a bank account. By implication, each object has a link to its aggregate elements. Aggregation represents the has-a relation. It represents physical or logical containment. In a class diagram, an aggregation is represented by drawing an edge with a large dark circle on the end which contains objects at the other end. Don't confuse aggregation with inheritance. New O-O programmers yearn to introduce inheritance where it is unnecessary.

Coupling and Cohesion


A good design is one that balances trade-offs to minimize the total cost of the system over its entire life, and issues of coupling, cohesion and connascence are relevant.

Coupling refers to how interdependent or interrelated the modules (classes, objects, and methods) are in the system, and there are two types of coupling to consider: interaction and inheritance. Interaction coupling deals with the coupling among methods and objects through message passing. It is believed that this type of coupling should be minimized by minimizing the number of objects that can receive messages from a given object, and objects should send messages only to one of the following: 1) itself, 2) an object that is contained in an attribute of one of its superclasses, 3) an object that is passed as a parameter to its method, and 4) an object that is created by the method.

There are six types of interaction coupling each falling on different parts of the good-to-bad continuum. The best coupling is no direct coupling (methods do not call one another). Next best is data coupling in which the calling method passes a variable to the called method, and, if a composite method, the method uses the whole variable. (it is slightly worse coupling to use only part of a composite variable). Next best form of coupling is when calling method passes a control variable whose variable will control the execution of the called method. A bad form of coupling is when a method refers to a global variable outside the individual object, and the worst form is when a method refers to the hidden parts of another object. In general, interaction coupling should be minimized. The one possible exception is that non-problem domain classes must be coupled to their corresponding problem-domain classes. However, problem-domain classes should never be coupled to non-problem-domain classes. Inheritance coupling deals with how tightly coupled the classes are in an inheritance hierarchy. While it was formerly thought that inheritance coupling was desirable, with problems with inheritance conflicts, redefinition capabilities, and dynamic binding, a high level of inheritance coupling may not be a good thing. Most problems with inheritance involve the ability within the object-oriented programming languages to violate encapsulation and information-hiding principles. The best way to solve this conundrum is to ensure (a-kind-of) semantics and the principle of substitutability. All other uses should be avoided. Coupling is the extent to which subsystems are dependent on each other. Subsystems should be as independent as possible. If one subsystem fails and other subsystems are highly dependent on it, the others will either fail themselves or have problems functioning. For example, the components of a portable CD player are tightly coupled. The amplifier and the unit that reads the CD signal are wired together in the same container, and the boundaries between these two subsystems may be difficult to draw clearly. If one subsystem fails, the entire CD player must be sent off for repair. In a home stereo system, the components are loosely coupled since the subsystems, such as the speakers, the amplifier, the receiver, and the CD player, are all physically separate and function independently. So if the speakers in a home stereo system fail, only the speakers need to be repaired. Coupling is a notion borrowed from structured design, but with a library interpretation it also applies to object-oriented. Coupling has been defined as the measure of the strength of association established by a connection from one module to another. Strong coupling complicates a system since a module is harder to understand, change, or correct by itself if it is highly interrelated with other modules. Complexity can be reduced by designing system with the weakest possible coupling between modules. A counterexample to good coupling is a modular stereo system in which the power supply is located in one of the speaker cabinets.

Coupling with regard to modules is still applicable to object oriented analysis and design, but coupling with regard to classes and objects is equally important. However, there is tension between the concepts of coupling and inheritance, because inheritance introduces significant coupling. While weak coupled classes are desirable, inheritance (tightly couples super classes and their subclasses) exploits the commonality among abstractions. Cohesion refers to how single-minded a module (class, object, or method) is within a system. A class or object should represent only one thing. With respect to method cohesion, a method should solve only a single task (should do one and only one thing). This is called functional cohesion. In general, method cohesion should be maximized, and there is a range of cohesion from good cohesion (functional) to bad cohesion (coincidental cohesion in which method performs multiple unrelated functions). Sequential cohesion is the next best cohesion after functional cohesion and combines two functions in which the output of one function serves as input to the other. Sequential cohesion is followed by communicational cohesion in which two functions use the same attributes to execute, and then by procedural cohesion in which a method supports two weakly related functions. Next is temporal cohesion in which a method supports multiple time related functions such as initialization of all attributes, and logical cohesion in which method supports multiple related functions but the choice is based on the value of a control variable. With respect to class cohesion (the level of cohesion among the attributes and methods of a class), a class should represent only one thing such as employee, department, or order. All attributes and methods contained in a class should be required to represent the thing. There should be no attributes or methods that are never used (only attributes and methods necessary for the problem at hand). Furthermore, a cohesive class should contain multiple methods (it makes little sense to have a single-method class) and each visible method should perform a single function (functional cohesion). Generalization/specialization cohesion addresses the sensibility of the inheritance hierarchy. In early days of object-oriented programming, when the programmer saw that there were some common properties that a set of classes shared, the programmer would create an artificial abstraction that defined the commonalities. While useful in a reuse sense, it turned out to cause many maintenance nightmares. Today, it is understood that highly cohesive inheritance hierarchies should support only the semantics of generalization and specialization (a-kind-of) and the principle of substitutability. Cohesion is the extent to which a subsystem performs a single function. In biological systems, subsystems tend to be well differentiated and thus very cohesive. In man-made systems, subsystems are not always as cohesive as they should be. The idea of cohesion comes from structured design too. Cohesion measures the degree of connectivity among the elements of a single module. The least desirable form of cohesion is coincidental cohesion in which unrelated abstractions are thrown into the same class or module. Example, think a class comprising the abstractions of cats and

vehicles. The most desirable form of cohesion is functional cohesion, which the elements of a class or module all work together to provide some well bounded behavior. Thus, the class cat is functionally cohesive if its semantics embrace the behavior of a cat; the whole cat, and nothing but the cat. Closely related to coupling and cohesion are the criteria that a module or class would be sufficient and complete. Sufficient mean that the module or class captures enough characteristic of the abstraction to permit meaningful and efficient interaction. Doing otherwise renders the component useless. Example, designing the class set, it is wise to include an operation that removes an item from the set. In practice, violations of this characteristic are detected very. Complete means that the interface of module or class captures all of the meaningful characteristics of the abstraction. Whereas sufficiency implies a minimal interface, a complete module or class is one whose interface is general enough to be commonly usable to any client. Completeness is a subjective matter, and it can be overdone.

Polymorphism
The Crunch Polymorphism, a term that implies many changes, literally means the capacity to assume many shapes. What does this mean for object oriented programming? Through the notion of polymorphism, programming code is minimized as well as reusable, system performance goes up, and there are no trade-offs, which usually occur in any situation where you substitute one method for another. There are two essentially different types of polymorphism. Ad-hoc polymorphism refers to the notion of overloading, which can allow multiple functions that take dissimilar types to be defined with the same name. Even with the same name, the compiler routinely calls on the correct function. This type of polymorphism is very familiar in object-oriented programming, which allows operators to be overloaded in such a way that is parallel to functions. The big benefit of overloading is the emergence of specialization. For example, a function with an identical name can be implemented in numerous different ways, each optimized for the particular data types that it operates on. Parametric polymorphism refers to a function or data type that can be written generically so that it can deal uniformly well with any objects devoid of depending on their type. Subtyping polymorphism employs the design of subtypes to limit the range of types that can be used in a particular case of parametric polymorphism. Object-oriented programming languages offer subtyping polymorphism using subclassing, also known as inheritance. The Fluff

The main benefit of polymorphism is localizing programming activity and supporting application maintainability. Advantages, with regards to message handling include more readable code, extendable code, improved system performance and trade-off free. Usually with anything that substitutes for something else, a series of trade-offs are expected. However, having more readable code, an improved performance boost in the system, and a more extendable code are all benefits from polymorphism that do not contain drawbacks. Advocates of object-oriented programming often cite polymorphism as one of the major benefits of the concept and idea of O programming. The rise in popularity of OO programming languages did contribute greatly to the awareness and use of polymorphism in the mainstream programming community.

Examples The print shape example from the textbook, The Object-Oriented Thought Process, provides a very easy to understand concept of polymorphisms basics. The Shape Hierarchy We start with the basic class, shape. It is an abstract class with generic attributes, which are those that identify that it is a shape. Underneath the shape class, we have three subclasses: circle, star, and square. Each of these classes inherits the traits of their parent class, shape. This is also an example of the is-a relationship. Since, in fact, circle is a shape, just as star is a shape. Our goal is to execute the program to print the circle shape. In procedural programming, there would be specific lines of code within the program that specifies exactly what it is to print. Whereas, with the concept of polymorphism, the shape object just interacts with the circle object, and even though there may be a print command coded into shape, the circle object has its own embedded code and methods, thus overwriting the generic print command from shape and using the print command contained within circle. The beauty of this is that we can use the same generic print command in shape and have it interact with star, enabling the star to print, even though it was the exact same code used to print circle. This same method will also work for square, or any other subclass under the shape hierarchy.

Another example of polymorphism comes from the article, Polymorphism: A Shape of Things to Come, by Barrie Grey, published in Computing Canada. It uses an employee hierarchy, similar to that of our shape hierarchy, with the intentions of calculating payroll for every employee with a single click. The Employee Class Hierarchy We start this example of polymorphism by providing a superclass called employee. The employee class will include attributes that can be similar for every employee. These can include age, gender, hire date, address, phone, social security number, etc. We now can branch out to two tier-1 classes, hourly employee and salaried employee. The salaried employee class could further be divided into derived subclasses, manager, salesperson, and general staff. These sub-classes of salaried employee would be classified as tier-2 classes. Each of our classes has different rules for the determination of employee payment. So each class needs to be embedded with its own calculate pay function. Polymorphism allows us to send a generic calculate pay function from our tier-0 class, employee, to any of our subclasses, where the chosen sub-class will receive the request from the employee class, and override the calculate pay function with one of its own. So if we needed to find out how much to pay a manager, we would have our employee class send a request with a generic calculate pay function to our manager class, which, again, has its own calculate pay method embedded within the object.

Class Responsibility Collaboration (CRC) Cards


Class responsibility collaboration (CRC) cards are a method of designing objects and the relationships between them. CRC cards work by taking people through programming episodes together and ultimately allow larger groups of people working together to feel this dialogue which is based on repeated episodes of decision making. The most basic way to do this write on 3 x 5 or 4 x 6 index cards the name of the class, as well as the responsibilities and collaborators expected for each class to be used in a program. Below in Figure 1, the layout of a typical CRC card can be seen.

ClassName Responsibilities

Collaborators

Figure 1

The name of the class, which appears at the top-left of the CRC card, is the main identifier of the CRC card and of the class itself. The ClassName may be placed on other

CRC cards as a Collaborator. Under the ClassName will be a bulleted list of responsibilities. A responsibility can be defined as anything that a class knows or does. Finally collaborators are placed on the right-hand side of the CRC card. Collaborations are identified as a request for information or a request to do something, and are linked to other classes. To create CRC models, there are four iterative steps one must follow: Find Classes. Classes identify the building blocks for your application

Find Responsibilities. Ask yourself what a class does as well as what information you wish to maintain about it. Define Collaborators. Because a class rarely has sufficient information to fulfill its responsibilities, it must collaborate with other classes to get the job done. To identify the collaborators of a class, ask yourself does the class have the ability to fulfill this responsibility? If it does not then it will need a collaborator that will fulfill the responsibilitys need. Move the Cards Around. The cards should be placed in an intelligent manner on a table or chalkboard. If two cards collaborate with one another, then they should be placed close together. Similarly, if two cards dont collaborate, they should be placed far apart (Ambler 1995).

Even though the idea of CRC cards is relatively new, the object-oriented programming languages and methods they are meant to simplify are not. ObjectOriented programming started with SIMULA I and SIMULA 67 in the mid 1960s, with SIMULA 67 introducing most of the key concepts of object-oriented programming: classes, objects, and subclasses (Dahl & Nyggard, 1965). Compared to the previous structured standard, the object-oriented thought process demanded an entirely new mindset which relied heavily on relationships. Within the last twenty years, CRC cards have developed into an integral tool for teaching the object-oriented thought process, expanding on the relationships by focusing on class responsibilities and ultimately its collaborations with other classes. Works Cited Ambler, Scott W. (1995). The Object Primer Agile Model-Driven Development with UML 2.0. [Electronic Version]. Retrieved February 8, 2007 from http://www.agilemodeling.com/artifacts/crcModel.htm Beck, Kent (1989). A Laboratory for Teaching Object-Oriented Thinking. [Electronic Version]. Retrieved February 8, 2007 from http://c2.com/doc/oopsla89/paper.html Cunningham, Ward (1994). OOPSLA 94 Workshop #12 How Do Teams Shape Objects? How Do Objects Shape Teams? [Electronic Version]. Retrieved February 8, 2007 from http://c2.com/doc/oopsla94.html Dahl, Ole-Johan & Nygaard, Kristen (1965). How Object-Oriented Programming Started. Retrieved April 9, 2007 from http://heim.ifi.uio.no/~kristen/FORSKNINGSDOK_MAPPE/F_OO_start.html

Structural Modeling
Structural Modeling A structural, or conceptual, model describes the structure of the data that supports the business processes in an organization and presents the logical organization of data without indicating how the data are stored, created, or manipulated. It illustrates people, places, or things about which information is captured and how they are related to each other. Drawing the structural model is an iterative process that spans the analysis and design stages of the systems development cycle. In analysis, analysts draw a conceptual model which shows the logical organization of the objects without indicating how they are stored, etc. In design, analysts evolve the conceptual structural model into a design model that reflects how the objects are organized in databases and files. The structural model (Class Diagram) creates a vocabulary that can be used by the analysts and users but does not represent the software components or classes in an object-oriented programming language. Instead, it represents the responsibilities of each class and the collaborations between the classes. The basic elements of the structural model include: classes, attributes, operations, and relationships. A class is a general template that is used to create specific instances, or objects, in the problem domain. All objects of a given class are identical in structure and behavior but contain different data in their attributes. Abstract classes do not exist in the real world. For example an employee class and a customer class may be generalized into a person class but only the employee and customer classes are instantiated. A second classification of classes is the type of real-world thing that a class represents. For example, there are domain classes, user interface classes, data structure classes, operating environment classes, multimedia classes, and document classes. Initially, the process is only interested in domain classes and later in design processes the other type become more relevant. For example, it is normally required that classes provide a means of creating, deleting, accessing and setting individual attribute values. However, early on, to avoid cluttering the definition of the class with these basic type of operations, the analyst focuses on problem domain-specific operations. There are three basic categories of data abstraction mechanisms: generalization relationships, aggregation relationships, and association relationships. Generalization is represented with the a-kind-of relationship and allows an analyst to create classes that inherit attributes and operations of other classes. A superclass contains the basic attributes and operations that will be used in several subclasses. This reduces redundancy in class definitions so that common elements are defined once and then reused in the subclasses. Also the flipside of generalization is specialization in which new subclasses are created from an existing class. To

ensure that the semantics of subclasses are maintained the analyst should apply the principle of substitutability (subclass can be used anywhere superclass is used and is applied by focusing on the a-kind-of interpretation). Different types of aggregation relationships have been proposed in data modeling, knowledge representation, and linguistics. For example, including such concepts as: a-part-of (logically or physically), a-member-of (set membership), contained-in, related-to, and associated-with. These relate parts to wholes or parts to assemblies (a-part-of or has-a semantic relationship), and aggregation relationships (as can generalization relationships) can be combined into hierarchies. Aggregation relationships are bidirectional and its flipside is decomposition. Association relationships are a weaker form of the aggregation relationship. For example, although a patient is a part-of an appointment, there is a clear semantic difference between this type of relationship and the part-whole notion of relationship. Responsibilities of a class can be broken into two separate types: knowing and doing. Knowing responsibilities are those things the instance of a class must be capable of knowing (such as the value of its attributes and its relationships). Doing responsibilities are the things an instance of a class must be capable of doing. The structural model describes the objects necessary to support the business processes modeled by the use cases. Most use cases involve a set of several classes, and these classes form collaboration and allow the analyst to think of terms of clients, servers, and contracts. A client object is an instance of a class that sends a request to an instance of another class. The server object receives the request, and a contract formalizes the interaction between the client and server objects. For example, a patient makes an appointment with a doctor and requires both to appear at an appointed time. The following sections briefly introduce the various structural modeling diagrams provided by the UML.

Class diagrams
A class diagram is a static model that shows the classes and the relationships among classes that remain constant. Its main building block is the class which refers to the people, places, events, and things about which the system will capture information. Later, during the design and implementation stages of the systems development life cycle, classes can refer to implementation-specific artifacts such as windows, forms, and other objects to build the system. Furthermore, the attributes of a class and their values define the state of each object created from the class, and the behavior is represented by the operations. Attributes of a class can be calculated or derived (denoted by putting slash (/) in front of

it in class diagram. Attributes can be either public (+), protected (#), or private (-). A public attribute is not hidden from any object, a protected attribute is hidden from all classes except its subclasses, and a private attribute is hidden from all other classes. In a class diagram the functions that are available to all classes (e.g., create a new instance, return a value of a particular attribute, delete an instance) are not explicitly shown within the class rectangle. Only operations unique to class are shown. Within a class rectangle, operations are followed by parentheses which contain the parameter(s) needed by the operation. If an operation has no parameters, the parentheses are still shown but are empty. A primary purpose of a class diagram is to show the relationships, or associations, that classes have with one another. These are depicted on the diagram by drawing lines between classes. The line is labeled with either the name of the relationship (e.g. associated with) or the roles the classes play in the relationship (e.g., schedules), and a solid triangle is placed next to name which allows a direction to be associated with the name of the relationship indicating the way the relationship is to be read. For example a line between the patient and appointment classes is labeled schedules and > triangle shows it should be read as patient schedules appointment. The plus (+) sign is placed before the label to communicate that it is a role as opposed to a relationship name. Relationships also have multiplicity which documents how an instance of an object can be associated with other instances. There are times when a relationship itself has associated properties, especially when its classes share many-to-many relationship. In these cases, a class called an association class is formed, which has its own attributes and operations. The association class is shown as a rectangle that is attached to the association path with a dashed line. Another way to decide when to use an association class is when attributes that belong to the intersection of the two classes involved in the association must be captured. While most relationships between classes are association, there are two special cases of association (generalization and aggregation) that appear quite often. Generalization association shows that one class (subclass) inherits from another class (superclass), and this path is shown with a solid line from the subclass to the superclass and a hollow arrow pointing to the superclass. An aggregation association is used when classes actually comprise other classes, and this relationship is denoted on a class diagram with a solid line with a hollow diamond placed nearest the class representing the aggregation (Healthteam rather than doctor, nurse, and administrative staff). From a UML perspective there are two types of aggregation: aggregation (logical part and fairly easy to remove from whole) and composition (physical and difficult to remove from whole). To differentiate the types of aggregation, composition is denoted by a black diamond.

An object diagram is essentially an instantiation of all or part of a class diagram which means to create an instance of a class with a set of appropriate attribute values. This enables one to think in terms of concrete objects rather than abstract classes. Class diagrams depict the structure of a system in general. Class diagrams have the following types of elements: A class Shown as a solid-outline rectangle labeled with a name, this represents a general concept. An association Shown as a solid-line path labeled with a name, this represents a relationship between classes. An attribute Shown as a text string in a class's second compartment, this represents what objects of the class know. An operation Shown as a text string in a class's third compartment, this represents what objects of the class can do. Figure 2-15 is based on the following paragraphs from the requirements description provided at the beginning of the chapter, and combines many of the sentences discussed in the figures shown earlier in this chapter: A project manager uses the project management system to manage a pro j ect. The project manager leads a team to execute the project within the project's start and end dates. Once a project is created in the project management system, a manager may initiate and later terminate the project due to its completion or for some other reason. As input, a project uses requirements. As output, a project produces a system (or part of a system). The requirements and system are work products: things that are created, used, updated, and elaborated on throughout a project. Every work product has a description, is of some percent complete throughout the effort, and may be validated. However, validation is dependent on the type of work product. For example, the requirements are validated with users in workshops, and the system is validated by being tested against the requirements. Furthermore, requirements may be published using various types of media, including on an intranet or in paper form; and systems may be deployed onto specific platforms. These paragraphs describe some of the classes that make up the project management system. We can communicate this information on a single diagram as shown in Figure 2-15, or by using multiple diagrams, as done throughout the earlier part of

this chapter.

Figure 2-15. Class diagram

A s s o c i a t i o n s . An association defines a type of link and is a general relationship between classes. For example, the project management system involves various general relationships, including manage, lead, execute, input, and output between proj ects, managers, teams, work products, requirements, and systems. Consider, for example, how a project manager leads a team. Binary associations. A binary association relates two classes. For example, one binary relationship in the project management system is between individual workers and their units of work, and another binary relationship is between individual workers and their work products. In a UML class diagram, a binary association is shown as a solid-line path connecting the two related classes. A binary association may be labeled with a name. The name is usually read from left to right and top to bottom; otherwise, it may have a small black solid triangle next to it where the point of the triangle indicates the direction in which to read the name, but the arrow is purely descriptive, and the name of the association should be understood by the classes it relates. Figure 3-9 shows various associations within the project management system using the most basic notation for binary associations. The associations in the figure are as follows: A worker is responsible for work products and performs units of work Units of work consume work products as input and produce work products as output. Notice that a binary association should be named using a verb phrase. Recall that you discover associations by focusing on verbs.

Figure 3-9. Binary associations

Wary associations. An n-ary association relates three or more classes. For example, in the project management system, the use of a worker involves the worker, her units of work, and her associated work products. In a UML class diagram, an n-ary association is shown as a large diamond with solid-line paths from the diamond to each class. An n-ary association may be labeled with a name. The name is read in the same manner as for binary associations, described in the previous section.

Figure 3-10 shows an n-ary association associated with the project management system using the most basic notation for n-ary associations. This association states that utilization involves workers, units of work, and work products. As with a binary association, an n-ary association is also commonly named using a verb phrase. However, this is not always the casefor example, the n-ary Utilization association shown in Figure 3-10 is described using a noun rather than a verb, because it is named from our perspective rather than the perspective of one of the classes. That is, from our perspective, we want to understand a worker's utilization relative to the other classes. From the worker's perspective, a worker is responsible for work products and performs units of work.

Figure 3-10. N-ary association Association Classes Association classes may be applied to both binary and n-ary associations. Similar to how a class defines the characteristics of its objects, including their structural fea-

tures and behavioral features, an association class may be used to define the characteristics of its links, including their structural features and behavioral features. These types of classes are used when you need to maintain information about the relationship itself. In a UML class diagram, an association class is shown as a class attached by a dashed-line path to its association path in a binary association or to its association diamond in an n-ary association. The name of the association class must match the name of the association. Figure 3-11 shows association classes for the binary associations in Figure 3-9 using the most basic notation for binary association classes. The association classes track the following information: The reason a worker is responsible for a work product The reason a worker performs a unit of work A description of how a unit of work consumes a work product A description of how a unit of work produces a work product.

Figure 3-11. Binary association classes Figure 3-12 shows an association class for the n-ary association in Figure 3-10 using the most basic notation for n-ary association classes. The association class tracks a utilization percentage for workers, their units of work, and their associated work products.

Figure 3-12. N-ary association class Class and Object Diagrams This section focuses on class and object diagrams, which depict the structure of a system in general and at a particular point in time, respectively. First, I introduce class and object diagrams and how they are used. Next, I discuss classes, objects, and

their details for modeling the elements that make up a system. Then, I go over associations, links, and their details for modeling the relationships among the elements that make up a system. Finally, I discuss various other types of elements and relationships. Class modeling is a specialized type of modeling concerned with the general structure of a system. Object modeling is a specialized type of modeling concerned with the structure of a system at a particular point in time. You usually apply class and object modeling during analysis and design activities to understand the requirements and determine how a system will satisfy its requirements. Object modeling is usually used in con j unction with class modeling to explore and refine class diagrams. Class and object modeling usually start after the requirements have matured enough (as determined by your system development process) and continue in parallel with interaction and collaboration modeling (Chapter 6) throughout the system development process, while focusing on the elements that make up the system and their relationships. As an architecture-centric process focuses on the architecture of a system across iterations, it is important to understand what elements make up a system and how they are related to one another. Given that every pro j ect has limited resources, you can use this information to determine how best to develop a system. This allows architects, designers, and developers to consider technical trade-offs concerning the system, including which elements can be developed in parallel, which elements can be purchased rather than built, and which elements can be reused. Class diagrams show classes that represent concepts, while object diagrams show objects that represent specific instances of those concepts. The next few sections talk in detail about the representation of classes and objects in class and object diagrams. Classes. A class is a general concept. For example, the project management system involves various general concepts, including projects, managers, teams, work products, requirements, and systems. A class defines a type of object and its characteristics, including structural features and behavioral features. Structural features define what objects of the class know, and behavioral features define what objects of the class can do. For example, individuals of the Manager class have names (something they know), and can initiate and terminate pro j ects (things they do). Structural features include attributes and associations. Behavioral features include operations and methods. The most crucial aspect of a class is that it has semantics: some agreed upon meaning between whomever is communicating about it. For example, when I discuss a project, what does a project mean to my audience? Is it an effort that lasts one week or one year? Is it an effort that requires a manager and other human resources? And so forth. Such meaning is very specific to the audience and domain in which the class is used.

In a UML class diagram, a class is shown as a solid-outline rectangle with three standard compartments separated by horizontal lines. The required top compartment shows the class name, the optional second compartment shows a list of attributes, and the optional third compartment shows a list of operations. The second and third compartments need only show the specific information you want to communicate using a given diagram. You don't need to show all of a class's attributes and operations all the time. Figure 3-1 shows various fundamental classes associated with the project management system in our case study, including Worker, UnitOfWork, and WorkProduct, using

Figure 3-1. Classes A worker is a person or group of people who perform work, including project managers, resource managers, human resources, and system administrators. A unit of work is a unit of effort, which includes capturing and analyzing requirements, as well as designing, implementing, testing, or deploying a system. A work product is anything produced and used within a project, including the requirements and the system. Notice that a class should be named using a noun phrase. Classes represent concepts that you discover by focusing on nouns. Attributes. An attribute is what an object of a class knows. It's an element of data maintained by the object. For example, each object of the Worker class of the project management system may have a name, description, and so forth. These are all attributes. In a class diagram, you list attributes in the second compartment for a class. The simplest approach is to just list attribute names, but the UML allows you to do much more than that. Consider an attribute for holding a worker's email address. You may start by defining it using the following basic syntax: EmailAddress As you go through the development process, you can add detail to this definition in each iteration by asking various questions and capturing more detail about the attribute based upon the answers. For example, you may ask how many email addresses a worker has. Presuming that a worker may have up to five email addresses, you can update the attribute definition to the following: EmailAddress [1..5]

Next, you may ask if these email addresses are ordered, perhaps by priority. Presuming that email addresses are not ordered, you can update the attribute definition as follows: EmailAddress [1..5 unordered] You may decide to ask the type of data an email address attribute needs to hold. You discover that an email address is a string of characters, and you update the attribute definition to indicate that: EmailAddress [1..5 unordered] : String You might then ask if there should be a default value for a worker's email address. Your client suggests using a default value of "No email address", so you update the attribute definition to the following: EmailAddress [1..5 unordered] : string "No email address" Class and method design is where all the work actually gets done during design. While some feel design is a waste of effort and that the project should jump from analysis to coding, experience shows that low-level, or detailed design, is critical despite the use of libraries and components provided by object-oriented languages. Many project teams are much too quick at jumping into writing code for the classes without first designing them. Furthermore, even though the use of layers can simplify the individual classes, they can increase the complexity of the interactions between them. The good news is that the detailed design of individual classes and methods is fairly straightforward, and the interactions among the objects on the problem-domain layer have been designed during analysis. The other layers (data management, human-computer interaction, and system architecture) are highly dependent on the problem-domain layer. It is important to realize that many of the specific details concerning the basic characteristics of object-orientation are language dependent with each language tending to implement some of the object-oriented basics in different ways. Objects are instances of classes and classes are used as templates to define objects. A class defines both the data and processes that each object contains. Each object has attributes that describe the object. Objects have a state which is defined by the value of its attributes and its relationship with other objects at a particular point in time. Each object also has methods which specify what processes the object can perform. In order to get an object to perform a method, a message is sent. A message is essentially a function or procedure call from one object to another. Encapsulation is the mechanism that combines the processes and data into a single object. Exactly how the object stores data or performs behaviors is not relevant to

oher objects. All that is required to use an object are the set of methods and the messages needed to trigger them. The only communication between objects should be through an objects methods. This is the key to reusability because it shields the internal workings of the object from changes in the outside system. Polymorphism means having the ability to take several forms, which allows objectoriented systems to send the same message to a set of objects that can be interpreted differently by different classes of objects. A message is sent to an object and it determines how to interpret the message. This is done through dynamic binding, which refers to the ability of object-oriented systems to defer data typing of objects to run time. However, the specific level of support for polymorphism and dynamic binding is language specific. Polymorphism is a double-edged sword. When using dynamic binding there is no way of knowing before run time which specific object will be asked to execute its method (decision is made by system and is not coded anywhere from a practical perspective there is an implied case statement). Because decisions are made at run time, it is possible to send a message to an object that it does not understand (the object does not have a corresponding method). In the case of an instance of employee, the compute pay method computes how much the employee is owed by the firm. Conversely, the pay method associated with a customer computes the amount owed the firm by the customer. Hence, depending on the whether the instance of the object is an employee or a customer, a different meaning is associated with the method. The key to using polymorphism correctly is to ensure that all methods with the same name implement the same generic operation (they are semantically consistent). There have been many different types of inheritance mechanisms associated with object-oriented systems. The most common inheritance mechanisms include different forms of single and multiple inheritance. Single inheritance allows a subclass to have only a single parent class while multiple inheritance allows a subclass to inherit from more than one superclass. (All OO languages support single inheritance). As a designer it is important to realize that inheritance conflicts and redefinition can cause all kinds of problems with interpreting the final design and implementation. Furthermore, with multiple inheritance a subclass may inherit from more than one superclass, multiplying inheritance conflicts, and great care should be taken when using multiple inheritance. .

Behavioral Modeling

Whereas structural models depict the static view of an information system, behavioral models provide a dynamic view of an information system. One of the primary purposes of behavioral models is to show how the underlying objects in a problem domain will work together to form a collaboration to support each of the use cases. n During analysis, behavioral models describe what the internal logic of the process is without specifying how the processes are to be implemented, while in design and implementation phases operations are fully specified. The UML diagrams used in behavioral modeling are sequence diagrams, communication diagrams, and behavioral state machines. There are two types of behavioral models. One type represents the underlying details of a business process portrayed by a usecase model and interaction diagrams (communication and sequence) are used for this type of modeling. To show changes in the underlying data, UML uses behavioral state machines. Hence, one of the primary differences between class diagrams and interaction diagrams is that the modeling focus of a class diagram is the class level. For interaction diagrams the focus is on the object level.

Sequence Diagram
A sequence diagram shows elements as they interact over time. They also show the interactions between objects to achieve a result (a use case). The communications between classes are known as messages. Sequence diagrams list objects horizontally, and time vertically, and models these messages over time. In a sequence diagram, classes and actors are listed as columns, while vertical lifelines indicate the lifetime of the object over time. During the design phase, sequence diagrams are very implementation specific and often include database objects or specific user interface components as the classes (objects). NOTATION Object: Objects are instances of classes, and are arranged horizontally. The pictorial representation of an Object is a class (a rectangle) with the name prefixed by the object name (optional) and a semi-colon.

: O

j e

Actor: Actors can also communicate with objects, so they too can be listed as a column. An

Actor is modeled using the ubiquitous symbol, the stick figure.

c t o r

Lifeline: The lifeline identifies the existence of the object over time. The notation for a Lifeline is a vertical dotted line extending from an object. Sometimes an object creates a temporary object; in this case an X is placed at the end of the lifeline at the point the object is

destroyed. When objects continue to exist in the system after they are used in the sequence diagram, then the lifeline continues to the bottom of the diagram. Activation: Activations are modeled as rectangular boxes on the lifeline, it represent the period during which an object is performing an operation. The top of the rectangle is aligned with the initiation time, and the bottom is aligned with the completion time.

Message: Messages, modeled as horizontal arrows between Activations, indicate the communications between objects. A message that goes from one object to another, goes from one objects lifeline to the other objects lifeline. An object can send a message to itself-that is, from its lifeline back to its own lifeline. Simple Message: This is a transfer of control from one object to another. Synchronous Message: If an object sends a Synchronous message, it waits for an answer to that message before it proceeds with its business.

Asynchronous Message: If an object sends a message, it does not wait for an answer before it proceeds.

Time: The diagram represents Time in the vertical direction. Time starts at the top and progresses toward the bottom. A message that is closer to the top occurs earlier in time than a message that is closer to the bottom. Return: When one object commands another, a value is often returned. This may be a value computed by the object as a result of the command or a return code indicating whether the object completed processing the command successfully. These returned values are generally not indicated on a sequence diagram; they are simply assumed. In some instances the objects may not be able to return this information immediately. In this case, the return of this information is noted on the diagram later using a dotted arrow. This indicates the flow of information was based on a previous request. Guard {conditional}: Square brackets indicate that a condition must be satisfied for the communication to be sent or occur, i.e., a Boolean expression that evaluates to TRUE OR FALSE. The message is only sent if the expression is true. Iteration: Square brackets are preceded by an asterisk (*) indicate Iteration. The message is sent multiple times. The expression within the brackets describes the iteration rule.

Deletion: An X is used to indicate the termination (deletion) of an object.

The basics
The main purpose of a sequence diagram is to define event sequences that result in some desired outcome. The focus is less on messages themselves and more on the order in which messages occur; nevertheless, most sequence diagrams will communicate what messages are sent between a system's objects as well as the order in which they occur. The diagram conveys this information along the horizontal and vertical dimensions: the vertical dimension shows, top down, the time sequence of messages/calls as they occur, and the horizontal dimension shows, left to right, the object instances that the messages are sent to.
Lifelines When drawing a sequence diagram, lifeline notation elements are placed across the top of the diagram. Lifelines represent either roles or object instances that participate in the sequence being modeled. Lifelines are drawn as a box with a dashed line descending from the center of the bottom edge (Figure 3). The lifeline's name is placed inside the box.

Figure 3: An example of the Student class used in a lifeline whose instance name is freshman In the example shown in Figure 3, the lifeline represents an instance of the class Student, whose instance name is freshman. Note that, here, the lifeline name is underlined. When an underline is used, it means that the lifeline represents a specific instance of a class in a sequence diagram, and not a particular kind of instance (i.e., a role). For now, just observe that sequence diagrams may include roles (such as buyer and seller) without specifying who plays those roles (such as Bill and Fred). This allows diagram reuse in different contexts. Simply put, instance names in sequence diagrams are underlined; roles names are not. Our example lifeline in Figure 3 is a named object, but not all lifelines represent named objects. Instead a lifeline can be used to represent an anonymous or unnamed instance. When modeling an unnamed instance on a sequence diagram, the lifeline's name follows the same pattern as a named instance; but instead of providing an instance name, that portion of the lifeline's name is left blank. Again referring to Figure 3, if the lifeline is representing an anonymous instance of the Student class, the lifeline would be: " Student." Also, because sequence diagrams are used during the design phase of projects, it is completely legitimate to have an object whose type is unspecified: for example, "freshman."
Messages

The first message of a sequence diagram always starts at the top and is typically located on the left side of the diagram for readability. Subsequent messages are then added to the diagram slightly lower then the previous message. To show an object (i.e., lifeline) sending a message to another object, you draw a line to the receiving object with a solid arrowhead (if a synchronous call operation) or with a stick arrowhead (if an asynchronous signal). The message/method name is placed above the arrowed line. The message that is being sent to the receiving object represents an operation/method that the receiving object's class implements. In the example in Figure 4, the analyst object makes a call to the system object which is an instance of the ReportingSystem class. The analyst object is calling the system object's getAvailableReports method. The system object then calls the getSecurityClearance method with the argument of userId on the secSystem object, which is of the class type SecuritySystem.

Figure 4: An example of messages being sent between objects Besides just showing message calls on the sequence diagram, the Figure 4 diagram includes return messages. These return messages are optional; a return message is drawn as a dotted line with an open arrowhead back to the originating lifeline, and above this dotted line you place the return value from the operation. In Figure 4 the secSystem object returns userClearance to the system object when the getSecurityClearance method is called. The system object returns availableReports when the getAvailableReports method is called. Again, the return messages are an optional part of a sequence diagram. The use of return messages depends on the level of detail/abstraction that is being modeled. Return messages are useful if finer detail is required; otherwise, the invocation message is sufficient. I personally like to include return messages whenever a value will be returned, because I find the extra details make a sequence diagram easier to read. When modeling a sequence diagram, there will be times that an object will need to send a message to itself. When does an object call itself? A purist would argue that an object should never send a message to itself. However, modeling an object sending a message to itself can be useful in some cases. For example, Figure 5 is an improved version of Figure 4.

The Figure 5 version shows the system object calling its determineAvailableReports method. By showing the system sending itself the message "determineAvailableReports," the model draws attention to the fact that this processing takes place in the system object. To draw an object calling itself, you draw a message as you would normally, but instead of connecting it to another object, you connect the message back to the object itself.

Figure 5: The system object calling its determineAvailableReports method The example messages in Figure 5 show synchronous messages; however, in sequence diagrams you can model asynchronous messages, too. An asynchronous message is drawn similar to a synchronous one, but the message's line is drawn with a stick arrowhead, as shown in Figure 6.

Figure 6: A sequence diagram fragment showing an asynchronous message being sent to instance2
Guards When modeling object interactions, there will be times when a condition must be met for a message to be sent to the object. Guards are used throughout UML diagrams to control flow. In UML, a guard could only be assigned to a single message. To draw a guard on a sequence diagram in UML, you placed the guard element above the message line being guarded and in

front of the message name. Figure 7 shows a fragment of a sequence diagram with a guard on the message addStudent method.

Figure 7: A segment of a UML sequence diagram in which the addStudent message has a guard In Figure 7, the guard is the text "[pastDueBalance = 0]." By having the guard on this message, the addStudent message will only be sent if the accounts receivable system returns a past due balance of zero. The notation of a guard is very simple; the format is:
Combined fragments (alternatives, options, and loops) In most sequence diagrams, however, the UML "in-line" guard is not sufficient to handle the logic required for a sequence being modeled. A combined fragment is used to group sets of messages together to show conditional flow in a sequence diagram. Alternatives Alternatives are used to designate a mutually exclusive choice between two or more message sequences. Alternatives allow the modeling of the classic "if then else" logic (e.g., if I buy three items, then I get 20% off my purchase; else I get 10% off my purchase).

As you will notice in Figure 8, an alternative combination fragment element is drawn using a frame. The word "alt" is placed inside the frame's namebox. The larger rectangle is then divided into what UML calls operands. Operands are separated by a dashed line. Each operand is given a guard to test against, and this guard is placed towards the top left section of the operand on top of a lifeline. If an operand's guard equates to "true," then that operand is the operand to follow.

Figure 8: A sequence diagram fragment that contains an alternative combination fragment As an example to show how an alternative combination fragment is read, Figure 8 shows the sequence starting at the top, with the bank object getting the check's amount and the account's balance. At this point in the sequence the alternative combination fragment takes over. Because of the guard "[balance >= amount]," if the account's balance is greater than or equal to the amount, then the sequence continues with the bank object sending the addDebitTransaction and storePhotoOfCheck messages to the account object. However, if the balance is not greater than or equal to the amount, then the sequence proceeds with the

bank object sending the addInsuffientFundFee and noteReturnedCheck message to the account object and the returnCheck message to itself. The second sequence is called when the balance is not greater than or equal to the amount because of the "[else]" guard. In alternative combination fragments, the "[else]" guard is not required; and if an operand does not have an explicit guard on it, then the "[else]" guard is to be assumed. Alternative combination fragments are not limited to simple "if then else" tests. There can be as many alternative paths as are needed. If more alternatives are needed, all you must do is add an operand to the rectangle with that sequence's guard and messages.
Option The option combination fragment is used to model a sequence that, given a certain condition, will occur; otherwise, the sequence does not occur. An option is used to model a simple "if then" statement (i.e., if there are fewer than five donuts on the shelf, then make two dozen more donuts).

The option combination fragment notation is similar to the alternation combination fragment, except that it only has one operand and there never can be an "else" guard (it just does not make sense here). To draw an option combination you draw a frame. The text "opt" is placed inside the frame's namebox, and in the frame's content area the option's guard is placed towards the top left corner on top of a lifeline. Then the option's sequence of messages is placed in the remainder of the frame's content area. These elements are illustrated in Figure 9.

Figure 9: A sequence diagram fragment that includes an option combination fragment Reading an option combination fragment is easy. Figure 9 is a reworking of the sequence diagram fragment in Figure 7, but this time it uses an option combination fragment because more messages need to be sent if the student's past due balance is equal to zero. According to the sequence diagram in Figure 9, if a student's past due balance equals zero, then the addStudent, getCostOfClass, and chargeForClass messages are sent. If the student's past due

balance does not equal zero, then the sequence skips sending any of the messages in the option combination fragment. The example Figure 9 sequence diagram fragment includes a guard for the option; however, the guard is not a required element. In high-level, abstract sequence diagrams you might not want to specify the condition of the option. You may simply want to indicate that the fragment is optional.
Loops Occasionally you will need to model a repetitive sequence. Modeling a repeating sequence has been improved with the addition of the loop combination fragment. The loop combination fragment is very similar in appearance to the option combination fragment. You draw a frame, and in the frame's namebox the text "loop" is placed. Inside the frame's content area the loop's guard is placed towards the top left corner, on top of a lifeline. Then the loop's sequence of messages is placed in the remainder of the frame's content area. In a loop, a guard can have two special conditions tested against in addition to the standard Boolean test. The special guard conditions are minimum iterations written as "minint = [the number]" (e.g., "minint = 1") and maximum iterations written as "maxint = [the number]" (e.g., "maxint = 5"). With a minimum iterations guard, the loop must execute at least the number of times indicated, whereas with a maximum iterations guard the number of loop executions cannot exceed the number.

Communication Diagram
A communication diagram is essentially and Object diagram that shows the messagepassing relationship instead of aggregation or generalization associations. Whereas sequence diagram show the time ordering of messages being passed, communication diagrams emphasize the flow of messages through a set of objects and are useful to show process patterns (patterns of activity that occur over a set of collaborating classes). To understand the flow of control over a set of collaborating objects and to understand which objects collaborate to support business processes use a communication diagram. In some cases both can be used to describe the dynamic activity of the system (this seems to imply that it is typical to only use one of these types of interaction diagrams and only sequence diagrams are covered in this document Dr. T).

Behavioral State Machine


Some of the classes in the class diagrams represent a set of objects that are quite dynamic in that they pass through a variety of states over the course of their existence. For example, a patient can change from new to current to former. A behavioral state machine is a dynamic model that shows the different states through which a single object passes during its life in response to events, along with its responses and actions. The state of an object is defined by the value of its attributes and its relationship with other objects at a particular point in time. The attributes of an object affect its state but not attribute changes will make a difference. An event is something that takes place at a certain point in time and changes a value(s) that describe an object. A transition is a relationship that represents the movement of an object from one state to another, typically, based on an action triggered by an event. An action is an atomic, nondecomposable process that cannot be interrupted. In contrast, an activity is non-atomic, decomposable process that can be interrupted and take a long period of time to complete. The elements of a behavioral state machine are as follows. A state is depicted by a state symbol (rectangle with rounded corners with a descriptive label that communicates a particular state), while an initial state is shown using a small filled in circle and a final state is shown as a circle surrounding a small, filled-in circle. These symbols depict when an object begins and ceases to exist. Arrows are used to connect the state symbols representing the transitions between states. Each arrow is labeled with the appropriate event name. Any parameters or conditions that may apply are shown using guard conditions. In some cases it is useful to explicitly show the context of the behavioral state machine using a frame. Sometimes, states and subclasses can be confused. For example, freshman, sophomore, etc., can be subclasses of undergraduate class or as states an object of an undergraduate class goes through during its lifetime. While it is better to model this as states rather than

subclasses, it is better to capture that information as part of the structural model and remove it when the behavioral models are created rather than risk omitting it. Remember, object-oriented development is iterative and incremental. Finally, remember that behavioral state machines are drawn to depict a single class from a class diagram and are not done for all objects (classes), only complex ones.

Вам также может понравиться