Lecture 4 OBJECT ORIENTED ANALYSIS PB007 Software Engineering I Faculty of Informatics, Masaryk University Fall 2018 1© Barbora Bühnová Outline ² UML Objects and classes [Lecture 3] ² Finding analysis classes [Lecture 3] ² Relationships between objects and classes § Links § Associations § Dependencies ² Inheritance and polymorphism ² UML State diagram 2© Clear View Training 2010 v2.6 Relationships Between Objects and Classes Lecture 4/Part 1 3© Clear View Training 2010 v2.6 © Clear View Training 2010 v2.6 4 What is a link? ² Links are connections between objects § Think of a link as a telephone line connecting you and a friend. You can send messages back and forth using this link ² Links are the way that objects communicate § Objects send messages to each other via links § Messages invoke operations ² OO programming languages implement links as object references or pointers § When an object has a stored reference to another object, we say that there is a link between the objects © Clear View Training 2010 v2.6 5 Object diagrams ² Paths in UML diagrams can be drawn as orthogonal, oblique or curved lines ² We can combine paths into a tree if each path has the same properties bookClub:Club ila:Person erica:Person naomi:Person chairperson secretary member role name link BookClub bookClub:Club ila:Person erica:Person naomi:Person chairperson secretary member BookClub oblique path style orthogonal path style preferred object Shape Square Circle Triangle © Clear View Training 2010 v2.6 6 What is an association? ² Associations are relationships between classes ² Associations between classes indicate that there may be links between objects of those classes, while links indicates that there must be associations ² Can there be a communication between objects of two classes that have no association between them? bookClub:Club jim:Person chairman Club Person «instantiate» «instantiate» «instantiate» link association links instantiate associations © Clear View Training 2010 v2.6 7 Association syntax ² An association can have role names OR an association name ² Multiplicity is a constraint that specifies the number of objects that can participate in a relationship at any point in time § If multiplicity is not explicitly stated in the model then it is undecided – there is no default multiplicity Company Person 1 0..* employs navigability association name multiplicity Company Person employer employee 1 0..* role names multiplicity: min..max 0..1 zero or 1 1 exactly 1 0..* zero or more 1..* 1 or more 1..6 1 to 6 reading direction © Clear View Training 2010 v2.6 8 Multiplicity exercise ² How many § Employees can a Company have? § Employers can a Person have? § Owners can a BankAccount have? § Operators can a BankAccount have? § BankAccounts can a Person have? § BankAccounts can a Person operate? Company Person employee 1 7 employer BankAccount 0..* 1owner 0..* 1..* operator © Clear View Training 2010 v2.6 9 Reflexive associations: file system example Directory File 0..*10..* 0..1 C Windows My Documents Corel Command autoexec config To John directories files parent subdirectory reflexive association ² If ToJohn was a directory, would it still conform to the class diagram? © Clear View Training 2010 v2.6 10 Hierarchies and networks A 0..* 0..1 a1:A b1:A c1:A d1:A e1:A f1:A g1:A B 0..* 0..* a1:B b1:B c1:B d1:Be1:B f1:B g1:B hierarchy network In an association hierarchy, each object has zero or one object directly above it. In an association network, each object has zero or many objects directly above it. © Clear View Training 2010 v2.6 11 Navigability ² Navigability indicates that it is possible to traverse from an object of the source class to objects of the target class ² Can there be a communication in a direction not supported by the navigability? ² Are some of the cases on the right equivalent? Order Product 0..* 0..* Not navigable A Product object does not store a list of Orders An Order object stores a list of Products Navigable source target navigability A B A B A B A B A to B is navigable B to A is navigable A to B is navigable B to A is not navigable A to B is navigable B to A is undefined A to B is undefined B to A is undefined © Clear View Training 2010 v2.6 12 Associations and attributes ² An association is (through its role name) a representation of an attribute ² Use associations when: § The target class is an important part of the model § The target class is a class that you have designed yourself ² Use attributes when: § The target class is not important, e.g. a primitive type such as number, string § The target class is just an implementation detail such as a bought-in component or a library component e.g. Java.util.Vector (from the Java standard libraries) address:Address House House Address 1 1 address House address:Address pseudo-attribute attribute = © Clear View Training 2010 v2.6 13 Association classes Company Person 0..* 0..*employment ² Where do we record the Person’s salary? ² We model the association itself as an association class. Exactly one instance of this class exists for each link between a Person and a Company. ² We can place the salary and any other attributes or operations which are really features of the association into this class Company Person 0..* 0..* Job salary:double the association class consists of the class, the association and the dashed line association class © Clear View Training 2010 v2.6 14 Using association classes Company Person 0..* 0..* Job salary:double If we use an association class, then a particular Person can have only one Job with a particular Company If, however a particular Person can have multiple jobs with the same Company, then we must use a reified association Company Person Job salary:double 0..*0..* 11 © Clear View Training 2010 v2.6 15 Dependencies ² "A dependency is a relationship between two elements where a change to one element (the supplier) may affect or supply information needed by the other element (the client)". § In other words, the client depends in some way on the supplier § Weaker type of relationship than association § Can there be both association and dependency between two classes? ² Three types of dependency: § Usage - the client uses some of the services made available by the supplier to implement its own behavior – this is the most commonly used type of dependency § Abstraction - a shift in the level of abstraction. The supplier is more abstract than the client § Permission - the supplier grants some sort of permission for the client to access its contents – this is a way for the supplier to control and limit access to its contents © Clear View Training 2010 v2.6 16 Usage dependencies ² Stereotypes § «use» - the client makes use of the supplier to implement its behaviour § «call» - the client operation invokes the supplier operation § «parameter» - the supplier is a parameter of the client operation § «send» - the client (an operation) sends the supplier (a signal) to some unspecified target § «instantiate» - the client is an instance of the supplier A foo( b : B ) bar() : B doSomething() B A :: doSomething() { B myB = new B(); } «use» A «use» dependency is generated between A and B when B is used in A as a parameter, return value or inside method body the stereotype is often omitted © Clear View Training 2010 v2.6 17 Abstraction and permission dependencies ² Abstraction dependencies § «trace» - the client and the supplier represent the same concept but at different points in development § «substitute» - the client may be substituted for the supplier at runtime. The client and supplier must realize a common contract. Use in environments that don't support specialization/generalization § «refine» - the client represents a fuller specification of the supplier § «derive» - the client may be derived from the supplier. The client is logically redundant, but may appear for implementation reasons ² Permission dependencies § «access» the public contents of the supplier package are added as private elements to the namespace of the client package § «import» the public contents of the supplier package are added as public elements to the namespace of the client package § «permit» the client element has access to the supplier element despite the declared visibility of the supplier © Clear View Training 2010 v2.6 18 Key points ² Links – relationships between objects ² Associations – relationships between classes § role names § multiplicity § navigability § association classes ² Dependencies – relationships between model elements § usage § abstraction § permission © Clear View Training 2010 v2.6 19 Inheritance and polymorphism Lecture 4/Part 2 © Clear View Training 2010 v2.6 20 Generalisation Shape Square Circle Triangle more general element more specific elements parent superclass base class ancestor child subclass descendent generalisation specialisation A generalisation hierarchy “is kind of” A relationship between a more general element and a more specific element (with more information) © Clear View Training 2010 v2.6 21 Class inheritance ² Subclasses inherit all features of their superclasses: § attributes § operations § relationships § stereotypes, tags, constraints ² Subclasses can add new features ² Subclasses can override superclass operations ² We can use a subclass instance anywhere a superclass instance is expected Substitutability Principle Shape origin : Point = (0,0) width : int {>0} height : int {>0} draw( g : Graphics ) getArea() : int getBoundingArea() : int Square Circle radius : int = width/2 What’s wrong with these subclasses? © Clear View Training 2010 v2.6 22 Overriding ² Subclasses often need to override superclass behaviour ² To override a superclass operation, a subclass must provide an operation with the same signature § The operation signature is the operation name, return type and types of all the parameters Shape draw( g : Graphics ) getArea() : int getBoundingArea() : int Square Circle draw( g : Graphics ) getArea() : int draw( g : Graphics ) getArea() : intwidth x height p x radius2 What’s wrong with the superclass? © Clear View Training 2010 v2.6 23 Abstract operations & classes ² We can’t provide an implementation for Shape :: draw( g : Graphics ) or for Shape :: getArea() : int because we don’t know how to draw or calculate the area for a "shape"! ² Operations that lack an implementation are abstract operations ² A class with any abstract operations can’t be instantiated and is therefore an abstract class concrete operations Shape draw( g : Graphics ) getArea() : int getBoundingArea() : int Square Circle draw( g : Graphics ) getArea() : int draw( g : Graphics ) getArea() : int abstract class concrete classes abstract operations Abstract class and operation names must be in italics © Clear View Training 2010 v2.6 24 Exercise Vehicle JaguarXJS Truck what’s wrong with this model? © Clear View Training 2010 v2.6 25 Polymorphism ² Polymorphism = "many forms" § A polymorphic operation has many implementations § Square and Circle provide implementations for the polymorphic operations Shape::draw() and Shape::getArea() ² The operation in Shape superclass defines a contract for the subclasses. Shape draw( g : Graphics ) getArea() : int getBoundingArea() : int Square Circle draw( g : Graphics ) getArea() : int draw( g : Graphics ) getArea() : int polymorphic operations concrete subclasses abstract superclass Canvas 0..* 1 A Canvas object has a collection of Shape objects where each Shape may be a Square or a Circle shapes © Clear View Training 2010 v2.6 26 What happens? ² Each class of object has its own implementation of the draw() operation ² On receipt of the draw() message, each object invokes the draw() operation specified by its class ² We can say that each object "decides" how to interpret the draw() message based on its class :Canvas s1:Circle s2:Square s3:Circle s4:Circle 1.draw() 2.draw() 3.draw() 4.draw() © Clear View Training 2010 v2.6 27 BankAccount example ² We have overridden the deposit() operation even though it is not abstract. BankAccount withdraw() calculateInterest() deposit() CheckingAccount DepositAccount withdraw() calculateInterest() withdraw() calculateInterest() Bank 0..*1 ShareAccount withdraw() calculateInterest() deposit() © Clear View Training 2010 v2.6 28 Key points ² Generalisation, specialisation, inheritance ² Subclasses § inherit all features from their parents including constraints and relationships § may add new features, constraints and relationships § may override superclass operations ² A class that can’t be instantiated is an abstract class © Clear View Training 2010 v2.6 29 UML State Diagram Lecture 4/Part 3 © Clear View Training 2010 v2.6 30 State machines ² Models life stages of a single model element – e.g. object, use case, module ² Every state machine exists in the context of a particular model element that: § Has a clear life history modelled as a progression of states, transitions and events § Responds to events dispatched from outside of the element ² There are two types of state machines: § Behavioural state machines - define the behaviour of a model element § Protocol state machines - model the protocol of a classifier • E.g. call conditions and call ordering of an interface that itself has no behaviour Off On Off On turnOff burnOut light bulb turnOn © Clear View Training 2010 v2.6 31 Basic state machine syntax ² State = a situation or condition during the life of an object § Determined at any point in time by the values of its attributes, the relationships to other objects, or the activities it is performing. ² Every state machine should have one initial state which indicates the first state of the sequence ² Unless the states cycle endlessly, state machines should have a final state which terminates its lifecycle A B anEvent initial state transition event state final state Color red : int green : int blue : int How many states? © Clear View Training 2010 v2.6 32 State syntax ² Actions are instantaneous and uninterruptible § Entry actions occur immediately on state entry § Exit actions occur immediately on state leaving ² Internal transitions occur within the state. They do not fire transition to a new state ² Activities take a finite amount of time and are interruptible EnteringPassword entry/display passwd dialog exit/validate password keypress/ echo "*" help/display help do/get password entry and exit actions internal transitions internal activity Action syntax: eventTrigger / action Activity syntax: do / activity state name © Clear View Training 2010 v2.6 33 Transitions A B event1, event2 [guard condition] / act1, act2 behavioral state machine C D [precondition] event1, event2 / [postcondition] protocol state machine {protocol} Protocol state machine Specifies legal sequences of events. Behavioral state machine Specifies object’s reactions to events. events guard condition actions precondition events postcondition © Clear View Training 2010 v2.6 34 ² Choice pseudo state directs its single incoming transition to one of its outgoing transitions § Each outgoing transition must have a mutually exclusive guard condition § Equivalent to two outgoing transitions from one state ² Junction pseudo state connects multiple incoming transitions into one (or more) transitions. § When there are more outgoing transitions, they must have guard conditions Unpaid FullyPaid PartiallyPaidOverPaid [payment == balance] [payment > balance] [payment < balance] acceptPayment acceptPayment makeRefund BankLoan choice pseudo-state Choice and junction pseudo states junction pseudo state © Clear View Training 2010 v2.6 35 Events ² "The specification of a noteworthy occurrence that has location in time and space" ² Events trigger transitions in state machines ² Events can be shown externally, on transitions, or internally within states (internal transitions) ² There are four types of event: § Call event § Signal event § Change event § Time event Off On turnOff turnOn event © Clear View Training 2010 v2.6 36 close() Call event ² A call for an operation execution ² The event should have the same signature as an operation of the context class ² A sequence of actions may be specified for a call event - they may use attributes and operations of the context class ² The return value must match the return type of the operation InCredit deposit(m)/ balance = balance + m AcceptingWithdrawal entry/ balance = balance - m RejectingWithdrawal entry/ logRejectedWithdrawal() withdraw(m) [balance < m] withdraw(m) [balance >= m] internal call event action conditionexternal call event entry action SimpleBankAccount © Clear View Training 2010 v2.6 37 close() Signal events ² A signal is a package of information that is sent asynchronously between objects InCredit deposit(m)/ balance = balance + m AcceptingWithdrawal entry/ balance = balance - m RejectingWithdrawal entry/ logRejectedWithdrawal() withdraw(m) [balance < m] withdraw(m) [balance >= m] SimpleBankAccount OverdrawnAccount send a signal «signal» OverdrawnAccount date : Date accountNumber : long amountOverdrawn : long Calling borrowerOverdrawnAccount signal receipt © Clear View Training 2010 v2.6 38 close() Change events ² The action is performed when the Boolean expression transitions from false to true § The event is edge triggered on a false to true transition § The values in the Boolean expression must be constants, globals or attributes of the context class ² A change event implies continually testing the condition whilst in the state InCredit deposit(m)/ balance = balance + m balance >= 5000 / notifyManager() AcceptingWithdrawal entry/ balance = balance - m RejectingWithdrawal entry/ logRejectedWithdrawal() withdraw(m) [balance < m] withdraw(m) [balance >= m] SimpleBankAccount OverdrawnAccount Boolean expression © Clear View Training 2010 v2.6 39 Time events ² Time events occur when a time expression becomes true ² There are two keywords, after and when ² Elapsed time: § after( 3 months ) ² Absolute time: § when( date =20/3/2000) Overdrawn balance < overdraftLimit / notifyManager Frozen after( 3 months ) Context: CreditAccount class © Clear View Training 2010 v2.6 40 Composite states ² Have one or more regions that each contain a nested submachine § Simple composite state • exactly one region § Orthogonal composite state • two or more regions ² The final state terminates its enclosing region – all other regions continue to execute ² The terminate pseudo-state terminates the whole state machine A composite state A B C region 1 region 2 submachines Another composite state D E F terminate pseudo-state © Clear View Training 2010 v2.6 41 [dialtone] after(20 seconds)/ noDialtone after(20 seconds)/ noCarrier [carrier] cancel Simple composite states do/ dialISP DialingISP entry/ offHook WaitingForDialtone Dialing WaitingForCarrier entry pseudo state notConnected dial connectedexit pseudo-state NotConnected Connected entry/ onHook exit/ onHook do/ useConnection ISPDialer the nested states inherit the cancel transition © Clear View Training 2010 v2.6 42 Orthogonal composite states ² Has two or more regions ² When we enter the superstate, both submachines start executing concurrently - this is an implicit fork do/ initializeSecuritySensor Initializing InitializingFireSensors do/ initializeFireSensor InitializingSecuritySensors Initializing composite state details do/ monitorSecuritySensor Monitoring MonitoringFireSensors do/ monitorFireSensor MonitoringSecuritySensors fire intruder Monitoring composite state details Synchronized exit - exit the superstate when both regions have terminated Unsynchronized exit - exit the superstate when either region terminates. The other region continues © Clear View Training 2010 v2.6 43 Key points ² Behavioral and protocol state machines ² States § Initial and final § Exit and entry actions, activities ² Transitions § Guard conditions, actions ² Events § Call, signal, change and time ² Composite states § Simple and orthogonal composite states