08_Modeling With UML

download 08_Modeling With UML

of 57

description

These slides shows how to model with the UML

Transcript of 08_Modeling With UML

Modeling with UML

Modeling with UMLLecture 81Overview: modeling with UMLWhat is modeling?What is UML?Use case diagramsClass diagramsSequence diagramsActivity diagrams2What is modeling?Modeling consists of building an abstraction of reality.Abstractions are simplifications because:They ignore irrelevant details andThey only represent the relevant details.What is relevant or irrelevant depends on the purpose of the model.Example: street map3Why model software?Software is getting increasingly more complexWindows XP around 45 million lines of codeOpenSolaris =9.7 M LOCMac OS X 10.4= 86 M LOCA small number of programmers cannot manage this amount of code in its entirety.Code is not easily understandable by developers who did not write itWe need simpler representations for complex systemsModeling is a means for dealing with complexity4Application and Solution DomainApplication Domain (Requirements Analysis):The environment in which the system is operating

Solution Domain (System Design, Object Design):The available technologies to build the system5Object-oriented ModelingApplication Domain (Phenomena)Solution Domain (Phenomena)System Model (Concepts)System Model (Concepts)AircraftTrafficControllerFlightPlanAirportMapDisplayFlightPlanDatabaseSummaryDisplay

TrafficControlTrafficControlUML Package

(Analysis)(Design)66What is UML?UML (Unified Modeling Language)Nonproprietary standard for modeling software systems, OMGConvergence of notations used in object-oriented methodsOMT (James Rumbaugh)Booch (Grady Booch) OOSE (Ivar Jacobson)Current Version: UML 2.4.1Information at the OMG portal http://www.uml.org/Commercial tools: Rational (IBM),Together (Borland), Visual Architect (business processes)Open Source tools: ArgoUML, StarUML, UmbrelloCommercial and Opensource: PoseidonUML (Gentleware)77UML: First PassYou can model 80% of most problems by using about 20% UMLThis lecture covers only that 20%

80-20 rule: Pareto principle (Wikipedia)80% of your profits come from 20% of your customers80% of your complaints come from 20% of your customers80% of your profits come from 20% of the time you spend80% of your sales come from 20% of your products

88UML First PassUse case diagramsDescribe the functional behavior of the system as seen by the userClass diagramsDescribe the static structure of the system: Objects, attributes, associationsSequence diagramsDescribe the dynamic behavior between objects of the systemState diagramsDescribe the dynamic behavior of an individual object99Statechart diagramsDescribe the dynamic behavior of an individual object (essentially a finite state automaton)Activity DiagramsModel the dynamic behavior of a system, in particular the workflow (essentially a flowchart)UML Core ConventionsAll UML Diagrams denote graphs of nodes and edgesNodes are entities and drawn as rectangles or ovalsRectangles denote classes or instances Ovals denote functions Names of Classes are not underlinedSimpleWatchFirefighter Names of Instances are underlinedmyWatch:SimpleWatchJoe:FirefighterAn edge between two nodes denotes a relationship between the corresponding entities1010UML first pass: Use case diagrams

Use case diagrams represent the functionality of the system from users point of viewActorUse CaseSystem boundaryClassifier11UML first pass: Class diagramsClassAssociationMultiplicityClass diagrams represent the structure of the system21111112SimpleWatchDisplayBatteryTimePushButton1212UML first pass: Class diagrams12push()release()11blinkIdxblinkSeconds()blinkMinutes()blinkHours()stopBlinking()referesh()LCDDisplayBatteryLoad121TimeNow1WatchOperationsstatePushButtonAttributeClass diagrams represent the structure of the systemClassAssociationMultiplicity1313MessageUML first pass: Sequence diagram:Time :Watch:WatchUserObjectActivationSequence diagrams represent the behavior of a system as messages (interactions) between different objectsActorpressButton1()LifelineblinkHours()pressButton2()incrementMinutes():LCDDisplaypressButton1and2()commitNewTime()stopBlinking()refresh()pressButton1()blinkMinutes()1414UML first pass: Statechart diagramsStateInitial stateFinal stateTransitionEventRepresent behavior of a single object with interesting dynamic behavior.button1&2Pressedbutton1Pressedbutton2Pressedbutton2Pressedbutton2Pressedbutton1Pressedbutton1&2PressedIncrementMinutesIncrementHoursBlinkHoursBlinkSecondsBlinkMinutesIncrementSecondsStopBlinking1515Represent behavior of single objects with interesting dynamic behavior in terms of states and transitionsThe behavior of the single object Watch, for example, has several different states, BlinkHours, BlinkMinutes, BlinkSeconds, because in each state pressing a button or two yields a different result. Other UML NotationsUML provides many other notations, for exampleDeployment diagrams for modeling configurations Useful for testing and for release managementWe introduce these and other notations as we go along in the lecturesObject Constraint Language (OCL): A language for constraining UML models1616In particular, in System Design we use Deployment Diagrams, in Testing we use Profiles. There is also a language to constrain the systems that can be instantiated from models. The language that has been designed to contain UML models is called OCL (Object Constraint Language)What should be done first? Coding or Modeling?It all depends.Forward EngineeringCreation of code from a modelStart with modelingGreenfield projectsReverse EngineeringCreation of a model from existing codeInterface or reengineering projectsRoundtrip EngineeringMove constantly between forward and reverse engineeringReengineering projectsUseful when requirements, technology and schedule are changing frequently.1717UML Second PassUse case diagramsDescribe the functional behavior of the system as seen by the userClass diagramsDescribe the static structure of the system: Objects, attributes, associationsSequence diagramsDescribe the dynamic behavior between objects of the systemState diagramsDescribe the dynamic behavior of an individual objectActivity diagramsDescribe the dynamic behavior of a system, in particular the workflow.1818Statechart diagramsDescribe the dynamic behavior of an individual object (essentially a finite state automaton)Activity DiagramsModel the dynamic behavior of a system, in particular the workflow (essentially a flowchart)UML Use Case DiagramsAn Actor represents a role, that is, a type of user of the systemPassengerPurchaseTicketUsed during requirements elicitation and analysis to represent external behavior (visible from the outside of the system)Use case model:The set of all use cases that completely describe the functionality of the system.A use case represents a class of functionality provided by the system1919ActorsAn actor is a model for an external entity which interacts (communicates) with the system:UserExternal system (Another system)Physical environment (e.g. Weather)An actor has a unique name and an optional descriptionExamples:Passenger: A person in the trainGPS satellite: An external system that provides the system with GPS coordinates.PassengerNameOptional Description2020Use Case A use case represents a class of functionality provided by the system Use cases can be described textually, with a focus on the event flow between actor and system The textual use case description consists of 6 parts:Unique nameParticipating actorsEntry conditionsExit conditionsFlow of eventsSpecial requirementsPurchaseTicket2121Textual Use Case - Description Example1. Name: Purchase ticket

2. Participating actor: Passenger

3. Entry condition: Passenger stands in front of ticket distributorPassenger has sufficient money to purchase ticket

4. Exit condition:Passenger has ticket5. Flow of events:1. Passenger selects the number of zones to be traveled2. Ticket Distributor displays the amount due3. Passenger inserts money, at least the amount due4. Ticket Distributor returns change5. Ticket Distributor issues ticket6. Special requirements: None.

PassengerPurchaseTicket2222Question: Anything missing? Answer: Exceptional cases!Use cases represent functionality of the systemAll use cases need to be described for the model to be usefulUse case diagrams are useful as an index into the use casesThe Textual Use case descriptions provide meat of model, not the use case diagrams.Uses Cases can be relatedExtends RelationshipTo represent seldom invoked use cases or exceptional functionalityIncludes RelationshipTo represent functional behavior common to more than one use case.2323The Relationship relationships model exceptional or seldom invoked casesThe exceptional event flows are factored out of the main event flow for clarityThe direction of an relationship is to the extended use case Use cases representing exceptional flows can extend more than one use case.

PassengerPurchaseTicketTimeOut

NoChange

OutOfOrder

Cancel

2424The Relationship relationship represents common functionality needed in more than one use case behavior is factored out for reuse, not because it is an exceptionThe direction of a relationship is to the using use case (unlike the direction of the relationship)PassengerPurchaseSingleTicketPurchaseMultiCard

CollectMoney

NoChange

Cancel

2525Class DiagramsClass diagrams represent structure of the systemIt is usedduring requirements analysis to model application domain conceptsduring system design to model subsystemsduring object design to specify the detailed behavior and attributes of classes.

Table zone2priceEnumeration getZones()Price getPrice(Zone)TarifSchedule**Tripzone:Zoneprice: Price2626ClassesA class represents a conceptA class encapsulates state (attributes) and behavior (operations)Table zone2priceEnumeration getZones()Price getPrice(Zone)TarifSchedulezone2pricegetZones()getPrice()TarifScheduleNameAttributesOperationsSignatureTarifScheduleThe class name is the only mandatory informationEach attribute has a typeEach operation has a signatureType27InstancesAn instance represents a phenomenonThe attributes are represented with their valuesThe name of an instance is underlined The name can contain only the class name of the instance (anonymous instance)

zone2price = {{1, 0.20},{2, 0.40},{3, 0.60}}tarif2006:TarifSchedulezone2price = {{1, 0.20},{2, 0.40},{3, 0.60}}:TarifSchedule28Actor vs Class vs ObjectActor An entity outside the system to be modeled, interacting with the system (Passenger)ClassAn abstraction modeling an entity in the application or solution domainThe class is part of the system model (User, Ticket distributor, Server)ObjectA specific instance of a class (Joe, the passenger who is purchasing a ticket from the ticket distributor). 2929What is the difference between an actor, a class and an instance?AssociationsAssociations denote relationships between classesPriceZone

Enumeration getZones()Price getPrice(Zone)TarifScheduleTripLeg**The multiplicity of an association end denotes how many objects the instance of a class can legitimately reference.301-to-1 and 1-to-many Associations1-to-1 association1-to-many associationPolygondraw()Pointx: Integery: Integer*Countryname:StringCapital(City)name:String1131131Many-to-Many Associations StockExchangeCompanytickerSymbol**3232A stock exchange lists many companies each of them uniquely identified by a ticker symbol used at that stock exchange.A company can be listed on more than one stock exchange, using the same ticker symbol.

Mercedes Benz is an example for a company listed on more than one stock exchange: Frankfurt and NYSE. Does it have two different Ticker symbols?Something not clear here: What happens if the company cannot have the same ticker symbol on two different stock exchanges?From Problem Statement To Object Model Class Diagram:StockExchangeCompanytickerSymbolLists **Problem Statement: A stock exchange lists many companies. Each company is uniquely identified by a ticker symbol3333From Problem Statement to Code Problem Statement: stock exchange lists many companies. Each company is identified by a ticker symbolClass Diagram: private Vector m_Company = new Vector(); public int m_tickerSymbol; private Vector m_StockExchange = new Vector();public class StockExchange{};public class Company{};Java CodeStockExchangeCompanytickerSymbolLists **Associationsare mapped to Attributes!3434AggregationAn aggregation is a special case of association denoting a consists-of hierarchyThe aggregate is the parent class, the components are the children classesExhaust systemMufflerdiameterTailpipediameter10..2TicketMachineZoneButton3A solid diamond denotes composition: A strong form of aggregation where the life time of the component instances is controlled by the aggregate. That is, the parts dont exist on their won (the whole controls/destroys the parts) 35Example for composition: Bill of MaterialQualifiersQualifiers can be used to reduce the multiplicity of an associationDirectoryFilefilenameWithout qualification1*With qualification0..1DirectoryFile1filename36In this case, filename is a qualifier attached to DirectoryQualification: Another Example*StockExchangeCompanyLists *tickerSymbol1StockExchangeCompanytickerSymbolLists **3737InheritanceInheritance is another special case of an association denoting a kind-of hierarchy Inheritance simplifies the analysis model by introducing a taxonomyThe children classes inherit the attributes and operations of the parent class.

ButtonZoneButtonCancelButton3838Later we will also see how inheritance allows the reuse of solutions (implementation and specification inheritance)PackagesPackages help organize UML models to increase their readability We can use the UML package mechanism to organize classes into subsystems

Any complex system can be decomposed into subsystems, where each subsystem is modeled as a package.

AccountCustomerBank3939Packages are the grouping constructObject Modeling in PracticeClass Identification: Name of Class, Attributes and MethodsIs Foo the right name?FooAmountCustomerIdDeposit()Withdraw()GetBalance()4040Object Modeling in Practice: Brainstorming FooAmountCustomerIdDeposit()Withdraw()GetBalance()

AccountAmountCustomerIdDeposit()Withdraw()GetBalance()Is Foo the right name?DadaAmountCustomerIdDeposit()Withdraw()GetBalance()

4141Naming is important!Object Modeling in Practice: More classesAccountAmountDeposit()Withdraw()GetBalance()CustomerNameCustomerIdCustomerIdAccountIdBankName1) Find New Classes2) Review Names, Attributes and Methods4242Object Modeling in Practice: AssociationsAccountDeposit()Withdraw()GetBalance()CustomerNameCustomerIdAccountIdBankName1) Find New Classes2) Review Names, Attributes and Methods3) Find Associations between Classesowns4) Label the generic assocations6) Review associations**?has5) Determine the multiplicity of the assocationsAmount4343Practice Object Modeling: Find TaxonomiesSavingsAccountWithdraw()CheckingAccountWithdraw()MortgageAccountWithdraw()AccountAmountDeposit()Withdraw()GetBalance()AccountIdCustomerNameCustomerId()Has*BankName*4444Practice Object Modeling: Simplify, OrganizeSavingsAccountWithdraw()CheckingAccountWithdraw()MortgageAccountWithdraw()AccountAmountDeposit()Withdraw()GetBalance()AccountIdShow Taxonomiesseparately4545Practice Object Modeling: Find TaxonomiesSavingsAccountWithdraw()CheckingAccountWithdraw()MortgageAccountWithdraw()AccountAmountDeposit()Withdraw()GetBalance()AccountIdCustomerNameCustomerId()Has*BankName*4646Sequence DiagramsUsed during analysisTo refine use case descriptionsto find additional objects (participating objects)Used during system design to refine subsystem interfacesInstances are represented by rectangles. Actors by sticky figuresLifelines are represented by dashed linesMessages are represented by arrows Activations are represented by narrow rectangles.selectZone()pickupChange()pickUpTicket()insertCoins()TicketMachinePassengerFocus on control flowMessages ->Operations on participating Objectzone2priceselectZone()insertCoins()pickupChange()pickUpTicket()TicketMachine4747Sequence Diagrams can also model the Flow of Data The source of an arrow indicates the activation which sent the messageHorizontal dashed arrows indicate data flow, for example return results from a messagePassengerselectZone()ZoneButtonTarifScheduleDisplaylookupPrice(selection)displayPrice(price)priceDataflowcontinued on next slide...48Sequence Diagrams: Iteration & ConditionIteration is denoted by a * preceding the message nameCondition is denoted by boolean expression in [ ] before the message namePassengerChangeProcessorinsertChange(coin)CoinIdentifierDisplayCoinDropdisplayPrice(owedAmount)lookupCoin(coin)price[owedAmount