CompSci 230 S2 2015 Software Construction UML & Use Cases & Class Diagrams Agenda & Reading Topics: Introduction to UML Introduction to Use Case modelling D. G. Firesmith, “Use Cases: the Pros and Cons”, in The Wisdom of the Gurus, SIGS Reference Library,1996. Available: http://www.ksc.com/article7.htm. To learn more (optional reading): 2 Essentials of class diagrams and sequence diagrams Reading: What? A process of determining what the stakeholders require – by decomposing their requirements into tasks (or “use cases”) for each class of stakeholders. How? Stakeholder Identification, Requirements Elicitation, Use Case Diagrams Why learn this? Use cases are widely used in the industry, because they seem to work pretty well, they aren’t very expensive to develop, and they are at a good level of detail for end-users. A. Ramirez, “Requirements Capture”, in ArgoUML User Manual, v0.34, 2011. Object Management Group, “Use Cases”, in OMG Unified Modeling Language (OMG UML) Superstructure, v 2.4.1, 6 August 2011. 04 Software Design (review) Communication: Planning: implement the software, with assured quality. Deployment: 3 develop structure diagrams and use cases, maybe some other UML artifacts. Construction: list tasks, identify risks, obtain resources, define milestones, estimate schedule. Modeling: identify stakeholders, find out what they want and need. deliver the software, then get feedback for possible revision. 04 UML Unified Modeling Language (UML) When creating complex OO systems, where do we start? When building complex systems, it might be worthwhile to plan things out before you start coding! The UML is a standard notation for writing software blueprints UML is a language which allows us to graphically model an OO system in a standardised format. This helps us (and others!) understand the system. There are many different UML diagrams, allowing us to model designs from many different viewpoints. Roughly, there are 4 When building a house, we usually have a set of plans. Structure diagrams (documenting the architecture), e.g. class diagrams Behaviour diagrams (documenting the functionality), e.g. use-case diagrams 04 UML Diagrams The UML is used to construct a model of a software system A model is a simplification of reality 5 A model is thus an abstraction that exposes interesting properties while suppressing unnecessary detail A UML model comprises different diagrams, each focusing on a particular aspect of a system State State Diagrams Class Diagrams diagrams Model State State Diagrams Interaction Diagrams diagrams State State Diagrams State Diagrams diagrams State State Diagrams Use case Diagrams diagrams State State Diagrams Activity Diagrams diagrams Component Component Diagrams Deployment Diagrams diagrams 04 Reserve book Update catalogue Borrower Borrow copy of book Librarian A Class diagram shows the static structure of a system in terms of classes, interfaces and their relationships. Return copy of book A Use Case diagram is user-centered and identifies system users (actors) and tasks. : LibraryMember theCopy : Copy : Book returned( ) borrow( theCopy ) returned( ) okToBorrow Not borrowable borrow Borrowable borrowed( ) [last copy] borrowed borrowed( ) [not last copy] A State diagram shows the states and transitions for an instance of particular class (Book in this case). An Interaction (sequence) diagram is concerned with dynamic behaviour and shows how objects exchange messages to fulfil a task. 6 A Deployment diagram shows the deployment of software to hardware entities. browser : PC <<http>> Internet servlet : Server dbms LAN : Server 6 04 Tool Support: ArgoUML? You will draw some class diagrams and use-case diagrams. Options: ArgoUML Supports forward- and reverse-engineering. works ok but missing some features such as an “undo” button – save your versions carefully! Not on lab image – you’ll have to download and unzip the binary distribution in your echome directory (or on your USB pendrive) then double-click on argouml.jar (this is an “executable jarfile”). Any general-purpose drawing package (e.g.Visio) Warning: you’ll have trouble with the fancy arrowheads in UML! Maybe Softwarestencils.com/uml/visio? By hand: 7 Class diagrams Java skeletons. Java classes class diagrams. This is your only option during exams and tests You’ll have to scan your drawings into your assignments (which are submitted online) 04 Stakeholder Identification Identify a variety of stakeholders, by asking yourself: Who is likely to be affected by, or to have an effect on, this system? Classify the stakeholders you know about. Anyone who will directly use the system is a stakeholder. Anyone who will be indirectly affected (in a major way) is a stakeholder. 8 Anyone who pays for, or otherwise controls the design of the system is a stakeholder. Example: Advertisers are important stakeholders for Google’s online search service. Governments are stakeholders, if their laws constrain the design of a system (e.g. because citizens could be greatly harmed by the system). Note: use cases depict the requirements of direct stakeholders (users), but you’ll have to use another method (e.g. natural language) to describe the requirements of indirect and external stakeholders. Reflect on your classification – have you missed an important class? 04 Use Case Analysis To start developing use cases, ask yourself: What useful tasks could be performed by my system, upon request by a user? You probably won’t “get it right” at first. (It’ll never be perfect, but could be improved…) To validate your current set of use cases, talk to stakeholders! Ask them “Would you use a system, if it would help you do …?” If they start telling you how they want the system to handle a use-case, then you have validated this use-case. If they tell you about some other task they’d like the system to help them with, you should document this as a possible use-case. 9 You should record their detailed requirements, in natural language, as notes which accompany your use case. If their detailed requirements are infeasible or contradictory, you should take careful note of this! Your system can’t do everything! Whenever you discover that you can’t deliver on all use cases within your current resources, you should communicate with your stakeholders to negotiate a feasible set. 04 An Example: Video System John’s Video Store is an Information System which supports the following business functions: Recording information about videos the store owns Information about which customer is renting which videos 10 John doesn’t trust his customers to make these entries in their own records! Staff can maintain customer, video and staff information. Access by staff, and also by customers who is asking about themselves. Staff are able to record video rentals and returns by customers. This database is searchable by staff and all customers Privacy requirements: customers cannot access information about other customers, personal information about customers must be accurate and relevant to John’s Video Store, … Managers of the store can generate various reports. 04 Who are the stakeholders? John’s Video Store is an Information System which supports the following business functions: Recording information about videos the store owns Information about which customer is renting which videos 11 John doesn’t trust his customers to make these entries in their own records! Staff can maintain customer, video and staff information. Access by staff, and also by customers who is asking about themselves. Staff are able to record video rentals and returns by customers. This database is searchable by staff and all customers Privacy requirements: customers cannot access information about other customers, personal information about customers must be accurate and relevant to John’s Video Store, … Managers of the store can generate various reports. 04 What are the tasks? John’s Video Store is an Information System which supports the following business functions: Recording information about videos the store owns Information about which customer is renting which videos 12 John doesn’t trust his customers to make these entries in their own records! Staff can maintain customer, video and staff information. Access by staff, and also by customers who is asking about themselves. Staff are able to record video rentals and returns by customers. This database is searchable by staff and all customers Privacy requirements: customers cannot access information about other customers, personal information about customers must be accurate and relevant to John’s Video Store, … Managers of the store can generate various reports. 04 System Requirements Documentation Use case descriptions A brief statement of what happens during each use case. The previous slide is a good start on this, but it’s not well-organised. Use case diagrams show Stick-figure actors, interacting with the system (a box). Choose easily-understood names for your classes of stakeholders! John’s Video Store might have three actors: Customer, Staff, and Manager. Use case Action (Hmmm… is John an actor? Does he have a special use-case which is so important that we must add it to our diagram? Hold this question…) Ovals (“use cases”) within the box, with easily-understood names, e.g. “Rent a video”. Lines (“associations”) between actors and ovals. include relationship occurs when you have a chunk of behavior that is similar across more than one Use Case 13 Actor use in two or more separate Use Cases to avoid repetition Optionally: arrowheads, extension cases, included cases, subsystems. 04 Example: John’s Video Store John’s Video Store Rent/Return Videos «include» Staff Customer Search for Videos Maintain Customers «include» Maintain Videos Manager Generate Reports John 14 “Include is a DirectedRelationship between two use cases, implying that the behavior of the included use case is inserted into the behavior of the including use case. … “An include relationship between use cases is shown by a dashed arrow with an open arrowhead from the base use case to the included use case. The arrow is labeled with the keyword «include».” [OMG UML v2.4.1, §16.3.5] 04 John’s Video Store, with HR module John’s Video Store Rent/Return Videos Staff «include» Search for Videos Maintain Customers Customer «include» Maintain Videos Manager Generate Reports Maintain Staff List Maintain Manager List John 15 04 Example: Query Health Use Case 16 Finalized: 2011-11-16 http://wiki.siframework.org/Query+Health+-+Consensus+Approved+Use+Case 04 Use Case Descriptions Use case descriptions should be detailed enough that system analysts can design the classes (by grouping attributes and decomposing functions), and determine the non-functional requirements: 17 “what the system should be” (or always be doing), as distinguished from “what the system should do, upon request”; “what the system shouldn’t do” (security requirements); usability, auditability, performance, efficiency, capacity, scalability, extensibility, availability, reliability, integrity, recovery, compatibility, portability, maintainability, transparency, legal conformance, … 04 Semi-formal Use Cases In some development environments (e.g. in the IBM Rational Unified Process), use cases are semi-formal documents with a required structure e.g. Title: the “goal the use case is trying to satisfy” [Fowler, 2004] Main Success Scenario: a numbered list of steps Step: “a simple statement of the interaction between the actor and a system” [Fowler, 2004] Extensions: separately numbered lists, one per extension John’s Video Store Example: a semi-formal use case for SearchForVideos 1. Used by Staff via an application to query for videos by title. 2. Event Flow: 2.1 Repeat Until Exit Program 18 JVS system Search for Videos Staff 2.1.1 Staff types in part of title in text field, 2.1.2 Staff clicks “Search” button and a list of matching videos are returned showing ID and title. If no videos found, goto step 2.2. If error, goto step 2.3. 2.1.3. Staff types in a ID. More information is displayed about the video e.g. rating, price to rent, etc 2.1.4 Exit Program 2.2 No videos found - error message displayed. Goto 2.1.1 2.3 Database Error – error message displayed. Goto 2.1.1 Customer 3. Related Actors and Use Cases: Staff may perform this search for a Customer. No inclusions. Included in Rent/Return Videos and Maintain Videos. 4. Special conditions: NONE 04 Video System – Designing the Classes In this system, information stored includes: Functions this system provides include: 19 Videos - unique ID; title; category (children's, drama, comedy, etc); cost per night to rent; number of copies video store has available; rating Staff - unique ID; name; password; position Customers - unique ID; name; password; address; phone # Rentals - date rented, customer who rent the video and whether video returned Staff can add, update, delete and find videos Staff can add, update, delete and find people. Staff can rent out videos to customer and indicate videos have been returned. Various reporting functions e.g. number of videos rented this month are provided for managers. 04 Class Diagrams Class diagrams represent the static structure of systems. They are made up of classes (or objects) which are interrelated. The main relationships between classes are generalisation and association. UML class notation is a rectangle divided into three parts: class name, attributes, and operations. Super Generalisation … Association Associated Sub1 Attribute1: type Operation1() Operation2(): type 20 Sub2 … … Aggregation 1 0..* Pieces … 04 Class Diagrams Class diagrams may include the following structural elements: Interface Package Class name <<interface>> Instance variables Interface name Method signatures These elements can be related, in general, using the following relationships 21 Class Method signatures Inheritance Implements Dependency Association 04 Person Attributes -ID: int -Name: String -price: double=0.0 Attributes & Operations can be labelled according to access and scope. Static members are underlined. Instance members are not. The operations follow this form: <access specifier> <name> : <type> <multiplicity> = <default> Access specifiers appear in front of each member. 22 #ID: int #Name: String #Password: String Product Private (-): can be used only by the owning class Protected (#): can be used by the owing class and descendents of the class Public (+): can be used by any other class Package (~): can be used by any other class within the package Default value: the value for a newly created object if the attribute isn't specified during creation 04 Operations Attributes & Operations can be labelled according to access and scope. The operations follow this form: <access specifier> <name> ( <parameter list>) : <return type> The parameter list shows each parameter type preceded by a colon. Access specifiers appear in front of each member. Return-type: the type of the returned value, if there is one. Rental -date: String -returned: boolean … +rent(customerID, videoID): boolean +return(customerID, videoID): boolean … 23 04 Generalization & specialization Inheritance Italics indicates an abstract class abstract class Shape { … } class RectangleShape extends Shape { … } 24 04 Dependency & Association Dependency Association public class Employer { private Employee[ ] myEmployees; … } public class Employee { private Employer myEmployer; … } Associations are implemented using instance variables … but Movie knows nothing about Rental Rental knows about Movie 25 public class Movie { private String title; } 04 Multiplicity of Associations Multiplicity specifies how many objects an instance of the class at the other end of the association can be linked to. 0..1 zero or one There are 0 or 1 objects on that end of the association. 0..* / * Zero or more There are 0 or more objects on that end of the association. 1 exactly one Exactly one instance 1..* One or more At lease one instance 2..4 Specified range … 10..300 Student -id: String -phone: String Course 1..5 -name: String -startDate: Date … 26 A Student can take up to five Courses. Student has to be enrolled in at least one course. Up to 300 students can enroll in a course. A class should have at least 10 students. 04 Examples: Multiplicity: There is exactly one teacher per course, as indicated by the 1. A lecturer can teach any number of courses, as indicated by 0..*. We can also write 1..* in a UML diagram. The arrowheads indicate that the taughtBy association is navigable in both directions, telling us that 27 Course has an instance variable teacher, of type Lecturer, and Lecturer has the instance variable Vector<Course> course. 04 Examples: Customer -address: String -phone: String Order 1 0..* Aggregation -date: String -status: String +calcTotal() +calcTotalWeight 1 1..* OrderDetail -quantity: int -taxStatus: String +calcSubTotal() +calcWeight() 1 0..* Item -shippingWeight: double -description: String … +getWeight() +getPriceForQuantity Rents/returns One Customer for each order, but a Customer can have any number of orders. Order has a collection of OrderDetails. An OrderDetail can be queried about its Item, but not the other way around. 28 04 Object interaction diagrams Object interaction diagrams show how class instances behave in terms of sending messages to one another Interaction diagrams give a dynamic view of objects and show how they interact at run-time to fulfil a task Often used to model the way a use case is realized through a sequence of messages between objects. The purpose of Interaction diagrams is to: 29 In UML, a sequence diagram is a popular form of interaction diagram where messages are time-ordered Model interactions between objects Assist in understanding how a system (a use case) actually works Verify that a use case description can be supported by the existing classes Identify responsibilities/operations and assign them to classes 04 Interaction diagram notation Key elements of interaction diagrams are objects and messages (method calls) Active Objects Messages Arrowed lines that indicated communication between objects Notations: 30 “Life line” appears below active objects to indicate their lifespan An instance, named “object”, of an unspecified class An instance, named “object”, of a class named “Class” An unnamed instance of class “Class” m Message m r Message reply r (optional) Object lifeline Focus of control (optional) object object : Class : Class 04 an Order Line Sequence Diagram Object: An object in a sequence diagram is rendered as a box with a dashed line descending from it. The line is called the object lifeline, and it represents the existence of an object over a period of time. an Order Line Messages 31 Messages are rendered as horizontal arrows being passed from object to object as time advances down the object lifelines. Conditions ( such as [check = “true”] ) indicate when a message gets passed a Stock Item check() [check = “true”] remove() 04 Sequence Diagram Return: Notice that the bottom arrow is different. The arrow head is not solid, and there is no accompanying message. an Order Line a Stock Item check() 32 This arrow indicates a return from a previous message, not a new message. [check = “true”] remove() 04 Sequence Diagram an Order a Order Line Iteration: An iteration marker, such as * (as shown), or *[i = 1..n] , indicates that a message will be repeated as indicated. * prepare() Iteration marker 33 04 an Order Entry window an Order an Order Line a Stock Item prepare() Condition * prepare() Object [Fowler,97] check() [check = “true”] remove() needsToReorder() Message Iteration Self-Delegation Return [needsToReorder = “true”] new A Reorder Item [check = “true”] new A Delivery Item Creation 34 04 Example: Part of a Vending Machine 35 04 Example: ATM 36 04 Banking task: applying interest to a savings account driver : Customer : SavingsAccount balance : Money Points to note: accounts( ) applyInterest( ) Sequence diagrams are timeordered Actual arguments can include literals or references to participating objects multiply( 0.08 ) interest create( ) interest : Money add( interest ) create( ) newBalance newBalance : Money create( Transaction.INTEREST, interest, this ) : Transaction 37 04 Review Use cases are functional descriptions of what the system should do for its users. 38 Use case diagrams depict Actors, the system, and the tasks performed by the system that are important to the Actors. If use case descriptions are sufficiently detailed, then they are very helpful in OO design. Use case diagrams are orthogonal to OO design, except in their identification of Actors (= classes of users). Use cases are commonly used in commercial software development, but there are some important alternatives. A UML class diagram shows the “bare bones” of an OO system design. Class diagrams represent the static structure of systems. UML sequence diagram represent behaviour in terms of interactions. 04