Presentation is loading. Please wait.

Presentation is loading. Please wait.

Methods for Software Specification

Similar presentations


Presentation on theme: "Methods for Software Specification"— Presentation transcript:

1 Methods for Software Specification
Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava

2 Used literature COCKBURN, A. Use Cases Jak efektivně modelovat aplikace. CP Books, a.s., ISBN FOWLER, M. UML Distilled: A Brief Guide to the Standard Object Modeling Language. Addison-Wesley Professional, ISBN GAMMA, E., HELM, R., JOHNSON, R. AND VLISSIDES, J.M. Design Patterns: Elements of Reusable Object-Oriented Software. 1st ed.: Addison-Wesley Professional, ISBN PFLEEGER, S.L. AND ATLEE, J.M. Software Engineering: Theory and Practice. Prentice Hall, ISBN POHL, K. Requirements Engineering: Fundamentals, Principles, and Techniques. Springer, ISBN PRESSMAN, R.S. Software engineering : a practitioner's approach. 7th ed. New York: McGraw-Hill Higher Education, xxviii, 895 p. p. ISBN SOMMERVILLE, I. Software engineering. 9th ed. Harlow: Addison-Wesley, xxiii, 840 p. p. ISBN WARMER, J. AND KLEPPE, A. The Object Constraint Language: Getting Your Models Ready for MDA. Addison-Wesley Professional, ISBN

3 Software engineering The IEEE Computer Society defines software engineering as: “(1) The application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software; that is, the application of engineering to software. (2) The study of approaches as in (1).”1

4 Software development „reality“

5 Users‘ vs. developers‘ view
How developers see users Users don’t know what they want. Users can’t articulate what they want. Users are unable to provide usable statements of needs. Users have too many needs that are politically motivated. Users want everything right now. Users can’t remain on schedule. Users can’t prioritize needs. Users are unwilling to compromise. Users refuse to take responsibility for the system. Users are not committed to development projects. How users see developers Developers don’t understand operational needs. Developers can’t translate clearly stated needs into a successful system. Developers set unrealistic standards for requirements. Developers place too much emphasis on technicalities. Developers are always late. Developers can’t respond quickly to legitimately changing needs. Developers are always over budget. Developers say “no” all the time. Developers try to tell us how to do our jobs. Developers ask users for time and effort, even to the detriment of the user’s important primary duties.

6 Software process – key disciplines

7 Requirement specifications
Requirements expressed in : Natural language sentences Structured natural language Design description language Graphical notations Formal specifications

8 Requirements Requirement types: Functional requirements
Requirement is A condition or capability needed by a user to solve a problem or achieve an objective. A condition or capability that must be met or possessed by a system or system component to satisfy a contact, standard, specification, or other formally imposed documents. A document representation of a condition or capability as in (1) or (2). Requirement artifact is a documented requirement. Requirement types: Functional requirements Quality requirements Constraints.

9 SRS should be Correct Unambiguous Complete Consistent Ranked for importance and/or stability Verifiable Modifiable Traceable

10 Functional requirements
Functional requirements are statements of services that a system should provide, how the system should react to particular inputs and how the system should behave in a particular situation. In some cases, functional requirements may also state what the system should not do. Example: If a sensor detects that a glass pane is damaged or broken, the system shall inform the security company, Mainly defines: data, functions, and behavior.

11 Quality requirements I
A quality requirement defines a quality property of the entire system or of a system component, service, or function. Types of quality requirements Important primarily for developers Maintainability Portability Reusability Testability Important primarily for users Availability Efficiency Flexibility Integrity Interoperability Reliability Robustness Usability Availability Availability refers to the percentage of time during which the system is actually available for use and fully operational. Is there a maximum time allowed for restarting the system after a failure. How often will the system be backed up? Must backup copies be stored at a different location? Must the system detect and isolate faults? What is the described mean time between failures? Should precautions be taken against fire or water damage? Efficiency (performance) Efficiency is a measure of how well the system utilizes hardware recources such as processor time, memory,, or communication bandwidth. Are there constraints on execution speed, response time or throughput? What efficiency measures will apply to resource usage and response time? How much data will flow through the system? How often will data be received or sent? Flexibility It indicates how much effort is needed to extend the system with new capabilities. Integrity (Security) Integrity denotes how well the system is protected against unauthorized access, violations of data privacy, information loss, and infections through maleficent software. Must access to the system or information be controlled? Should each user’s data be isolated from the data of the other user? Should user programs be isolated from other programs and from the operating system? Should precautions be taken against theft or vandalism?

12 Quality requirements II
A quality requirement defines a quality property of the entire system or of a system component, service, or function. Types of quality requirements Important primarily for developers Maintainability Portability Reusability Testability Important primarily for users Availability Efficiency Flexibility Integrity Interoperability Reliability Robustness Usability Interoperability It indicates how easily the system can exchange data or services with other systems. Reliability Reliability is the probability of the system executing without failure for a specific period of time. Robustness Robustness is the degree to which a system or component continues to function correctly when confronted with invalid inputs, defects in connected systems or components, or unexpected operating conditions. Usability and human factors Usability measures the effort the user requires to prepare input for, operate, and interpret the output of the system. What kind of training will be required for each type of user? How easy should it be for a user to understand and use the system? How difficult should it be for a user to misuse the system? Precision and Accuracy How accurate must data calculations be? To what degree of precision must calculations be made?

13 Quality requirements III
A quality requirement defines a quality property of the entire system or of a system component, service, or function. Types of quality requirements Important primarily for developers Maintainability Portability Reusability Testability Important primarily for users Availability Efficiency Flexibility Integrity Interoperability Reliability Robustness Usability Maintainability It indicates how easy it is to correct a defect or make a change in the system. Will maintenance merely correct errors, or will it also include improving the system? When and in what ways might the system be changed in the future? How easy should it be to add features to the system? Portability It relates to the effort it takes to migrate a system or component form operating environment to another. How easy should it be to port system from one platform (computer, OS) to another? Reusability It indicates the extent to which a component can be used in systems other than the one for which it was initially developed. Testability It refers to the ease with which the software components or integrated system can be tested to find defects.

14 Non-functional requirements
Underspecified functional requirements Quality requirements The system shall be secure. Each user must log in to the system with their user name password prior to using the system. The system shall remind the user every four weeks to change the password. When the user changes the password, the system shall validate that the new password is at least eight characters long and contains alphanumeric characters. Users‘ password stored in the system must be protected against password theft.

15 Constraints I. Organizational process Design (operational environment)
A constraint is an organizational or technological requirement that restricts the way in which the system shall be developed. Organizational process Resources Documentation Standards Design (operational environment) Physical environment Interface Users Process Resources What materials, personnel, or other resources are needed to build the system? What skills must the developer have? Documentation How much documentation is required? Should it be online, in book format, or both? To what audience should each type of documentation be addressed? Standards

16 Constraints II Organizational process Design (operational environment)
A constraint is an organizational or technological requirement that restricts the way in which the system shall be developed. Organizational process Resources Documentation Standards Design (operational environment) Physical environment Interface Users Design Physical environment Where is the equipment to be located? Is there one location or several? Are there any environment restrictions, such as temperature, humidity, or magnetic interference? Are there any constraints on the size of the system? Are there any constraints on power, heating, or air conditioning? Are there constraints on the programming language, because of the existing software components? Interface Is input coming from one or more other systems? Is output going to one or more other systems? Is there a prescribed way in which input/output data must be formatted? Is there a prescribed medium that the data must use? Users Who will use the system? Will there several types of users? What is the skill level of each user?

17 Constraints III Organizational process
A constraint is an organizational or technological requirement that restricts the way in which the system shall be developed. Organizational process Resources Documentation Standards Design (operational environment) Physical environment Interface Users Constraints affecting the system: With respect to current conditions defined by the insurance company, only the security technicians are allowed to deactivate the control function of the system. A fire protection requirement demands that terminals in the sales rooms do not exceed the size 120cm x 90 cm x 20 cm. Constraints affecting the development process: The effort for development of the system must not exceed 480 man-months, The system must be developed using RUP.

18 Creation of textual requirement I
oug deletion T o g s h u t distortion Generalization Universal quantifications – Indicated with words all, every, always, nobody, never, no one. Example: Every, wants to borrow a book, must have an identity card It is questioned by: ”Has there ever been a time when … ” Modal operator possibility It defines what is considered to be possible/impossible. Example: “Manager cannot enter delete order.” It is clarified by asking: ”What would happen if you did … ?” “What prevents you … ?” Model operator of necessity It involves a need and are indicated by use of words like, “should”, “should not”, “must” and “must not”, “ought” and “ought not”. Example: “User must enter his ”. It is clarified by asking: “What would happen if he did not.” Thoughts generalization Specific thoughts

19 Creation of textual requirement II
oug deletion T o g s h u t distortion Distortion Complex equivalence Readers cannot borrow a book if they have a book with expired time. Presuppositions There are hidden presuppositions in sentences. Example: It is questioned: What leads you to believe that … ? Cause and effect – There are defined causalities between actions and human feeling in sentences. It could be questioned by asking: ”How exactly does this cause that?” Mind reading – We presume to know, without direct evidence, what others think or feel. Example: If a user forgets to close an order, then the system reminds him every day by . It is questioned by asking: “How exactly do you know…?” Thoughts generalization Specific thoughts

20 Creation of textual requirement III
oug deletion T o g s h u t distortion Deletion – System is used for book borrowing Unspecified noun There is not a noun specified in the sentences. “Password strong is accepted and then is changed in database.” It is questioned by asking: “Who or what specifically?” Unspecified verb Verb doesn’t specify how the action should be done. Example: System chekcs ID according to the birthday. It is questioned by asking: “How specifically?” Comparison There is a comparison being made here, but this is not made clear. Example: “Calculation of provision is more brisk.” It is clarified by asking:” Compared with what…”. Judgment Judgments are closely allied to comparisons – no need to involve it, although they often do. Missing information about persons who made the judgment that is hidden in. Example: It is clarified by asking: “who is making this judgment, and what grounds are they making it on?” Nominalization Verb is transcribed to noun. This noun is virtual – cannot be felt, touched, smelled, who actual order “accountant is responsible for invoice editing” “System is used for borrowing.” It is clarified by asking: ”Who is nominalizing about what, and how they are doing it.” Thoughts generalization Specific thoughts

21 Use cases Benefits: goal identification, exceptional situation.
Use case is specification of a sequence of actions, including variants that a system (or other entity) can perform, interacting with actors of the system. Benefits: goal identification, exceptional situation. It is a contract between the stakeholders of the system about its behavior. It shows how a system responds to a request from one of the stakeholders, called the primary actor. The primary actor initiates an interaction with the system. Use cases are mainly described in a text form but it could be written using flow charts, sequence charts, Petri nets, or programming languages. Text is preferred – it is untestable by stakeholders. History Ivar Jacobson invented use cases (in 1960s). He worked on telephony systems at Ericsson. Two decades later, his use cases were introduced on OOPSLA to the community of object-oriented developers.

22 Requirements and use cases
They are really requirements Cover only a part of requirements – it lacks: External interface, Data format Business rules, Complex formulae. Cover one third of all requirements. They express real requirements and they don’t need alternative way of representation. They properly describe what system should do. They don’t express all of the requirements. They captures only one third of all requirements that need to be captured. They miss: detail external interfaces; data formats; business rules; complex formulae.

23 Use case structure Scope: <design scope, what system is being considered black-box under design> Level: <one of: Summary, User-goal, Subfunction> Primary Actor: <a role name for the primary actor, or description> Stakeholders & Interests: <list of stakeholders and key interests in the use case> Precondition: <what we expect is already the state of the world> Minimal Guarantees: <how the interests are protected under all exits> Success Guarantees: <the state of the world if the goal succeeds> Scope identifies the system that is developed. Primary actor is actor that initiates use case. Preconditions and guarantees define condition that should be satisfied before and after the use case runs. Level defines level of the goal. The main success scenario is a case in which everything is successfully performed.

24 Primary actors and stakeholders gathering
Actors have goals supported by described system. The system should ensure interests of stakeholders. Interactions between Actors with Goals Actors have goals Goals can fail Interactions are compound A use case collects scenarios Contract between Stakeholders with Interests Their gathering is important because users have goals and will use constructed system to achieve their goal. Users are suitable sources of use cases – use cases correspond to the supported user goals. Use case execution should ensure that stakeholder interests are preserved

25 Design scope is the extent of the system
Design scope is the extent of the developed system. It is the class of systems, hardware and software, that are considered during development. It is system‘s boundary. It is very important for the writer and reader to understand the same design scope of the system.

26 Design scope II "Enterprise" scope "System" scope "Subsystem" scope
We should give proper names to important system parts to distinguish between them. What can we do to clear up these misunderstandings? "Enterprise" scope describes the behavior of the entire organization or enterprise in providing of the goal of the primary actor (of the whole enterprise). It is better to name this scope with the company name to prevent misunderstanding.

27 Design scope III "Enterprise" scope "System" scope "Subsystem" scope
"System" scope defines a part of hardware/software you are developing. Outside the use case are all the parts of other systems that communicate with this through an interface.

28 Design scope is the extent of the system
Design scope IV Design scope is the extent of the system "Enterprise" scope "System" scope "Subsystem" scope "Subsystem" scope defines only limited parts of the system – it shows how these work together. It is useful to attach a graphic symbol to the left of the use case title. Use cases should be written from black box or white box perspective. In black box perspective, we are not interested how the system works whilst in a white-box perspective we do.

29 THREE NAMED GOAL LEVELS
Level of goals depicts activities on different level of abstraction and helps to understand them.

30 THREE NAMED GOAL LEVELS II
The user goal is the goal of the greatest interest. It is the goal of the primary actor. He is working with the system to satisfy his needs. It defines "elementary business process" in the business process engineering literature. It will be defined by question "Can the primary actor go away happy after having done this?" For an accountant, it would be, "Sending invoice to a customer". It is performed by one person. It holds one sitting (2-20 minutes

31 THREE NAMED GOAL LEVELS III
Summary-level goal contains more than one user goal. It is used to describe system: It shows the context in which the user goals operate, It shows life-cycle sequencing of related goals, It provides a list of lower-level use cases. It is performed by more than one person. It is typically executed over hours, days, weeks, months, or years.

32 THREE NAMED GOAL LEVELS IV
Subfunction-level goals are executed during use case-s on user level. It is necessary to define them to improve readability or if many use cases use them. Examples of subfunction use cases are "Find a customer", "Sort a table", "Log into a system."

33 Use case structure I Context of use: <a longer statement of the goal, if needed, its normal occurrence conditions> Scope: <design scope, what system is being considered black-box under design> Level: <one of: Summary, User-goal, Subfunction> Primary Actor: <a role name for the primary actor, or description> Stakeholders & Interests: <list of stakeholders and key interests in the use case> Precondition: <what we expect is already the state of the world> Trigger: <what starts the use-case may be a time event> Minimal Guarantees: <how the interests are protected under all exits> Success Guarantees: <the state of the world if the goal succeeds> Preconditions The Precondition of the use case defines what condition should be satisfied before the use case can start. They are not checked in use case again. A common example is, "the user has already logged on and has been authorized". Generally, a precondition indicates that some other use case has already run, to set up the condition. Triggers The Trigger defines what event start the use case. Sometimes the trigger precedes the first step of the use case. Sometimes it is the first step of the use case.

34 Use case structure II Context of use: <a longer statement of the goal, if needed, its normal occurrence conditions> Scope: <design scope, what system is being considered black-box under design> Level: <one of: Summary, User-goal, Subfunction> Primary Actor: <a role name for the primary actor, or description> Stakeholders & Interests: <list of stakeholders and key interests in the use case> Precondition: <what we expect is already the state of the world> Trigger: <what starts the use-case may be a time event> Minimal Guarantees: <how the interests are protected under all exits> Success Guarantees: <the state of the world if the goal succeeds> Minimal Guarantees The Minimal Guarantees are the least promises the system makes to the stakeholders in every case even when the primary actor’s goal cannot be provided. The Minimal Guarantee is written as a number of simple assertions. Minimal Guarantee: Order will be initiated only if payment received. The acceptance test for them is that the stakeholders would agree that their interests had been protected under all condition.

35 Use case structure III Context of use: <a longer statement of the goal, if needed, its normal occurrence conditions> Scope: <design scope, what system is being considered black-box under design> Level: <one of: Summary, User-goal, Subfunction> Primary Actor: <a role name for the primary actor, or description> Stakeholders & Interests: <list of stakeholders and key interests in the use case> Precondition: <what we expect is already the state of the world> Trigger: <what starts the use-case may be a time event> Minimal Guarantees: <how the interests are protected under all exits> Success Guarantees: <the state of the world if the goal succeeds> Success Guarantee The Success Guarantee states what interests of the stakeholders are satisfied after a successful execution of the use case. The Success Guarantee is generally written to add onto the Minimal Guarantee: all of the Minimal Guarantee is delivered, and some extra conditions are true. The acceptance test for the Success Guarantee section is that the stakeholders agree that their interests have been satisfied by use case execution. The best way to uncover the success guarantee is to ask, "What would make this stakeholder unhappy at the end of a successful run?"

36 Scenarios and steps I Main success scenario – a typical scenario in which the primary actor’s goal is delivered and stakeholder‘s interests are satisfied Common surrounding structure Condition of scenario a goal to achieve a set of action steps an end condition, a possible set of extensions. The scenario body an interaction between two actors, a validation step to protect an interest of a stakeholder, an internal change to satisfy a stakeholder. Main success scenario It describes a fairly typical scenario in which the primary actor’s goal is delivered and all stakeholders’ interests are satisfied.

37 Scenarios and steps II Main success scenario
Common surrounding structure condition of scenario goal to achieve set of action steps end condition, possible set of extensions. The scenario body an interaction between two actors, a validation step to protect an interest of a stakeholder, an internal change to satisfy a stakeholder. The main success scenario and scenario extensions sit within the same structure. That consists of: A condition under which the scenario runs. For the main success scenario, this is the use case precondition plus the use case trigger. For an extension scenario, this is the extension condition (perhaps with the step number or place in the scenario where that condition applies). A goal to achieve. For the main success scenario, this is exactly the use case name, satisfying, of course, the stakeholders’ interests. For an extension scenario, the goal is either to complete the use case goal or to rejoin the main success scenario after handling the condition. A set of action steps. These form the body of the scenario, and follow the same rules in every scenario or scenario fragment. An end condition. The goal is achieved at the end of the main success scenario. A scenario fragment may end with the goal either being achieved or abandoned. A possible set of extensions, written as scenario fragments. Extensions to the main success scenario are placed in the Extensions section of the use case template. Extensions to extensions are placed directly inline, inside or just after the extension body

38 Scenarios and steps III
Main success scenario Common surrounding structure Condition of scenario a goal to achieve a set of action steps an end condition, a possible set of extensions. Scenario body interaction between two actors, validation step to protect interest of the stakeholder, internal change to satisfy the stakeholder. Every scenario or fragment is written as a sequence of goal-achieving actions by the various actors.

39 Different level of goals and precondition
The use case on the summary level gives context for use-cases on lower levels. The precondition indicates the use-case performed previously. As we have already said, a precondition indicates that some other use case has already run, to set up the condition. Place an Order, relies on a precondition ("logged on"). It indicates that some use case was executed a produced state in which a user is logged. A higher-level use case that mentions both use cases could be created - Use the application.

40 Action Steps – guideline 1: It uses simple grammar
Subject ... verb... direct object... prepositional phrase. Example: The system ... computes ... provision... from the invoiced amount. The sentence structure should be very simple: Subject ... verb... direct object... prepositional phrase. Example: The system ... computes ... provision... from the invoiced amount.

41 Action Steps – guidelines 2: It shows clearly, "Who has the ball“.
At each step one actor "has the ball". That actor is going to be the subject of the sentence, the first actor named, probably as the first or second word in the sentence. The "ball" is the message and data that gets passed from actor to actor. A useful visual image is that of friends battering a soccer ball around. Sometimes person 1 kicks it to person 2, and then person 2 dribbles it a while, then kicks it to person 3. Occasionally it gets muddy, and one of the players wipes the mud off. A scenario has the same structure. At each step one actor "has the ball". The "ball" is the message and data that gets passed from actor to actor.

42 Action Steps – guidelines 3: It is written from a bird's eye point of view.
Beginning use case writers write the scenario as seen by the system: Get an ATM card and PIN number. Deduct the amount from the account balance. X A better form is: The customer inserts the ATM card and PIN. The system deducts the amount from the account balance. v Beginning use case writers, particularly programmers who have been given the assignment of writing a use case document, often write the scenario as seen by the system, looking out at the world, and talking to itself. The sentences have the appearance: "Get ATM card and PIN number. Deduct amount from account balance." Write the use case from a bird's eye point of view: The customer puts in the ATM card and PIN. The system deducts the amount from the account balance.

43 Action Steps - guideline 4: It shows the process moving distinctly forward
Avoid small steps – find a slightly higher-level goal for a step, ask "Why is the actor doing that?“. Example: A user hits the tab key. Why is the user hitting the tab key? To get to the address field. Why is he trying to get to the address field? Because he has to enter her name and address before the system does anything. A user enters name and address. The amount of progress made in one step is related to how high or low the use case goal is. In the summary or user level of use case, the step probably moves forward the entire user goal. In a subfunction use case, it moves forward a much smaller amount. If we see the step "User hits the tab key", either it indicates a subfunction level of the goal or the writer has chosen too small level of an action to describe. Choosing very small steps causes uselessly long use cases - if a use case has 13 or 17 steps, it often indicates steps on very low level of actions. Example: User hits tab key. Why is the user hitting the tab key? To get to the address field. Why is he trying to get to the address field? Because he has to enter her name and address before the system does anything. Actually, it is a written level of action - User enters name and address.

44 more data items being passed
Action Steps – guidelines 5: It shows the actor’s intentions, not movements. It is user interface designer’s job to invent a user interface but we are interested in the semantic description of the interface in the requirements document 1. System asks for name. 2. User enters name. 3. System prompts for address. 4. User enters address. 5. User clicks ’OK’. 6. System presents user’s profile. 1. User enters name and address. 2. System presents user’s profile. more data items being passed Customer enters name, address, phone number, secret information, emergency contact phone number. Describing the user’s movements during using of user interface is one of the more common mistakes – it causes writing goals at too low level. Effective user interface is invented by designer not by analyst – writer of the use case. Customer enters - name - address - phone number - secret information - emergency contact phone number

45 Action Steps – guidelines 6: It contains a ’reasonable’ set of actions.
The primary actor sends a request and data to the system. The system validates the request and the data. The system alters its internal state. The system replies to the actor with the result. Version 1 – All interaction are in one step. Version 2 – a/ 1. b/ 2., 3., 4. Version 3 – a/ 1. b/ 2. c./ 3., 4. Version 4 – a/ 1. b/ 2. c./ 3. d/ 4. Version 5 – a/ 1. b/ 2. c./ 3. d/ 4( to an actor a) e/ 4 (to an actor b) Ivar Jacobson has described a step in a use case as representing a transaction where 4 types of interaction should perform. 5 variants of their composition could be identified and none of them is wrong: 1 is too complicated to read easily. Version 2 is good when the pieces are simple but could be complicated. Version 3 is often preferred. Version 4 is also good. Action steps in version 5 are a bit too small, making the scenario too long. However, version 5 does have the advantage – steps are separated and can be easily tested.

46 Action Steps – guidelines 7: It doesn’t "check whether", it "validates“
Verifying step is often written as “System … checks” it is not a good action verb because it does not move process distinctly forward – it is followed by “If the (condition) … ” 2. The system checks whether the password is correct 3. If it is, the system presents available actions to the user. One kind of interaction step verifies that some business rule is satisfied. Common mistake is that people write that the system checks the condition. This is not a good action verb - it does not move the process distinctly forward. After checking, you immediately have to write "If the check passes..." and "If the check fails". Better formulation is establishing or validating or ensuring something – they are good goal achieving action verbs. 2. The system validates that the password is correct. 3. The system presents available actions to the user.

47 Action Steps – guidelines 8: It optionally mentions the timing
Feel free to put in the timing, but only when you need to. At any time between steps 3 and 5, the user will ... As soon as the user has ..., the system will ... One step usually follows another step in the scenario. Sometimes, you need to write: At any time between steps 3 and 5, the user will .. or As soon as the user has ..., the system will ... Use this construction when you need it but sometimes it is not necessary to mention it.

48 Action Steps – guidelines 9: Idiom: "User has System A, kick System B“
The user hits the FETCH button, at which time the system fetches the data from system B. 4. The user signals to the system to fetch data from system B. 5. The system fetches the background data from system B." You want the developed system to fetch information from system B, or run an interaction with system B. It should only do so when the primary actor says to system A that it is time to do so. It is not very clear to write, "An accountant hits FETCH button, at which time the system fetches the data from system B." – it contains a description of user interface. Note: Comment example. This text indicates that the user defines the timing, the ball passes from the user to the system A to system B and shows the responsibilities of all three actors (user, system A, System B). The details of how the user fires the action is unspecified as it should be. 4. The user has system A, fetch data from system B.

49 Action Steps – guidelines 10: Idiom: "Do steps x-y until condition"
only one step being repeated "The user selects one or more products." "The user searches through various product catalogs until he finds the one he wants to use.„ several steps to be repeated 1. The customer supplies either the account identifier or name and address. 2. The system brings up the customer's preference information. 3. The user selects an item to buy, marks it for purchase. 4. The system adds the item to the customer's "shopping cart". The customer repeats steps 3-4 until indicating that he/she is done. 5. The customer purchases the items in the shopping cart (see use case xxx). Occasionally, some steps can be repeated. Writing a use case as plain prose has an advantage again – we simply mark which step and when repeat.

50 Action Steps – guidelines 10: Idiom: "Do steps x-y until condition“ - II
Variant – “Steps x-y can happen in any order.” 1. The customer logs on 2. The system presents available products and services. Steps 3-5 can happen in any order. 3. The user selects products to buy. 4. The user specifies the preferred form of payment. 5. The user gives the destination address. 6. The user indicates shopping spree is complete. 7. The system initiates an order with the selected products to be charged against the form of payment and to be sent to the destination address. A variant of the previous is "Steps x-y can happen in any order." – it doesn’t define a loop.

51 Extensions I write every scenario individually – bad maintenance
use “if” statements through text - hard to read write a scenario extension for each branch point - best A scenario is a sequence of steps. Use case should contain all of the scenarios, both success and failure. There are three approaches how to write another scenario (besides the main) To write every scenario individually - it is a maintenance nightmare - each change to a scenario has to be copied to all the other scenarios that contain the same text. To write if statements throughout the text: "If the password is good, the system does ..., otherwise the system does.... "- hard to read especially if inside an if. Reader loses track of the behavior after just two “if” branches, and most use cases contain many branching points. To write the main success scenario as a simple sequence running from trigger to completion, and then write a scenario extension for each branch point.

52 Extensions II write every scenario individually – bad maintenance
use “if” statements through text - hard to read write a scenario extension for each branch point - best ... 3. The system goes through the document, checking every word against its spelling dictionary. 4. The system detects a spelling mistake, highlights the word and presents a choice of alternatives to the user. 5. The user selects one of the choices for replacement. The system replaces the highlighted word with the user’s replacement choice. Extensions; 4a. The system detects no more misspellings through the end of the document: 4a1. The system notifies the user, terminates use case. 5a. The user elects to keep the original spelling: 5a1. The system leaves the word alone and continues. 5b. The user types in a new spelling, not on the list: 5b1. The system revalidates the new spelling, returns to step 3.

53 Extensions Conditions
condition under which the system takes different behavior. say extension instead of failure or exception 4. The user has the system save the work so far. ... Extensions; 4a. System auto detects the need for an intermediate save: 4a1. ... 4b. Save fails: 4b1. ... Extension conditions define when the system performs in a different behavior. We say extension but not failure or exception - we can include alternative success as well as failure conditions.

54 Brainstorm all conceivable failures and alternative courses I
Alternate success path - "Clerk uses a shortcut code". The primary actor behaves incorrectly - "Invalid password". Inaction by the primary actor - "Time-out waiting for password". Every occurrence of the phase "the system validates" implies there will be an extension to handle failure of the validation - "Invalid account number". Inappropriate or lack of response from a supporting actor - "Time-out waiting for response“ Internal failure within the system under design, which must be detected and handled as part of normal business - "Cash dispenser jams“. Unexpected and abnormal internal failure, which must be handled and will have an externally visible consequence - "Corrupt transaction log discovered". Critical performance failures of the system that you must detect. - "Response not calculated within 5 seconds". It is important to have good coverage of the extension conditions before definition of an alternative scenario. Brainstorming is used – it is tiring and so is documenting handling of the extensions. On the other hand, having all of the alternative success and failure situations means to have a list of tasks of your work for next several hours or days.

55 Brainstorm all conceivable failures and alternative courses II
Alternate success path - "Clerk uses a shortcut code". The primary actor behaves incorrectly - "Invalid password". Inaction by the primary actor - "Time-out waiting for password". Every occurrence of the phase "the system validates" implies there will be an extension to handle failure of the validation - "Invalid account number". Inappropriate or lack of response from a supporting actor - "Time-out waiting for response“ Internal failure within the system under design, which must be detected and handled as a part of normal business - "Cash dispenser jams“. Unexpected and abnormal internal failure, which must be handled and will have an externally visible consequence - "Corrupt transaction log discovered". Critical performance failures of the system that you must detect. - "Response not calculated within 5 seconds".

56 Action Steps – guidelines 11: The condition says what was detected.
Write down what the system detects, not just what happened. put a colon (’:’) after the condition Customer forgets PIN. PIN entry time-out. Invalid PIN: Network is down: The customer walked away (time-out): Cash did not eject properly: The system can’t detect that users forgot their PIN. Perhaps they walked away, had a heart attack, or are busy quieting a crying baby. What is the system able to detect in this case? Passivity, which really means it detects that the time limit has been exceeded. A colon (’:’) put after the condition means that the reader doesn’t accidently think it is an action step.

57 Extension optimization
Rationalize the extensions list. The system must be able to detect the condition. The system must be obliged to handle detecting the condition. Roll up failures Use Case: Update Investment ... 7. The user has PAF save the work. 8. ... Extensions: 7a. Save fails: 7a1. ...whatever should happen next... Use Case: Save Work ... Extensions: 3a. File already exists (user doesn't want to overwrite): ... 3b. Directory not found: ... 4a. Out of disk space: ... 4b. File write-protected: ... ... and so on... Rationalize the extensions list. Reduction - The ideal extension conditions list shows all the situations the system must to handle and no more. Roll up failures Conditions from lower level are merged in one that has the same effect on a higher level – it prevents having an explosion of extension condition at the higher level. Failures are reported in vocabulary appropriate for the level – it saves time to read

58 Action Steps – guidelines 12: Condition handling is indented.
indent the action step and start numbering again at 1 Extensions 2a. Insufficient funds: 2a1. The system notifies customer, asks for a new amount. 2a2. The customer enters new amount. The action steps in extension follow all the style guidelines given earlier.

59 Failures within failures
Extensions 6a. The clerk decides to exit without completing minimum information: 6a1. The system warns the Clerk it cannot exit and finalize the form without date, name or policy number, or adjuster name provided. 6a1a. The clerk chooses to continue entering loss 6a1b. The clerk saves as "intermediate" report and exits. 6a1c. The clerk insists on exiting without entering minimum information: The system discards any intermediate saved versions and exits. There may occur a new branching condition in extensions – usually some failure. They are simply indented again. Most of the people agree that the maximum level of indentation is three – it is better to create new sub function use case instead of another level of indentation.

60 Creating a new use case from an extension
consider using if The extension is used in several places. The extension makes the use case really hard to read. costs: it must be: Labeled, Tracked, Scheduled, Tested, Maintained. It requires: to define the primary actor’s goal; to create the use case name; to open up the template for a new use case, and fill in other details. The cost of creating a use case is not only the effort needed for the typing. The new use case must be labeled, tracked, scheduled, tested and maintained.

61 Technology & Data Variations
7. Repay customer for returned goods. Technology & Data Variations List: 7a. Repay by check, EFTS, or credit against future purchases. Main Success Scenario: ... 2. The user identifies him/herself, bank, and account #. Technology & Data Variations List: 2a. Use magnetic bank card, eye scan, or fingerprints." It is not extensions – it is rather specialization Extensions define what the system does differently. Sometimes, it is needed to express that "there are several different ways this can be done". What is the same, but how it is done might vary. This is usually because there are some different technology aspects, or some differences in the data representation. These variant are written into the Technology and Data Variations List section but not in the Extensions section.

62 Linking Use Cases I Sub use cases Extension use cases
The user saves the report The user saves the report (UC 35 Save a Report) An action step can be simple or reference to another use case. Writing in specific way indicates there is a use case called Save a Report.

63 Linking Use Cases II Sub use cases Extension use cases
There is a main activity which can be interrupted. It can be interrupted in a number of ways, without the main activity being in control of the interruptions. Example: Word processing example with spellchecker. The user’s main activity is typing. However, the user might suddenly decide to change the zoom factor or another activity. Note: comment list It is uninvited to explicitly name all the interrupting use cases in the base use case – the use case becomes messy and badly maintainable. Every time it gets edited, it might get corrupted, it needs to be versioned, reviewed, etc. Create a new use case - extension use case. It starts with a condition, referencing a situation in the base use case where the condition might occur. Put all that into the Trigger section of the template.

64 When to use extension use case
Many asynchronous or interrupting services. Adding to locked requirement document. Create extension use cases only when you need to. They are harder for people to understand and maintain. Two situations call for extension use cases. When there are many asynchronous or interrupting services the user might use, which should not disturb the base use case (The most common use is). Often, they will be developed by different teams. When you are writing additions to a locked requirements document.

65 When are we done? You have named all the primary actors and all the user goals with respect to the system. You can capture every trigger condition to the system either as a use case trigger or an extension condition. You have written all the user-goal use cases, along with the summary and subfunction use cases needed to support them. Each use case is clearly enough written that: the sponsors agree they will be able to tell whether or not it is actually delivered. the users agree that it is what they want or can accept as system’s behavior. the developers agree they can actually develop that functionality. The sponsors agree that the use case set covers all they want (for now). All primary actors are important to define because they should define their all user goals in context of created system. It is necessary to capture every triggered condition to the system because we define how to system should react to the situations those differs from main scenario. All defined user goals are important because we know which user function and sub function should be described by use cases and have implementation. Finally, agreement between sponsors, users and developers is important. Sponsors agree what functionality they will pay for. Users agree what functionality they will be using. Developers agree what functionality they are able to develop.

66 Special use cases: CRUD
Advice is to keep this use cases separate if you need to keep track of which primary actors have security access to the different functions but start with just one Manage users. If writing of such a use case gets too complex, we set aside a certain part – similarly to a use case from an extension is created.

67 Special use cases: parameterized use cases I
Similar USE-CASES: Find a Customer, Find a Product, Find a Promotion differing in: the name of the thing to be found the searchable qualities (search fields) of the thing to be found what to display about the thing to be found (the display values, in sequence) how to sort the choices (sort criteria). Another typical class of use cases is use cases that do some generic action and just one development team will probably create the generic mechanism for them, and other teams will use it. Writing half-a-dozen similar use cases is not much of a problem with casual use cases. However, writing six similar fully dressed use cases is not good – it introduced redundancy and cost a lot of effort.

68 Special use cases: parameterized use cases II
Similar USE-CASES: Find a Customer, Find a Product, Find a Promotion differing in: the name of the thing to be found the searchable qualities (search fields) of the thing to be found what to display about the thing to be found (the display values, in sequence) how to sort the choices (the sort criteria). Generic USE-CASE: Find a Whatever The clerk finds a customer using customer search details. 1. The user identifies the searchable qualities of the whatever thing. 2. The system finds all matching whatevers and displays their display values on a list. 3. The user can resort them according to the sort criteria. 4. The user selects the one of interest.

69 MISSING REQUIREMENTS UC is only „third chapter of SRS“ – it doesn’t contain – contain performance requirements, business rules, user interface design, data descriptions, finite state machine behavior, priority, etc. Could be attached: use case priority, expected frequency of occurrence, performance needs, delivery date, list of secondary actors, business rules (possibly), open issues. Additional table: primary actor trigger delivery priority estimated complexity probable release performance requirement state of completion ...and whatever else you need. Use cases do not contain performance requirements, business rules, user interface design, data descriptions, finite state machine behavior, priority, and probably some other information. Where are those? Some of them could be attached to each use case: use case priority, expected frequency of occurrence, performance needs, delivery date, list of secondary actors, business rules (possibly), open issues. Contained information depends on the project. There is a simple spreadsheet or table with information in many cases. The table should contain – besides the name: primary actor Trigger delivery priority estimated complexity probable release performance requirement state of completion ...and whatever else you need.

70 Data requirements Required by programmers – includes field check
Three level of precision: Information nicknames, Field lists, or data descriptions, Field details & checks. Information nicknames will: speed up the requirement gathering make use cases shorter and easier to read make use case more durable Enable to refer the same information to other use cases. There are still missing requirements similarly important as behavioral requirements – the data requirements with field check to perform. It is useful to divide the data requirements into three levels of precision: Information nicknames, Field lists, or data descriptions, Field details & checks.

71 Data requirements: information nicknames
only a nickname is used in UC, it will enable speed up the requirement gathering, make use cases shorter and easier to read, make use case more durable enable to refer the same information to other use cases. "Accountant enters customer’s name, address and phone number." Description of each name, address, and phone number is defined in some other place. In use case, nicknames are only used: to speed up the requirements gathering, to make the use cases much shorter and easier to read, and to make them also less brittle (sensitive to changes in the data requirements). it is also likely that many use cases refer the same information nicknames. Therefore, break the details of the data requirements out of the use case, and link from the use case to the relevant field list.

72 Data requirements: field list
describes what fields information links contain. many strategies for dealing with this level of precision: a separate entry for each entry a single entry for a parcel of information that arrives in a single UC step together (name, address, phone number) It contains definition of nicknames - whether "customer's name", consists of two parts, first and last names, or three parts (or more)? What exactly is needed for "address"? There are more strategies how to deal with level of precision: to have a separate entry in your tool for each nicknamed item. We defined that "customer name" has three fields: the customer's first name, middle name, last name to notice that parcel of information arrive together in a single use case step (e.g. name, address and phone number). This is useful information for the user interface designer, since it is quite likely that these three parcels of information will show up together.

73 Data requirements: Field details & checks
Data length specifications & data restrictions Let‘s note: Field details need to be expanded and checked Use case is not a place for expansion Use case should link to the expansion The fields details usually change in time independently from use cases It is the last level of abstraction and it defines information as "How many characters long can the customer's name be?" and "What restrictions are there on Date of Loss?" These are field types, field lengths, and field checks. Some teams put it into: Data requirements or External Data Formats, Field definitions UI data details – interface requirements and design document.

74 Use Cases In Project Organization: Organization of use cases
Analytic: names of use cases with names of primary actors Sponsor: priority of business need Developer: technical difficulty Project planning: to create a table with the use case and primary actor names in the left two columns. the business sponsors put the priority or value to the business of each use case. the development team estimates the complexity or difficulty of delivering that function. This is a natural evolution of Use cases. Over the time, complete the estimates for each use case, assign them to teams, and track the work per use case per release.

75 Use Cases In Project Organization: Use cases cross releases
A complete use case is delivered in one release very occasionally. More often: Deliver the simple case in release 1 Add high-risk handling in release 2 Put preferred customer handling in release 3 Deliver complete scenario. A complete use case is delivered in one release very occasionally. Either you write one use case and deliver a fraction of it in each release, or you write three use cases. The use case says what the user wants to accomplish, and enumerates the many scenarios involved in accomplishing that. When you deliver software, you must deliver some of those scenarios top to bottom, or your application is not delivering usable function. Planning and design must coincide to produce end-user usable collections of functions. Those are full scenarios from the use cases. Functional testers will test for use case compatibility.

76 Use cases to design - I Design doesn’t cluster by use case – parts of business logic or mechanism occur in several use cases. During OO design - don’t mirror functional decomposition by classes. Use cases describe in designed system all and only black-box behavioral requirements for the design to meet – designer has freedom in production of good design that meets the requirements. Design doesn’t cluster by use case. The design tasks do not map themselves exactly to use case units. A design task produces business objects or behavioral mechanisms which could be used in several use cases – for more details see available literature. Object oriented design Functional decomposition is good for requirement but it is not good for an object oriented design. Don’t mirror functional decomposition by classes. Experience shows it as a bad technique.

77 Design makes use of scenarios Use cases name domain concepts
Use cases to design - II Design makes use of scenarios Use cases name domain concepts Design makes use of scenarios Use cases also serve well with other design techniques, showing when the design is complete and handles all situations. Responsibility Based Design is based on designing while stepping through scenarios. Use cases name domain concepts Use cases fairly shout out the names of the domain objects involved. Consider the use case phrase: "System produces an invoice, fills the invoice line items with their costs, adds tax and shipping costs, and produces the total. The invoice footer states the terms of delivery."

78 UML diagrams limitations
Information conveyed by such diagrams has a tendency to be incomplete, imprecise and even inconsistent. Diagrams cannot express the statements that should be a part of a specification. Interpretation of a diagram can be ambiguous.

79 UML Limitations: Example

80 Correct Interpretation of Model

81 Mistaken Interpretation
Object vondrak should pay his products and the amount that has to be paid is given by the sum of both product. This interpretation is not valid but it is correct from the point of view of the class diagram. The class diagram is ambiguous!

82 OCL – Object Constraint Language
OCL is a language that can express additional and necessary information about models and other artifacts used in object-oriented modeling, and should be used in conjunction with UML diagrammatic models. OCL is precise, unambiguous language that is easy for people who are not mathematicians or computer scientists to understand. It does not use any mathematical symbols, while maintaining rigor in its definition. OCL is a typed language, because it must be possible to check an expression included in the specification without having to produce an executable version of the model. OCL is a declarative, side-effects-free language; that is the state of a system does not change because of an OCL expression. UML/OCL enables to build models completely platform-independent. Základní typy jsou – String, Real, Integer, Boolean. Kolekce

83 How to Combine UML and OCL
Rules related to the class diagram of an e-shop: A payment is valid only when the products ordered by a customer are paid by the same customer. The address has to be unique. The payment sum is given by the sum of all ordered products’ prices. The customer has to pay the amount of money equal to the payment sum.

84 OCL Expressions Rules related to the class diagram of an e-shop:
A payment is valid only when the products ordered by a customer are paid by the same customer. The address has to be unique. The payment sum is given by the sum of all ordered products’ prices. The customer has to pay the amount of money equal to the payment sum. context Payment inv: self.items->forAll (item | item.buyer = payer) context Customer inv: Customer::allInstances()->isUnique( ) context Payment inv: self.items.price->sum() = self.sum context Customer::pay(amount: float) pre: self.remittance.sum = amount

85 context <Context for expressions>
OCL anatomy context <Context for expressions> <type of OCL>: <expressions> Types of OCL constructions: inv – invariants pre, post – pre and post condition derive – derived attribute body – query functions Init – initial value

86 Types in OCL Boolean Integer Real String
User defined – classes, enumeration Collection

87 Boolean operators Simple operators Ternary operatory a or b a and b
a xor b not a a implies b a = b a <> b Ternary operatory if <boolean OCL expression> then <OCL expression> else <OCL expression> endif

88 Integer and Real operators
=,<>, <, >, <=, >=, +, -, *, / a.mod(b), a.div(b) , a.abs(), a.max(b), a.min(b), a.round(), a.floor(), 2654 * = (3.2).floor() / 3 = 1 1.175 * (-8.9).abs() - 10 = 12 > 22.7 = false 12.max(33) = 33 33.min(12) = 12 13.mod(2) = 1 13.div(2) = 6 33.7.min(12) = 12.0 -24.abs() = 24 (-2.4).floor() = -3

89 String operators string1.concat(string2), string.size(), string.toLower(), string.toUpper(), string.substring(int1, int2), string1 = string2, string1 <> string2 'Anneke'.size() = 6 ('Anneke' = 'Jos') = false 'Anneke '.concat('and Jos') = 'Anneke and Jos' 'Anneke'.toUpper() = 'ANNEKE' 'Anneke'.toLower() = 'anneke' 'Anneke and Jos'.substring(12, 14) = 'Jos'

90 Invariants An invariant is a constraint – a boolean expression - that should be true for an object during its complete lifetime. Invariants on attributes context Product inv ofPrice: self.price >= 0 Invariants on associated objects context Payment inv ofAge: payer.age >= 18 Keyword self means reference to a given instance. Its use is mandatory in the case of ambiguity only.

91 context Customer inv ofAge: age >= 18 Attribute age of every customer object must be equal to or greater than 18.

92 validFrom should be earlier than goodThru.
context CustomerCard inv checkDates: validFrom.isBefore(goodThru) validFrom should be earlier than goodThru.

93 Working with association I.
Multiplicity at least one enables direct access to object. result of expression “self.payer.name” in context of Payment is the name of Customer associated with Payment

94 Every owner of CustomerCard has age greater than or equal to 18.
context CustomerCard inv ofAge: owner.age >= 18 Every owner of CustomerCard has age greater than or equal to 18.

95 Working with association II.
When the multiplicity of an association is greater than 1, OCL provides a wide range of collection operations: basic operations loop operations. These operations are accessible in the following way: collection->operation()

96 Standard collection operators
count( object ) -The number of occurrences of the object in the collection excludes( object ) -True if the object is not an element of the collection excludesAll( collection) -True if all elements of the parameter collection are not present in the current collection includes( object ) - True if the object is an element of the collection includesAll( collection) - True if all elements of the parameter collection are present in the current collection isEmpty() - True if the collection contains no elements notEmpty() - True if the collection contains one or more elements size() - The number of elements in the collection sum() - The addition of all elements in the collection. The elements must be of a type supporting addition (such as Real or Integer).

97 context Customer inv minServices: self.cards->size() > 1 implies self.programs->size() > 1 Only a customer associated to some programs could have some cards – every customer with at least one card is associated to some program

98 Loop operations collect(expr)…collection of objects that result from evaluating expr for each element in the source collection exists(expr)…true if there is at least one element in the source collection for which expr is true forAll( expr )…true if expr is true for all elements in the source collection isUnique( expr )…true if expr has a unique value for all elements in the source collection one( expr) … true if there is exactly one element in the source collection for which expr is true select(expr)…subcollection of the source collection containing all elements for which expr is true

99 context Customer inv sizesAgree: programs->size() = cards->select( valid = true )->size() The number of valid cards for every customer must be equal to the number of programs in which the customer participates.

100 Iterator Variables Every iterator operation may have an extra (optional) parameter, an iterator variable. An iterator variable is a variable that is used within the body parameter to indicate the element of the collection for which the body parameter is being calculated. context Customer inv: Customer::allInstances()->isUnique( ) or context Customer inv: Customer::allInstances()->isUnique(c | c. ) context Customer inv: Customer::allInstances()->isUnique(c:Customer | c. )

101 Types of collections OCL defines types of collection:
Set - a collection that contains instances of a valid OCL type and does not contain duplicate elements OrderedSet – Set with ordering of elements Bag - a collection that may contain duplicate elements Sequence - Bag whose elements are ordered Specific operation for collection are provided append(object),prepend(object) … add on the end resp. start asBag(), asOrderedSet(), asSequence(), asSet() … casting at(index), first(), last() … gets given item including(object), excluding(object) … add resp. remove item flatten … change a collection of a collection to a single collection

102 context ProgramPartner
inv nrOfParticipants: self.numberOfCustomers = self.programs.participants->flatten()->asSet()->size() Attribute numberOfCustomers holds the number of customers who participate in one or more loyalty programs offered by this program partner

103 Preconditions and Postconditions
Preconditions and postconditions are constraints that specify the applicability and effect of an operation without stating an algorithm or implementation. context Product::discount(percentage: Integer) : Real pre: percentage >= 0 and percentage <= 10 post: let oldPrice : Real = in self.price = oldPrice – (oldPrice*percentage/100) and result = self.price

104 context CustomerCard::block():boolean
post: self.valid =false and result = Consider method CustomerCard::block – value of valid is set to false and old value of the attribute is returned.

105 Information addition Definition of already declared elements in a class diagram: Query function context Product::possibleDiscount(percentage: Integer) : Real body: self.price – (self.price*percentage/100) Derived attributes context Project::duration: Integer derive: self.end.diference(self.start) Definition of new elements – query function and derived attributes context Department def completeBudget : Real = self.project.budget->sum();

106 context CustomerCard::printedName:String
derive: self.owner.title.concat(' ').concat(self.owner.name) Derived attribute printedName of CustomerCard is determined based on the name and title of the card owner.

107 context Service def: turnover : Real = self.transactions.amount->sum() Let‘s introduce a derived attribute called turnover in class Service which would sum the amount attributes of the transactions on the account.

108 Initial values Attributes context CustomerCard::valid : Boolean
init: true Association role context Customer::products : Set( Products) init: Set{}

109 context CustomerCard::valid: Boolean
init: self.owner.cards->exists(c| c != self and c.valid) A new CustomerCard is valid if and only if owner has already at least another one card.

110 Roots of UML Standardized by OMG
OOSE Object-oriented Software Engineering I. Jacobson Booch Method ... G. Booch OMT Object Modeling Technique J. Rumbaugh UML Unified Modeling Language Rational Roots of UML 1980 – OOP began to move forward the “real” word 1988 – 1992 – key books about OO graphical modeling language appeared, methods were similar containing a number of often annoying minor differences Standardization was ignored – OMG obtained only an open letter of protest from all the key methodologists. Jim Rumbaugh left GE to join Grady Booch at Rational. first public description of their merged method: version 0.8 Rational bougth Objectory (Ivar Jacobson) OMG took active role – demand of tool vendors because they afraid of dominant status of Rational. 1997 – version 1.0 was released by OMG Standardized by OMG

111 UML using Three modes: Two directions: as a sketch as a Blueprint
as a programing language. Two directions: forward engineering reverse engineering There are different ways in which people want to use it. These differences have its opponents and supporters. There are three modes of UML using: sketch, blueprint, and programming language. UML as a sketch is probably the most common one. Developers use the UML to help communicate some aspects of a system in this case. Forward engineering draws a UML diagram before you write code, while reverse engineering builds a UML diagram from existing code. Tools that can do both are called round-trip tools.

112 UML as a sketch most common its essence is selectivity
forward sketching – to discuss some issue in code, to help to communicate reverse sketching – to explain working of some parts of a system Forward sketching rough some issues in software, usually discussing them with a group of people on your team aim is to help communicate ideas and alternatives; don’t talk about all code – only important issues; Sessions: 10-minutes discuss sessions - a few hours of programming. a day discuss session – a 2-week iteration. Reverse engineering Sketches explain how some part of a system works. It doesn't show every class, simply those that are interesting and worth talking. Because sketching is pretty informal and dynamic, you need to do it quickly and collaboratively, so a common medium is a whiteboard. Sketches are also useful in documents, in which case the focus is communication rather than completeness. The tools used for sketching are lightweight drawing tools.

113 UML as a blueprint its essence is completeness
forward sketching – detailed design sufficiently complete for coding up reverse sketching – shows every detail about the selected part of a system Forward engineering It represents a detailed design for a programmer to code up. A design should be sufficiently complete: all design decisions are laid out a programmer should be able to follow it with little thought A designer may be the same person as the programmer, but usually the designer is a more senior developer who designs for a team of programmers. This approach inspired in other forms of engineering. It is used for all details, or a designer may draw blueprints to a particular area - develop blueprints of interfaces of subsystems but then let developers work out the details of implementing those details. Reverse engineering It provides detailed information about the code either in paper documents or as an interactive graphical browser. The blueprints can show every detail about a class in a graphical form that's easier for developers to understand.

114 UML as a blueprint II. requires more sophisticated tools than sketches
reasonable for interfaces Value of reverse-engineering depends on tools Dynamics browser is valuable Generating large documents is worthless Successful using of blueprints stands on much more sophisticated tools than sketches. E.g., Blueprinting of interfaces is reasonable, but even then you should expect to change those interfaces as developers implement the interactions across the interface. The value of reverse-engineered blueprints depends on how the tool works. If it's used as a dynamic browser, it can be very helpful; if it generates a large document, then it doesn’t generate additional value.

115 UML as a programming language I
another level of code generation requires sophisticated tools environment should provide better productivity requires a mass of users A developer could generate the code in many CASE tools. However, a quality and way differs from tool to tool, but it automates building a significant part of a system. The most extreme attitude is that all the system can be specified in the UML, and you reach UML as programming language. In this environment, developers draw UML diagrams that are compiled directly to executable code, and the UML becomes the source code. Obviously, this usage of UML requires particularly sophisticated tooling.

116 UML as a programming language II
another level of code generation requires sophisticated tools environment should provide better productivity requires a mass of users The approach is worth if it is more productive than using another programming language, but various existing graphical development environments probably are not. Even if it they were more productive, it would still need to get a critical mass of users for it to make the mainstream. E.g., Smalltalk is considered to be much more productive than current mainstream languages. But as Smalltalk is now only a niche language, there are not many projects using it. To avoid Smalltalk's fate, the UML has to be luckier, even if it is superior.

117 UML diagrams Activity - Procedural and parallel behavior - In UML 1
Class - Class, features, and relationships - In UML 1 Communication - Interaction between objects; emphasis on links -UML 1 collaboration diagram Component - Structure and connections of components - In UML 1 Composite structure - Runtime decomposition of a class - New to UML 2 Deployment - Deployment of artifacts to nodes - In UML 1 Interaction overview - Mix of sequence and activity diagram - New to UML 2 Object - Example configurations of instances - Unofficially in UML 1 Package - Compile-time hierarchic structure - Unofficially in UML 1 Sequence - Interaction between objects; emphasis on sequence - In UML 1 State machine - How events change an object over its life - In UML 1 Timing - Interaction between objects; emphasis on timing - New to UML 2 Use case - How users interact with the system - In UML 1 UML2 UML2

118 UML meaning Precise definition of language
Not a formal definition of mapping into the source code Development teams follow their local convention UML Is Not Enough Although the specification describes in great detail what well-formed UML is, it doesn't have much to say about what the UML means outside of the rarefied world of the UML meta-model. No formal definition for UML mapping to any particular programming language - you cannot look at a UML diagram and say exactly what the equivalent code would look like. You can get a rough idea of what the code would look like - that's enough to be useful. Development teams often form their local conventions for these, and you'll need to be familiar with the ones in use. Different diagrams can be useful, and you shouldn't hesitate to use a non-UML diagram if no UML diagram suits your purpose.

119 UML in a software process – software requirements I
use cases - how people interact with the system. class diagram - conceptual perspective, vocabulary of the domain. an activity diagram - work flow of the organization (how software and human activities interact), can show the context for use cases and also the details of how a complicated use case works. a state diagram – an interesting life cycle of concepts A number of UML diagrams can be used: use cases, which describe how the outer world interact with the developed system a class diagram drawn from the conceptual perspective, which can be a good way of building up a rigorous vocabulary of the domain.

120 UML in a software process – software requirements II
use cases - how people interact with the system. a class diagram - conceptual perspective, vocabulary of the domain. an activity diagram - work flow of the organization (how software and human activities interact), can show the context for use cases and also the details of how a complicated use case works. a state diagram – an interesting life cycle of concepts an activity diagram for business modeling that is used to show how software and human activities interact. It can also show the context for use cases as well as the details of how a complicated use case works. A state diagram to show interesting life cycles, with various states and events.

121 UML in a software process – design I
Class diagrams - classes in software and how they interrelate. Sequence diagrams - to figure out what happens in the software for most important and interesting scenarios. Package diagrams - the large-scale organization of the software. State diagrams - for classes with complex life histories. Deployment diagrams - physical layout of the software. Design becomes more technical using UML diagrams. Various notation with a different level of detail could be used. Some useful techniques are: Class diagrams describing software components and their relation. Sequence diagrams for common scenarios that are the most important and interesting scenarios from the use cases. It shows what happens in the software.

122 UML in a software process – design II
Class diagrams - classes in the software and how they interrelate. Sequence diagrams - to figure out what happens in the software for most important and interesting scenarios. Package diagrams - large-scale organization of software. State diagrams - for classes with complex life histories. Deployment diagrams - physical layout of software. Package diagrams – show large-scale organization of the software. State diagrams for classes with complex life histories. Deployment diagrams to show the physical layout of the software. Many of these same techniques can be used to document already finished software. It improves understanding for developers which are not familiar with the code.

123 UML in a software process – maintenance
Documentation only for highlighting most important parts understanding Legacy Code During documenting of a finished system, we may be careful to not produce a lot of detailed diagrams. Detailed documentation should be generated from the code by a tool, such as JavaDoc. Use diagrams as sketches that highlight the most important parts of the system – it requires an additional value of UML using. E.g. Sketches of key classes in a package and their relations and interactions can help clarify what's going on. With modern tools, you can generate detailed diagrams for key parts of a system. Don't use these tools to generate big paper reports; instead, use them to drill into key areas as you are exploring the code itself. A particularly nice capability is that of generating a sequence diagram to see how multiple objects collaborate in handling a complex method.

124 Where to Start with UML UML is very complex
Class and sequence diagrams are the most useful Experiment with diagrams – don’t hesitate to leave out a technique useless for you A complete UML specification is complex. It is necessary to find the subset of the UML that works for you and your team. Concentrate first on the basic forms of class diagrams and sequence diagrams on the beginning. With increasing experience, you can use more advance class diagram notation and take a look at the other diagram types. Experiment with them and if they are useless to you, drop them.

125 Class diagrams majority of UML diagrams
types(classes) of object and various kind of static relations among them constraints feature – operation and properties Class diagram is the most common from UML. It describes the types of objects in the system and various kinds of static relationships that exist among them. It also shows class properties and operations. The term feature is used for properties and operations of a class. Picture: boxes – classes three compartments: its name(in bold) its attributes its operations two kinds of relationships: associations generalizations

126 Class diagrams – properties I
structural features of a class attributes: visibility name: type multiplicity = default {property-string} Example: -name: String [1] = "Joe Daw" {readOnly} association show many similar information to attributes: Property represents structural features of a class – it can be simply viewed as a field in a class. The attribute notation refers to a line of text within the class box itself.

127 Class diagrams – properties II
structural features of a class attributes: association shows much similar information to attributes: Much of the same information that you can show on an attribute appears on an association. An association is a solid line between two classes, directed from the source class to the target class. The name of the property is at the target end of the association, together with its multiplicity. The target end of the association is the class - the type of the property. Attributes are preferred for value types and associations are preferred for reference types.

128 Associations - multiplicity
indicates how many objects may be in the property The most common: 1 0..1 * Properties of association end: {ordered} – {unordered} (default) {nonunique} – {unique} (default) Multiplicity of property indicates how many objects may be in the property. The most common used multiplicities are: 1 0..1 * It could be referred by terms: Optional – lower bounds is 0 Mandatory – lower bounds is 1 (or more) Single-valued – upper bound is 1 Multivalued – upper bound is more than 1 Elements in a multivalued multiplicity form a set. If ordering values in association has a meaning, add {ordered} to the association end. If you want to allow duplicities of values in association, add {nonunique}.

129 Bidirectional Associations
a pair of properties that are linked together as inverse. label association by using a verb phrase. The Car class has property owner:Person[1], and the Person class has property cars:Car[*]. The inverse link implies that if you start on one association end, you should get back to the set that contains your starting point. A label of association by using a verb phrase is alternative – especially for developers with data-modeling background. One of these schemes is recommended but not both. Using a property name is preferred – it corresponds better to responsibilities and operations.

130 Class diagrams - operations
the actions that a class knows to carry out visibility name (parameter-list) : return-type {property-string} parameters - similar way to attributes: direction name: type = default value Operations are the actions that correspond to messages known by the class. They most obviously correspond to the methods on the class. Normally, you don't show those operations that simply manipulate properties, because they can usually be inferred. Description of syntax defined in the picture: visibility – is a marker: public (+) for operations visible anywhere or private (-) for operations visible only in a class where is defined name – is a string and defines the name that is used for operation reference parameter-list – attributes for the operation. return-type - a type of the returned value, if there is one. The property-string - property values for given operation. The parameters in the parameter list: name, type, and default value same as for attributes. direction - indicates whether the parameter is input (in), output (out) or both (inout). (default direction is in). Example: + balanceOn (inout date: Date) : Money

131 Generalization Obvious inheritance substatiability Subtyping
subclassing An important principle of using inheritance effectively is substitutability - it is possible to substitute a Successor within any code that requires a predecessor. Many other mechanisms can be used to provide substitutable classes: A class is a subtype if it is substitutable for its supertype, whether it uses inheritance or not. Subclassing is used as a synonym for regular inheritance.

132 Notes and Comments can appear in any kind of diagram
They are comments in the diagrams. Notes can be alone in a diagram, or they can be linked to the commented element by a dashed line. They can be used in any kind of diagram. They could be used for a constraints description.

133 Dependency Change of one elements may cause definition of another elements Basically, it is not transitive. Minimalize dependencies – lower coupling Be selective with showing

134 Dependency II Minimalize dependencies – lower coupling
Be selective with showing <<call>> The source calls an operation in the target. <<create>> The source creates instances of the target. <<derive>> The source is derived from the target. <<instantiate>> The source is an instance of the target. <<permit>> The target allows the source to access the target's private features. <<realize>> The source is an implementation of a specification or interface defined by the target <<refine>> Refinement indicates a relationship between different semantic levels <<substitute>> The source is substitutable for the target <<trace>> Used to track <<use>> The source requires the target for its implementation.

135 Constraint rules Class diagram cannot indicate every constraint
Name of constraint – {disallow incest: husband and wife not be siblings}

136 Class diagrams – usage I
Don’t use all available notations. Useful conceptual class diagram – keep the notation simple Better to have a few diagrams up to date then many obsolete Using with some form of behavioral technique Class diagrams are so rich and they can be overwhelming to use. Few tips: Don't try to use all the notations available to you. Start with a simple notation: classes, associations, attributes, generalization, and constraints. Introduce other notations only when you need them. Conceptual class diagrams are very useful in exploring the language of business – use only simple notation.

137 Class diagrams – usage II
Don’t use all available notation. Useful conceptual class diagram – keep notation simple Better to have a few diagrams up to date than many obsolete Use with some form of behavioral technique Don't model everything with class diagram but concentrate on the key areas. It is better to have a few diagrams that you use and keep up to date than to have many forgotten, obsolete models. Always use class diagram in conjunction with some form of behavioral technique – the biggest mistake is that the model captures the structure but misses the behavior.

138 Sequence diagrams The most common interaction diagram in UML
Single scenario – objects, messages They describe how groups of objects collaborate in some behavior. There are defined several forms of interaction diagram in the UML and the sequence diagram is the most common. Typically, a sequence diagram captures the behavior of a single scenario. The diagram shows a number of sample objects and the messages that are sent between these objects within the specific use case. Elements: Participants. Messages. Returns – describes point of return from method call. Lifeline – runs vertically down the page and defines existence of an object Activation – shows when the object is activated with received message (operation call); it allows a multiple level – message is passed to the object in the scope of handling of another message. Found message – the first message comes from and an undetermined source; useful because doesn’t need definition of actors

139 Sequence diagrams : Creating and deleting participants
Explicit deletion in gc environment is also available – it indicates that it is no longer needed A message arrow is drawn directly into the participant box. A message name is optional, but it is usually marked with "new". An activation element is started directly after the participant box whenever an object does something immediately after its creation. Deletion of a participant is described by big X. A message passed from another participant into the X means that another participant explicitly deletes the descried one; an X without an incoming arrow defines that a participant deletes himself.

140 Sequence diagrams: Loops, Conditionals
Possible use of another diagram Interaction frames are available in a sequence diagram procedure dispatch foreach (lineitem) if (product.value > $10K) careful.dispatch else regular.dispatch end if end for if (needsConfirmation) messenger.confirm end procedure A typical question of a modeler is whether it is possible to show loops and alternative scenarios. The answer is positive, but a sequence diagram is not optimal – different diagrams are more suitable. Interaction frames are used for conditional flows, for loops and for others. They contain: operator – it defines semantic. condition (mandatory) – contained in fragment and it contains condition where to iterate.

141 Common operators for interaction frames
Meaning alt Alternative multiple fragments; opt Optional; the fragment executes only if the supplied condition is true par Parallel; each fragment is run in parallel. loop Loop; the fragment may execute multiple times region Critical region; the fragment can have only one thread executing it at once. neg Negative; the fragment shows an invalid interaction. ref Reference; refers to an interaction defined on another diagram. sd Sequence diagram; used to surround an entire sequence diagram

142 Sequence diagrams: Synchronous and Asynchronous Calls
Synchronous message Asynchronous message Sending a synchronous message indicates waiting of the caller for a response. The caller doesn’t need to wait if he sends an asynchronous message. Asynchronous calls are used in multithreaded applications and in message-oriented middleware. Asynchronicity gives better ability to a response but it is harder to debug.

143 When to Use Sequence Diagrams
overview of behavior of several objects in a single use case good at showing collaborations but bad at precise definition of the behavior behavior of a single object across many use cases – state diagram behavior across many use cases or many threads – activity diagram other interactions diagrams: communication diagram – showing connections timing diagrams – showing timing constraints

144 Classification and Generalization
Consider: Shep is a Border Collie. A Border Collie is a Dog. Dogs are Animals. A Border Collie is a Breed. Dog is a Species. It deduces: 1 and 2 - "Shep is a Dog“ 2 and 3 - "Border Collies are Animals." 1 plus 2 plus 3 - "Shep is an Animal." 1 and 4: "Shep is a Breed." - bad 2 and 5 is "A Border Collie is a Species." - bad Some are classification and some generalization. There exists dependency «instantiate» for classification showing in the UML. Using is a can leads to inappropriate use of subclassing. Better phrases: "Dogs are kinds of Animals" "Every instance of a Border Collie is an instance of a Dog."

145 Class Diagrams - Advanced Concepts: Multiple and Dynamic Classification
single classification – instance of a single type (may be inherited). multiple classification – described by several types (not necessarily connected by inheritance). Static classification – object is unable to change class Dynamic classification – object is able to change class Mainstream programming languages allows that an object belongs only to a single class. Note: (Female, Patient, Nurse); (Male, Physiotherapist); (Female, Patient); and (Female, Doctor, Surgeon) – legal – but (Patient, Doctor, Nurse) – illegal because it contains two types from the role generalization set. An object has to be an instance of one class bellow one discriminator. Dynamic classification is useful for conceptual modeling but from the software perspective, the distance between this and implementation is too much of a leap.

146 Class Diagrams - Advanced Concepts: Association Class
It allows you to add: attributes, operations, and other features to associations The association class adds an extra constraint, in that there can be only one instance of the association class between any two participating objects.

147 Class Diagrams - Advanced Concepts: Template (Parameterized) Class
class Set <T> { void insert (T newElement); void remove (T anElement); T is a placeholder for the type parameter Use of a parameterized class is called derivation: It reflects the ability of languages, such as C++, to describe a parameterized class, or a template. It is not the same as subtyping - to add features to the bound element, you must create a subtype.

148 Class Diagrams - Advanced Concepts: Enumerations
Shows a fixed set of values having only their symbolic values, <<enumeration>> keyword Enumeration represents the domain type with a fixed set of available values. Many programming languages support it directly or it is represented with constants of suitable primitive type (integer, string, char). It is represented as class symbol with <<enumeration>> keyword. Available values are in attribute compartment (without type and access modification). Enumeration could be used as a type of attribute, parameter of method or method result value.

149 Class Diagrams - Advanced Concepts: Active class
It has instance executing its own thread of control It is a class with instances, which executes on separate thread. The elements could be used in architecture design – it is useful in the process view stage.

150 Class Diagrams - Advanced Concepts: Visibility
You can tag every feature with: + … public - … private # … protected ~ …package their meaning dependents base on a used programming language However, many languages use such terms as public, private, and protected, they mean different things in different languages. It is important to be careful and respect the target language.

151 Class Diagrams - Advanced Concepts: Responsibilities
Defined responsibilities are useful because it increases their cohesion and their showing in a UML diagram could be a perfect way. We define it as a comment as comment strings in its own compartment in the class.

152 Class Diagrams - Advanced Concepts: Static Operations and Attributes
The UML names an operation or an attribute that is related to a class as class features. This is equivalent to static features in C++-based languages. Class features are underlined in a class diagram.

153 Class Diagrams - Advanced Concepts: Aggregation and Composition
Aggregation – contains relationship - "Think of it as a modeling placebo" [Rumbaugh, UML Reference] Composition – part-of relationship, class could be a component of other classes but its instance could be a component of only one owner. It is often confused and the main difference is: Aggregation is a part of relationship and it has no semantic difference with association and its using depends on the modeler using, whilst a composition is defined precisely. It defines that some parts (components) form a class (composite). It haa to follow constraints that any instance could be a component of only one composite. On the other hand, it is possible for a class to be a component of more classes.

154 Class Diagrams - Advanced Concepts: Derived properties
Calculated attribute form value of others has different interpretation: indicates the difference between the calculated value and the stored values indicates the constraint between the values Their value is computed during runtime – e.g. date range contains: start date, end date, and length. These values are linked and the length could be derived from values start and end. Derivation can be interpreted in different ways: To indicate the difference between the calculated value and stored values – start and end are stored but the length is computed. To indicate the constraint between values – constraint among three values holds, no matter which. It reminds the constraint and it could be used with conceptual diagrams.

155 Class Diagrams - Advanced Concepts: Abstract Classes
Cannot be instantiated – has to be sub-classed Typically has one or more abstract methods Abstract class and operation – name is italicized or label {abstract}. This class cannot be instantiated. It could be sub-classed and their successors could be instantiated. An abstract class often contains one or more operations that are abstract – they do not have any implementation. An abstract method or class is indicated by its name in italic style. Abstract properties indicate abstract accessor or mutator methods. Instead of italic style, you can mark elements with {abstract}.

156 Class Diagrams - Advanced Concepts: Interfaces
Class without any implementation – directly corresponds to JAVA, C# Label «interface» Two kinds of relation with classes: Implements Requires It strictly corresponds to the concept of an interface in C# and Java. You mark an interface with the keyword «interface». There exist two kinds of relationships with interfaces in the UML: providing and requiring. A class provides an interface if it is substitutable for the interface. A class requires an interface if it needs an instance of that interface in order to work and it has dependency on it.

157 Class Diagrams - Advanced Concepts: Benefits of interface using
It allows to simply change the implementation later - another implementation may provide better performance Use the most general type you can: //without need of ordered container private Collection lineItems = new ArrayList(); //otherwise private List lineItems = new ArrayList(); It increases the level of encapsulation with programming to the interface rather than to the implementation. The presented code creates dependency on ArrayList – during initialization - but the dependency is only on one line and could be simply changed.

158 Class Diagrams - Advanced Concepts: Interface ball-and-socket notation
Lollipop notation was in the previous UMLversion Socket syntax – alternative syntax for dependency description; addition in UML 2.0 You could probably see both version.

159 Class Diagrams - Advanced Concepts: Reference Objects and Value Objects
Reference objects – Customer – identity is important; comparison based on identity Value Objects – Date – multiple objects representing the same object in the real world; comparison is not based on identities Use composition or attribute when associating with a value object; common convention to use stereotype «value» or «struct» One of the common things said about objects is that they have identity – sometimes, it is not so important. For Reference objects identity is very important because you usually want only one software object to designate a customer in the real world. If you have two references to a Customer and wish to see whether they are the same, you usually compare their identities. Value objects have multiple value objects representing the same object in the real world. For example, it is normal to have hundreds of objects that designate same date. These are all interchangeable copies. If you have two dates and wish to see whether they are the same, you don't look at their identities but rather at the values they represent.

160 Class Diagrams - Advanced Concepts: Qualified Associations
Equivalent to associative array, maps, hashes, and dictionaries Be careful - multiplicity at least one indicates that for given “Product” exists at least one ”Order Line” associated with specific Order but more Order Lines could be associated with one “Order” (but for different products). A multiplicity greater than one is also permitted.

161 Object diagrams a snapshot of a system at a specific time
elements are underlined useful for showing examples of objects connected together It is a snapshot of the objects in a system at a point in time. It shows instances. Strictly, the elements of an object diagram are instance specifications rather than true instances. It is sometimes necessary tuse it because a precisely defined a structure with a class diagram is not enough.

162 Package Diagrams package – grouping construct that allows to group any construct into high-level units namespaces – every class has to have a unique name with a package Useful on large-scale systems – dependencies between major elements of the system; represent a compile-time grouping mechanism. Architecture overview It allows to group elements together into higher-level units – classes are grouped mostly, but it allows to group any other elements.

163 Packages and Dependencies I
Summarize dependencies of their content Be careful with cyclic dependency – avoid cross layers with cycles More dependencies coming into a package – mare stable interface should be. Dependency is not transitive Stereotype «global» is used for package accessed from many places – it avoids a lot of dependency lines It depicts packages and their dependencies. You have dependency between two packages if any class in the first package has a dependency to any class in the second package.

164 Packages and Dependencies II
Summarize dependencies of their content Be careful with cyclic dependency – avoid cross layers with cycles More dependencies coming into a package – should be a more stable interface. Dependency is not transitive Stereotype «global» is used for a package accessed from many places – it avoids a lot of dependency lines  Ideally, this diagram should be generated from the code base itself, so that you can see what really there is in the system. It is necessary to select what dependency to describe – UML allows more types.

165 Implementing Packages
One package contains a class implementing interface from another package. An interface and its implementation are often in separate packages.

166 Deployment Diagrams Shows system’s physical layout
Shows communication paths and connected nodes Useful in showing what is deployed where. A node is something that can host some software. Two forms: Device – hardware that is computer or simpler piece of hardware connected to a system Execution environment – software that hosts or contains other software –e.g. an operating system or a container process Nodes contain artifacts – physical manifestation of software – usually files – executables, data files, configuration files, HMTL documents. They are often implementation of components.

167 Use Case diagrams It is not mandatory – instead, diagrams concentrate on the textual content Graphical table of use cases The best way to think of a use case diagram is that it's a graphical table of contents for the use case set. It's also similar to the context diagram used in structured methods, as it shows the system boundary and the interactions with the outside world. The use case diagram shows the actors, the use cases, and the relationships between them: Which actors carry out which use cases Which use cases include/extend other use cases

168 State Machine Diagram Based on a finite automaton
Lifetime behavior of a single object Shows only what the object directly observes or activates The picture depicts a controller for a secret panel in a Gothic castle. Initial pseudo-state is not state, it is an arrow to initial state in a finite automaton. A transition indicates a movement from one state to another. It defines rules by which the controller changes from state to state. It has signature trigger-signature [guard]/activity and all are optional. Trigger signature defines a single event that triggers a change of state – it could contain multiple events. Guard is a Boolean condition that must be true for the transition to be taken. An activity is some behavior that's executed during the transition. Missing trigger-signature indicates that you take the transition immediately. The final state indicates that the state machine is completed.

169 State Machine Diagrams – Internal activities
States can react to events without transition – internal activities – event, guards and activity inside state box Two special activities (not internal): entry activity – executed whenever a state is entered; exit activity – executed whenever a state is exited It is like self-transition: a transition that loops back to the same state. Its syntax is the same as for common transitions. Two special activities: entry activity is executed whenever you enter a state; the exit activity, whenever you leave. Internal activities do not trigger the entry and exit activities but self-transitions do.

170 State Machine Diagrams – Activity states
States when objects do something Marked with do/ Can be interrupted Sometimes, an object is quiet and waiting for the next event before it does something. However, you can have states in which the object is doing some ongoing work. The activity is named as do-activity. Once it is completed, any transitions without an activity are taken. If the cancel event occurs during the activity, the do-activity is immediately halted – in contrast with regular activities.

171 State Machine Diagrams – Superstates
Often several states share common transitions and internal activities – shared behavior into a superstate If several states share common transitions and internal activities then sub-states are used. The shared behavior is moved into a super-state. Without using the super-state, you would have to draw a cancel transition for three states in this example.

172 State Machine Diagrams – Concurrent states
States can be broken down into several orthogonal state diagrams that run concurrently History pseudostate restores the last state The choices CD/radio and current/alarm time are orthogonal choices that are visited independently. It would be messy diagram without using concurrent states. History pseudo-state indicates that sub-state is started in the same state which it was leaving before. The arrow from the history pseudo-state indicates where to start if no history is available (in the first time).

173 State Machine Diagrams – when to use I
Good for describing a single object across several use cases Not good at describing behavior that involves a number of objects collaborating

174 State Machine Diagrams – when to use II
Useful to combine with other techniques – e.g. with interaction diagrams Draw only for classes that exhibit interesting behavior – e.g. GUI or control objects It is useful to combine them with others techniques– sequence diagrams, activity diagrams. They are used only for those classes that have interesting lifecycle. It is often used to describe the control or UI object lifecycle.

175 Activity diagrams - I describe procedural logic, business process, work flow of actions – similar role as flowcharts have parallelism (fork) in comparison with flowcharts have synchronization (join) define order for execution There is a simple example of an activity diagram. We begin at the initial node action and then do the action Receive Order. Once that is done, we encounter a fork. The fork has one incoming flow and several outgoing concurrent flows. When you have parallelism, you'll need to synchronize – join activity.

176 Activity diagrams – II Decision – single incoming/several ongoing flows Each flow is a guarder – Boolean expression (use [else] for guard used when other guards are false) Merge - multiple input/one output Conditional behavior is defined by decision and merges mark.

177 Activity diagrams – decomposing an action
Action can be decomposed into sub-activities Can be implemented either as a sub-activity or as a method on class (syntax classname::method-name) Actions can be implemented either as sub-activities or as methods on classes. A sub-activity is marked with the rake symbol. Calling on a method with syntax (classname::method-name) could be used. A code fragment could be written into the action symbol – e.g. if the invoked behavior isn't a single method call.

178 Activity diagrams - when to use
Work flow and process modeling Representation of behavioral logic Description of use case They support and encourage parallel behavior so they are a great tool for work flow and process modeling. They are suitable for represention of behavioral logic. It is possible to use activity diagrams to describe a use case. However, domain experts often don't understand them easily – it is better to use a text form.

179 Activity diagrams – partitions
They are useful for description of different responsibilities for activity handling. In UML 1.x, it was referred as swim lines but in UML 2.x, you can use a two-dimensional grid. You can also take each dimension and divide the rows or columns hierarchically.

180 Activity diagrams – signals
Actions can also respond to signals. It helps to define that actions respond to signals. The figure shows an activity that listens to two signals: A common signal – activity waits for receiving of an event from an outside process and its reaction Time signal – defined time condition that starts another activity reaction.

181 Activity diagrams – sending and receiving signals
Sending a signal is also supported – communication with external process It is opposite concept for signal sending.

182 Activity diagrams – tokens
Initial note creates a token. The token passes to the next action. A fork produces more tokens – one for each branch; a join consumes tokens. It has been very close to concept of Petri Nets since version UML 2.0.

183 Activity diagrams – flows and edges
Flow and edge – connections between two actions Connectors – use it in the case of a messy diagram; using in a pair Control flow – the simplest without another meaning Object node – passing an object along edges; objects play role of tokens and carry data Pin on the actions – alternative to object node Four syntaxes are available: the simplest – passed token is only a control token used if there is difficulty with routing of edges, it has to be used in pair token represents object passed along edge in addition of its control function. using of pins is equivalent to the previous type in this case

184 Activity diagrams – pins and transformations
Actions can have parameters – as methods do You can show it with pins In decomposed diagrams, pins correspond to the parameter boxes Output parameter of an outbound action should match the input parameters of another. A transformation is indicated in case they don’t match If parameters don’t match, you can describe transformation that transforms from one to another. It has no side effects.

185 Activity diagrams – expansions regions
Expansion region – it marks an invocation for each item in the collection Parallel area is marked by keyword «concurrent» - iterative regions process each input element one at a time Multiple invocation of a single activity – shorthand could be used; concurrent invocation is expected We often need to describe situations in which one action's output triggers multiple invocations of another action. The region is started for every item in collection and following action is started if every item is handled – only one output.

186 Activity diagrams – flow final
Flow final – the end of one particular flow; the whole activity is not terminated it allows expansion regions to act as filters – the output collection is smaller than the input collection It consumes only one token that has arrived into it – it doesn´t stop the full activity execution.

187 Activity diagrams – join specification
Join specification – another involved rule attached to a join It is a Boolean expression attached to a join and it is evaluated each time a token arrives and if true, an output token is emitted.

188 Communication diagrams
Represent a kind of an interaction diagram, Emphasize the data links between the participants Collaboration diagrams in UML 1.x Bad for control logic – only iteration markers and guards They emphasize the data links between various participants in the interaction. It allows free placement of participants and to draw links to show how the participants connect. It uses numbering to show the sequence of messages.

189 Communication diagrams - transient links
Links are instances of associations or transient links Arise only in the context of interaction: «local» - represents local variables «parameter» - represents parameters of method «global» - represents global value Missing in UML 2.x but are very useful They arise only the context of the interaction. These keywords were used in UML 1 but has been missing from UML 2. However, they are useful.

190 Communication diagrams - decimal numbering
Legal numbering style should be nested It resolves ambiguity with self-calls Many people prefer a flat numbering scheme – simpler The previous style of numbering is not legal in UML. It should be used nested decimal numbering scheme. This scheme avoids ambiguity with self-calls. Despite its illegality, many people prefer a flat numbering scheme. The nested numbers can get very tangled, particularly as calls get rather nested, leading to such sequence numbers, such as

191 Communication diagrams - when to use
Sequence diagrams are more common Personal preference Easier to draw on a white board – good for exploring alternatives Their usage is partially based on personal preference. More precisely it could be said that sequence diagrams are better when you want to emphasize the sequence of calls and that communication diagrams are better when you want to emphasize the links.

192 Composite structures Hierarchically decompose a class into an internal structure Allow to take a complex object and break it down into parts It is one of the most significant new features of UML 2. It allows to hierarchically decompose a class into an internal structure. We can take a complex object and break it down into parts. A class is decomposed internally into two parts in the picture. Every part supports and requires the different interfaces. The name of each part is in the form “name : class”. Both elements are optional.

193 Composite structures – interfaces
Delegating connectors – provided and required interfaces Connectors between parts – simple line or ball-and-socket notation Ports – allow to group the required and provided interfaces We draw a delegating connector from that interface – it shows which parts implement specific the interface. Delegating connectors are similarly used for the required interface.

194 Composite structures – when to use
Show runtime grouping (packages are compile time grouping) Similar to a component Composite structures are new to UML 2, although some older methods had some similar ideas. A Difference between composite structure and packages: packages are a compile-time grouping but composite structures show runtime groupings. Used for showing components and how they are broken into parts - much of this notation is used in component diagrams.

195 Component diagram Annotated class in UML 2.0 – no additional syntax
Not any additional notation that we haven't seen yet. Implemented and required interfaces are used for connection of components. There is often used the ball-and socket notation. Components could be decomposed using composite structure diagrams.

196 Component diagram – example
The component of a till is ideally connected directly to Sales Server using a message interface. In the case of an unreachable network, the till communicates with the message queue and the message queue communicates with the server when the network is reachable. The message queue component both required and provided the interface. The server is divided into two major components: the transaction processor realizes the sales message interface, and the accounting driver talks to the accounting system.

197 Component diagram – when to use
Beware of overly fine-grained components – hard to manage. Components and their interrelationship through interfaces. It is used to show how the system is divided into components and their relationship through interfaces. It also allows to breakdown of components into a lower-level structure. In the current version of UML, components are not used to represent physical structures, such as DLLs, executable etc. That's Artifacts are used instead.

198 Collaborations It is not an official diagram – a part of composite structures No typical class diagram – definition of roles. Interaction diagram - participant-name /role-name : class-name. Part of composite structure – it shows the structure of behavior. An auction contains a seller, some buyers, a lot and offers for sale. The dashed ellipse represents the auction collaboration. Symbols in the collaboration are not classes but roles that will be realized as the collaboration is applied—hence the fact that their names aren't capitalized.

199 Collaboration occurrence
Collaboration could be used – it is placed on a class diagram. The links from the collaboration to those classes indicate how the classes play the various roles defined in the collaboration. Collaboration occurrence notation could be used to show the use of patterns, but hardly any patterns author has done this. Erich Gamma developed a nice alternative notation. Elements of the diagram are labeled with either the pattern name or a combination of pattern:role.

200 Interaction Overview Diagrams
Activity and sequence diagram together The diagram shows producing and formatting an order summary report. A scenario has basic cases: the customer is external – information is obtained from XML; the customer is internal - it is obtained from a database. We illustrate the two alternatives with two small sequence diagrams.

201 Timing Diagrams Inspiration from electrical engineering
States as a line vs. states as an area They are another form of interaction diagram. They are focused on timing constraints. Diagrams show a simple scenario based on the pump and hotplate for a coffee pot. There exists a rule that says that at least 10 seconds must pass between the pump coming on and the hotplate coming on. When the water reservoir becomes empty, the pump switches off, and the hotplate cannot stay on for more than 15 minutes.

202 Design Patterns The design pattern concept can be viewed as an abstraction of imitating useful parts of other software products. The design pattern is a description of communicating objects and classes that are customized to solve a general design problem in a particular context. Christopher Alexander says, "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice". Even though Alexander was talking about patterns in buildings and towns, what he says is true about object-oriented design patterns.

203 General structure of design patterns
Pattern name Problem Solution Consequences The pattern name is a placeholder that is used to describe a design problem, its solutions, and consequences very briefly (in a word or two). The name of pattern is used in our design vocabulary. It lets us design at a higher level of abstraction – we use names of patterns in design and programmer creates the software according to defined patterns. The problem describes when to apply the pattern. It explains the problem and its context. It might describe specific design problems such as how to represent algorithms as objects. The solution describes the elements that make up the design, their relationships, responsibilities, and collaborations. The solution doesn't describe a particular concrete design or implementation - application in many different situations. The consequences are the results and trade-offs of applying the pattern – they include its impact on system's flexibility, extensibility, or portability

204 Structure of design patterns in software design
Pattern Name and Classification Intent Also Known As Motivation Applicability Structure Collaborations Consequences Implementation Sample Code Known Uses Related Patterns Pattern Name and Classification The pattern's name describes the main pattern principle. Intent - A brief statement that answers the following questions: What does the design pattern do? Also Known As – It defines equivalent names used for the pattern. Motivation - A scenario that illustrates a design problem and how the class and object structures in the pattern solve the problem. Applicability - What are the situations in which the design pattern can be applied? Participants - The classes and/or objects participating in the design pattern and their responsibilities. Collaborations - How the participants are collaborating to obtain their responsibilities. Consequences –

205 Structure of design patterns in software design II
Pattern Name and Classification Intent Also Known As Motivation Applicability Structure Collaborations Consequences Implementation Sample Code Known Uses Related Patterns Implementation - What pitfalls, hints, or techniques should you be aware of when implementing the pattern? Are there language-specific issues? Sample Code - Code fragments that illustrate how you might implement the pattern in a specific language. Known Uses - Examples of the pattern found in real systems. Related Patterns - What design patterns are closely related to this one?

206 Classification of Design Patterns
Creational patterns defer some part of object creation to a subclass or another object. Structural patterns compose classes or objects. Behavioral patterns describe algorithms or cooperation of objects. We use classification of legendary book “Design pattern: reusable design elements” from “Gang of Four”. It is generally noted as GoF. Four authors of the book are: Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides.

207 Creational Design Patterns
Factory Method defines an interface to create an object, but let subclasses decide which class to instantiate. Factory provides an interface to create families of related objects without specifying their concrete classes. Prototype specifies the kinds of objects to create using a prototypical instance, and to create new objects by copying this prototype. Builder separates the construction of a complex object from its representation so that the same construction process can create different representations. Singleton ensures that the class only has one instance and provides a global point of access to it.

208 Factory Method Example

209 Factory Method Design Pattern

210 Abstract Factory Example

211 Abstract Factory Design Pattern

212 Prototype Example

213 Prototype Design Pattern

214 Builder example Záměr:
Separate the construction of a complex object from its representation so that the same construction process can create different representations. Motivace: Použitelnost the algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled. the construction process must allow different representations for the object that's constructed

215 Builder design pattern
Struktura: Účastníci -Builder , ConcreteBuilder , Director, Product Kolaborace: Důsledky: It lets you vary a product's internal representation. The Builder object provides the director with an abstract interface for constructing the product. The interface lets the builder hide the representation and internal structure of the product. It also hides how the product gets assembled. Because the product is constructed through an abstract interface, all you have to do to change the product's internal representation is define a new kind of builder. It isolates code for construction and representation. The Builder pattern improves modularity by encapsulating the way a complex object is constructed and represented. Clients needn't know anything about the classes that define the product's internal structure; such classes don't appear in Builder's interface. Each ConcreteBuilder contains all the code to create and assemble a particular kind of product. The code is written once; then different Directors can reuse it to build Product variants from the same set of parts. In the earlier RTF example, we could define a reader for a format other than RTF, say, an SGMLReader, and use the same TextConverters to generate ASCIIText, TeXText, and TextWidget renditions of SGML documents. It gives you finer control over the construction process. Unlike creational patterns that construct products in one shot, the Builder pattern constructs the product step by step under the director's control. Only when the product is finished does the director retrieve it from the builder. Hence the Builder interface reflects the process of constructing the product more than other creational patterns. This gives you finer control over the construction process and consequently the internal structure of the resulting product. Implementace: Assembly and construction interface. Builders construct their products in step-by-step fashion. Therefore the Builder class interface must be general enough to allow the construction of products for all kinds of concrete builders. A key design issue concerns the model for the construction and assembly process. A model where the results of construction requests are simply appended to the product is usually sufficient. In the RTF example, the builder converts and appends the next token to the text it has converted so far. But sometimes you might need access to parts of the product constructed earlier. In the Maze example we present in the Sample Code, the MazeBuilder interface lets you add a door between existing rooms. Tree structures such as parse trees that are built bottom-up are another example. In that case, the builder would return child nodes to the director, which then would pass them back to the builder to build the parent nodes. Why no abstract class for products? In the common case, the products produced by the concrete builders differ so greatly in their representation that there is little to gain from giving different products a common parent class. In the RTF example, the ASCIIText and the TextWidget objects are unlikely to have a common interface, nor do they need one. Because the client usually configures the director with the proper concrete builder, the client is in a position to know which concrete subclass of Builder is in use and can handle its products accordingly. Empty methods as default in Builder. In C++, the build methods are intentionally not declared pure virtual member functions. They're defined as empty methods instead, letting clients override only the operations they're interested in.

216 Singleton design pattern
Záměr: Ensure a class only has one instance, and provide a global point of access to it. Motivace: Although there can be many printers in a system, there should be only one printer spooler. Použití: there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point. when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code. Struktura: Účastníci: Spolupráce: Důsledky: Controlled access to sole instance. Because the Singleton class encapsulates its sole instance, it can have strict control over how and when clients access it. Reduced name space. The Singleton pattern is an improvement over global variables. It avoids polluting the name space with global variables that store sole instances. Permits refinement of operations and representation. The Singleton class may be subclassed, and it's easy to configure an application with an instance of this extended class. You can configure the application with an instance of the class you need at run-time. Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance needs to change. More flexible than class operations. Another way to package a singleton's functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can't override them polymorphically. Implementace: Ensuring a unique instance – přes statickou metodu, která provádí inicializaci - Subclassing the Singleton class. – inicializace st. Proměnné nebo registr

217 Structural Design Patterns
Composite composes objects into tree structures to represent part-whole hierarchies. Composites let client treat individual objects and compositions of objects uniformly. Adapter converts the interface of a class into another interface clients expect. Adapters let classes work together that couldn’t otherwise because of incompatible interfaces. Decorator attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. Proxy provides a surrogate or representative for another object to control access to it. Façade provides a unified interface to a set of interfaces in a subsystem. Flyweight uses sharing support for large numbers of fine-grained objects efficiently.

218 Composite Example

219 Composite Design Pattern

220 Adapter Example

221 Adapter Design Pattern

222 Decorator Example

223 Decorator Design Pattern

224 Proxy Example

225 Proxy Design Pattern

226 Facade design pattern Záměr:
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. Použitelnost: you want to provide a simple interface to a complex subsystem. there are many dependencies between clients and the implementation classes of an abstraction you want to layer your subsystems. Struktura: Účastníci -Facade , subsystem classes Spolupráce: Důsledky: It shields clients from subsystem components, thereby reducing the number of objects that clients deal with and making the subsystem easier to use. It promotes weak coupling between the subsystem and its clients. Often the components in a subsystem are strongly coupled. Weak coupling lets you vary the components of the subsystem without affecting its clients. Facades help layer a system and the dependencies between objects. They can eliminate complex or circular dependencies. This can be an important consequence when the client and the subsystem are implemented independently. Reducing compilation dependencies is vital in large software systems. You want to save time by minimizing recompilation when subsystem classes change. Reducing compilation dependencies with facades can limit the recompilation needed for a small change in an important subsystem. A facade can also simplify porting systems to other platforms, because it's less likely that building one subsystem requires building all others. It doesn't prevent applications from using subsystem classes if they need to. Thus you can choose between ease of use and generality. Implementace: Reducing client-subsystem coupling. – možnost prověděd dědění fasády – alternativně lze toho dosáhnout někdy jinou konfigurací subsytému Public versus private subsystem classes.

227 Flyweight example Záměr:
Use sharing to support large numbers of fine-grained objects efficiently Motivace: Použitelnost: An application uses a large number of objects. Storage costs are high because of the sheer quantity of objects. Most object state can be made extrinsic. Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed. The application doesn't depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects.

228 Flyweight design pattern
Struktura: Účastníci: Flyweight, ConcreteFlyweight , UnsharedConcreteFlyweight, FlyweightFactory, Client Spolupráce: State that a flyweight needs to function must be characterized as either intrinsic or extrinsic. Intrinsic state is stored in the ConcreteFlyweight object; extrinsic state is stored or computed by Client objects. Clients pass this state to the flyweight when they invoke its operations. Clients should not instantiate ConcreteFlyweights directly. Clients must obtain ConcreteFlyweight objects exclusively from the FlyweightFactory object to ensure they are shared properly. Důsledky: Flyweights may introduce run-time costs associated with transferring, finding, and/or computing extrinsic state, especially if it was formerly stored as intrinsic state. Storage savings are a function of several factors: the reduction in the total number of instances that comes from sharing the amount of intrinsic state per object whether extrinsic state is computed or stored. Implementace: Consider the following issues when implementing the Flyweight pattern: Removing extrinsic state. The pattern's applicability is determined largely by how easy it is to identify extrinsic state and remove it from shared objects. Removing extrinsic state won't help reduce storage costs if there are as many different kinds of extrinsic state as there are objects before sharing. Ideally, extrinsic state can be computed from a separate object structure, one with far smaller storage requirements. Managing shared objects. Because objects are shared, clients shouldn't instantiate them directly. FlyweightFactory lets clients locate a particular flyweight. FlyweightFactory objects often use an associative store to let clients look up flyweights of interest. For example, the flyweight factory in the document editor example can keep a table of flyweights indexed by character codes. The manager returns the proper flyweight given its code, creating the flyweight if it does not already exist. Použití: JBOSS

229 Behavioral Design Patterns
Chain of Responsibility avoids coupling senders of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. Command encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. Iterator provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. Observer defines a one-to-many dependency between objects so that when one object changes its state, all its dependents are notified and updated automatically. State allows an object to alter its behavior when its internal state changes. The object will appear to change its class. Strategy defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets algorithm vary independently from clients that use it. Given a language, interpreter defines a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. Visitor represents an operation to be performed on the elements of an object structure. Without violating encapsulation, memento captures and externalizes object's internal state so that the object can be restored to this state later. Mediator defines an object that encapsulates how a set of objects interacts. Template method defines the skeleton of an algorithm in an operation, deferring some steps to subclasses.

230 Chain of Responsibility Example

231 Chain of Responsibility Design Pattern

232 Command Example

233 Command Desing Pattern

234 Iterator Example

235 Iterator Design Pattern

236 Observer Example

237 Observer Design Pattern

238 State Example

239 State Design Pattern

240 Strategy Example

241 Strategy Design Pattern

242 Interpreter example expression ::= literal | alternation | sequence | repetition | '(' expression ')' alternation ::= expression '|' expression sequence ::= expression '&' expression repetition ::= expression '*' literal ::= 'a' | 'b' | 'c' | ... { 'a' | 'b' | 'c' | ... }* Motivace:

243 Interpreter design pattern
Použitelnost: the grammar is simple. efficiency is not a critical concern. Struktura - AbstractExpression, TerminalExpression, NonterminalExpression , Context, Client Spolupráce: The client builds (or is given) the sentence as an abstract syntax tree of NonterminalExpression and TerminalExpression instances. Then the client initializes the context and invokes the Interpret operation. Each NonterminalExpression node defines Interpret in terms of Interpret on each subexpression. The Interpret operation of each TerminalExpression defines the base case in the recursion. The Interpret operations at each node use the context to store and access the state of the interpreter. Důsledky: It's easy to change and extend the grammar. Implementing the grammar is easy, too. – často generováno např sableCC Complex grammars are hard to maintain. Adding new ways to interpret expressions – např. Visitor Implementace: Creating the abstract syntax tree … není definováno jak … možno použít různé techniky Creating the abstract syntax tree … možnost oddělit interpretaci od pomocí Visitoru Sharing terminal symbols with the Flyweight pattern

244 Visitor example Záměr:
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. Motivace: Použitelnost: an object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes. many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations. the classes defining the object structure rarely change, but you often want to define new operations over the structure. Changing the object structure classes requires redefining the interface to all visitors, which is potentially costly.

245 Visitor design pattern
Struktura: Účastníci – Visitor, ConcreteVisitor , Element, ConcreteElement , ObjectStructure, Spolupráce: Důsledky: Visitor makes adding new operations easy. A visitor gathers related operations and separates unrelated ones. Adding new ConcreteElement classes is hard. Visiting across class hierarchies. Accumulating state. Breaking encapsulation. Realizace: Who is responsible for traversing the object structure – obj. struktura, Visitor nebo iterátor

246 Mediator example Intent
Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. Motivation As an example, consider the implementation of dialog boxes in a graphical user interface. Applicability a set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand. reusing an object is difficult because it refers to and communicates with many other objects. a behavior that's distributed between several classes should be customizable without a lot of subclassing.

247 Mediator design pattern
Structure Participants - Mediator, ConcreteMediator, Colleague classe Collaborations Consequences It limits subclassing – only mediator It decouples colleagues. It abstracts how objects cooperate. It centralizes control. Implementation Omitting the abstract Mediator class. Colleague-Mediator communication. – např. observer, ale může být i definováno přímo rozhranní pro komunikaci

248 Memento design pattern
Intent Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later. Motivation Sometimes it's necessary to record the internal state of an object. This is required when implementing checkpoints and undo mechanisms that let users back out of tentative operations or recover from errors. You must save state information somewhere so that you can restore objects to their previous states. Applicability a snapshot of (some portion of) an object's state must be saved so that it can be restored to that state later, and a direct interface to obtaining the state would expose implementation details and break the object's encapsulation Structure Participants – Memento, Originator, Caretaker Collaborations Consequences – Preserving encapsulation boundaries. It simplifies Originator. Using mementos might be expensive. Defining narrow and wide interfaces. Hidden costs in caring for mementos. Implementation Language support. Storing incremental changes.

249 Template method example
Intent Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. Motivation Applicability to implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary. when common behavior among subclasses should be factored and localized in a common class to avoid code duplication. to control subclasses extensions. You can define a template method that calls "hook" operations (see Consequences) at specific points, thereby permitting extensions only at those points.

250 Template method design pattern
Structure Participants - AbstractClass , ConcreteClass Collaborations Consequences Template methods are a fundamental technique for code reuse. Template methods lead to an inverted control structure that's sometimes referred to as "the Hollywood principle," that is, "Don't call us, we'll call you" Template methods call the following kinds of operations: concrete operations (either on the ConcreteClass or on client classes); concrete AbstractClass operations (i.e., operations that are generally useful to subclasses); primitive operations (i.e., abstract operations); factory methods (see Factory Method (107)); and hook operations, which provide default behavior that subclasses can extend if necessary. A hook operation often does nothing by default. Implementation Using C++ access control Minimizing primitive operations. Naming conventions.


Download ppt "Methods for Software Specification"

Similar presentations


Ads by Google