methods for software specification jan kožusznik. dept. of computer science technical university of...

250
Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan @ kozusznik . cz http:// www . kozusznik.cz

Upload: darren-briscoe

Post on 01-Apr-2015

224 views

Category:

Documents


1 download

TRANSCRIPT

Page 2: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• COCKBURN, A. Use Cases Jak efektivně modelovat aplikace. CP Books, a.s., 2005. ISBN 80-251-0721-3.

• FOWLER, M. UML Distilled: A Brief Guide to the Standard Object Modeling Language. Addison-Wesley Professional, 2003. ISBN 978-0321193681.

• GAMMA, E., HELM, R., JOHNSON, R. AND VLISSIDES, J.M. Design Patterns: Elements of Reusable Object-Oriented Software. 1st ed.: Addison-Wesley Professional, 1994. ISBN 978-0201633610.

• PFLEEGER, S.L. AND ATLEE, J.M. Software Engineering: Theory and Practice. Prentice Hall, 2009. ISBN 0136061699.

• POHL, K. Requirements Engineering: Fundamentals, Principles, and Techniques. Springer, 2010. ISBN 978-3642125775

• PRESSMAN, R.S. Software engineering : a practitioner's approach. 7th ed. New York: McGraw-Hill Higher Education, 2010. xxviii, 895 p. p. ISBN 9780073375977.

• SOMMERVILLE, I. Software engineering. 9th ed. Harlow: Addison-Wesley, 2010. xxiii, 840 p. p. ISBN 978-0137035151.

• WARMER, J. AND KLEPPE, A. The Object Constraint Language: Getting Your Models Ready for MDA. Addison-Wesley Professional, 2003. ISBN 0321179366.

Used literature

Page 3: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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

Page 4: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Software development „reality“

Page 5: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Users‘ vs. developers‘ viewHow 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.

Page 6: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Software process – key disciplines

Page 7: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Requirement specifications

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

Page 8: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Requirements

Requirement is1. A condition or capability needed by a user to solve a problem or achieve an

objective.2. 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.

3. 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.

Page 9: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

SRS should be

• Correct• Unambiguous• Complete• Consistent• Ranked for importance and/or

stability• Verifiable• Modifiable• Traceable

Page 10: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Functional requirements

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.

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.

Page 11: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Quality requirements I

Types of quality requirements• Important primarily for

developers– Maintainability– Portability– Reusability– Testability

A quality requirement defines a quality property of the entire system or of a system component, service, or function.

• Important primarily for users– Availability – Efficiency– Flexibility– Integrity– Interoperability– Reliability– Robustness– Usability

Page 12: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Quality requirements II

Types of quality requirements• Important primarily for

developers– Maintainability– Portability– Reusability– Testability

A quality requirement defines a quality property of the entire system or of a system component, service, or function.

• Important primarily for users– Availability – Efficiency– Flexibility– Integrity– Interoperability– Reliability– Robustness– Usability

Page 13: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Quality requirements III

Types of quality requirements• Important primarily for

developers– Maintainability– Portability– Reusability– Testability

A quality requirement defines a quality property of the entire system or of a system component, service, or function.

• Important primarily for users– Availability – Efficiency– Flexibility– Integrity– Interoperability– Reliability– Robustness– Usability

Page 14: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Non-functional requirements

Non-functional =

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.

Page 15: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Constraints I.

• Organizational process– Resources– Documentation– Standards

• Design (operational environment)– Physical environment– Interface– Users

A constraint is an organizational or technological requirement that restricts the way in which the system shall be developed.

Page 16: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Constraints II

• Organizational process– Resources– Documentation– Standards

• Design (operational environment)– Physical environment– Interface– Users

A constraint is an organizational or technological requirement that restricts the way in which the system shall be developed.

Page 17: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Constraints III

• Organizational process– Resources– Documentation– Standards

• Design (operational environment)– Physical environment– Interface– Users

A constraint is an organizational or technological requirement that restricts the way in which the system shall be developed.

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.

admin
nemá tu být hours?
Page 18: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Creation of textual requirement I

Specific thoughts

Thoughts

generalization

distortion

T o g s h u t

deletion

oug

Page 19: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Creation of textual requirement II

Specific thoughts

Thoughts

generalization

distortion

T o g s h u t

deletion

oug

Page 20: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Creation of textual requirement III

Specific thoughts

Thoughts

generalization

distortion

T o g s h u t

deletion

oug

Page 21: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

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.

Page 22: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 23: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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>

Page 24: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Primary actors and stakeholders gathering

• Interactions between Actors with Goals– Actors have goals– Goals can fail– Interactions are compound– A use case collects scenarios

• Contract between Stakeholders with Interests

Actors have goals supported by described system. The system should ensure interests of stakeholders.

Actors have goals supported by described system. The system should ensure interests of stakeholders.

Page 25: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Design scope IDesign scope is the extent of the

system

Page 26: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Design scope II

• "Enterprise" scope • "System" scope• "Subsystem" scope

Page 27: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Design scope III

• "Enterprise" scope • "System" scope• "Subsystem" scope

Page 28: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Design scope IVDesign scope is the extent of the

system

• "Enterprise" scope • "System" scope• "Subsystem" scope

Page 29: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

THREE NAMED GOALLEVELS

Page 30: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

THREE NAMED GOALLEVELS II

Page 31: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

THREE NAMED GOALLEVELS III

Page 32: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

THREE NAMED GOALLEVELS IV

Page 33: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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>

Page 34: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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>

Page 35: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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>

Page 36: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 37: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 38: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 39: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 40: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Action Steps – guideline 1: It uses simple grammar

Subject ... verb... direct object... prepositional phrase.

Example:

The system ... computes ... provision... from the invoiced amount.

Page 41: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 42: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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

Page 43: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 44: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Action Steps – guidelines 5:It shows the actor’s intentions, not

movements.

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.

Customer enters name, address, phone number, secret information, emergency contact phone number.

Customer enters- name- address- phone number- secret information- emergency contact phone number

more data items being passed

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

Page 45: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Action Steps – guidelines 6:It contains a ’reasonable’ set of actions.

1. The primary actor sends a request and data to the system.

2. The system validates the request and the data.

3. The system alters its internal state.

4. 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)

Page 46: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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 correct3. If it is, the system presents available actions to the user.

2. The system validates that the password is correct.3. The system presents available actions to the user.

Page 47: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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 ...

Page 48: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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."

4. The user has system A, fetch data from system B.

Page 49: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.„

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).

several steps to be repeated

Page 50: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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 on2. 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.

Page 51: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Extensions I

1. write every scenario individually – bad maintenance

2. use “if” statements through text - hard to read

3. write a scenario extension for each branch point - best

Page 52: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Extensions II

1. write every scenario individually – bad maintenance

2. use “if” statements through text - hard to read

3. 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.

Page 53: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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. ...

Page 54: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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".

Brainstorm all conceivable failures and alternative courses I

Page 55: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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".

Brainstorm all conceivable failures and alternative courses II

Page 56: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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:

Page 57: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Extension optimization

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...

Page 58: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Action Steps – guidelines 12:Condition handling is indented.

• indent the action step and start numbering again at 1

Extensions2a. Insufficient funds:

2a1. The system notifies customer, asks for a new amount.2a2. The customer enters new amount.

Page 59: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Failures within failures

Extensions6a. 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.

Page 60: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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.

Creating a new use case from an extension

Page 61: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Technology & Data Variations

• It is not extensions – it is rather specialization

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."

7. Repay customer for returned goods.Technology & Data Variations List:7a. Repay by check, EFTS, or credit against future purchases.

Page 62: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Linking Use Cases I

• Sub use cases

• Extension use cases

The user saves the reportThe user saves the report (UC 35 Save a Report)

Buy product Save a Report<<includes>>

Page 63: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Buy product

Find synonym

Change template

Check spelling

«extends»

«extends»

«extends»

Page 64: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Many asynchronous or interrupting services.• Adding to locked requirement document.

When to use extension use case

Buy product

Find synonym

Change template

Check spelling

«extends»

«extends»

«extends»

Page 65: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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).

Page 66: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Special use cases: CRUD

Create a User

Delete a User

Update a User

Retrieve a User

Manage a User

Page 67: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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).

Special use cases: parameterized use cases I

Similar USE-CASES: Find a Customer, Find a Product, Find a Promotion differing in:

Page 68: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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).

Special use cases: parameterized use cases II

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.

Similar USE-CASES: Find a Customer, Find a Product, Find a Promotion differing in:

Page 69: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 70: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 71: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 72: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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)

Page 73: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Data requirements:Field details & checks

Page 74: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Use Cases In Project Organization:Organization of use cases

1. Analytic: names of use cases with names of primary actors

2. Sponsor: priority of business need

3. Developer: technical difficulty

Page 75: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 76: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 77: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Use cases to design - II

• Design makes use of scenarios• Use cases name domain concepts

Page 78: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 79: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

UML Limitations: Example

+discount(in percentage : int) : float

-name : string-price : float

Product

+pay(in amount : float)

-name : string-address : string-e-mail : string

Customer

-sum : float-date : Date

Payment

-products

0..*

-buyer

0..1

3 orders

-items1..*

-payment

0..1

defines4 -remittance

0..1

-payer 1

3 pays

Page 80: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Correct Interpretation of Model

name : string = Ivo Vondrakaddress : string = Ostravae-mail : string = [email protected]

vondrak : Customername : string = Sony Ericsson T630price : float = 100

vondrak'sT630 : Product

name : string = ICT25price : float = 15

vondrak'sCase : Product

sum : float = 115date : Date = 12/24/2004

vondrak's : Payment

Page 81: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Mistaken Interpretation

name : string = John Smithaddress : string = Los Angelese-mail : string = [email protected]

smith : Customer

name : string = Sony Ericsson T630price : float = 100

vondrak'sT630 : Product

name : string = ICT25price : float = 15

vondrak'sCase : Product

sum : float = 200date : Date = 12/24/2003

vondrak's : Payment

name : string = Ivo Vondrakaddress : string = Ostravae-mail : string = [email protected]

vondrak : Customer

name : string = Sony Ericsson P900price : float = 200

smith'sP900 : Product

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!

Page 82: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

OCL – Object Constraint Language

• 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.

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 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.

Page 83: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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 e-mail 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.

+discount(in percentage : int) : float

-name : string-price : float

Product

+pay(in amount : float)

-name : string-address : string-e-mail : string

Customer

-sum : float-date : Date

Payment

-products

0..*

-buyer

0..1

3 orders

-items1..*

-payment

0..1

defines4 -remittance

0..1

-payer 1

3 pays

Page 84: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

OCL Expressions

+discount(in percentage : int) : float

-name : string-price : float

Product

+pay(in amount : float)

-name : string-address : string-e-mail : string

Customer

-sum : float-date : Date

Payment

-products

0..*

-buyer

0..1

3 orders

-items1..*

-payment

0..1

defines4 -remittance

0..1

-payer 1

3 pays

• context Paymentinv: self.items->forAll (item | item.buyer = payer)

• context Customerinv: Customer::allInstances()->isUnique(e-mail)

• context Paymentinv: self.items.price->sum() = self.sum

• context Customer::pay(amount: float)pre: self.remittance.sum = amount

• 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 e-mail 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.

Page 85: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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

Page 86: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Types in OCL

• Boolean• Integer• Real• String• User defined – classes, enumeration• Collection

Page 87: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Boolean operators

• Simple operators– 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

Page 88: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Integer and Real operators

• =,<>, <, >, <=, >=, +, -, *, /• a.mod(b), a.div(b) , a.abs(), a.max(b), a.min(b),

a.round(), a.floor(),

2654 * 4.3 + 101 = 11513.2

(3.2).floor() / 3 = 1

1.175 * (-8.9).abs() - 10 = 0.4575

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

Page 89: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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'

Page 90: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Invariants

• Invariants on attributescontext Productinv ofPrice: self.price >= 0

• Invariants on associated objectscontext Paymentinv ofAge: payer.age >= 18

An invariant is a constraint – a boolean expression - that should be true for an object during its complete lifetime.

An invariant is a constraint – a boolean expression - that should be true for an object during its complete lifetime.

Keyword self means reference to a given instance. Its use is mandatory in the case of ambiguity only.

Page 91: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

1. Attribute age of every customer object must be equal to or greater than 18.

context Customerinv ofAge: age >= 18

LoyaltyProgram

name: String

Customer

name:Stringtitle:StringisMale:BooleandateOfBirth:Date/age:Integer

«datatype»Customer

now:Data

isBefore(t:Date):BooleanisAfter(t:Date):Boolean=(t:Date):Boolean

Date is a utility class

0..*

programs

0..*

participants

CustomerCard

valid:BooleanvalidFrom:DategoodThru:Datecolor:Color/printedName:String

block()

1owner

0..*cards

ProgramPartner

numberOfCustomers:Integername:String

1..* partners

1..*

programs

Page 92: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

2. validFrom should be earlier than goodThru.

context CustomerCard inv checkDates: validFrom.isBefore(goodThru)

LoyaltyProgram

name: String

Customer

name:Stringtitle:StringisMale:BooleandateOfBirth:Date/age:Integer

«datatype»Customer

now:Data

isBefore(t:Date):BooleanisAfter(t:Date):Boolean=(t:Date):Boolean

Date is a utility class

0..*

programs

0..*

participants

CustomerCard

valid:BooleanvalidFrom:DategoodThru:Datecolor:Color/printedName:String

block()

1owner

0..*cards

ProgramPartner

numberOfCustomers:Integername:String

1..* partners

1..*

programs

Page 93: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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

+discount(in percentage : int) : float

-name : string-price : float

Product

+pay(in amount : float)

-name : string-address : string-e-mail : string

Customer

-sum : float-date : Date

Payment

-products

0..*

-buyer

0..1

3 orders

-items1..*

-payment

0..1

defines4 -remittance

0..1

-payer 1

3 pays

Page 94: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

3. Every owner of CustomerCard has age greater than or equal to 18.

context CustomerCard inv ofAge: owner.age >= 18

LoyaltyProgram

name: String

Customer

name:Stringtitle:StringisMale:BooleandateOfBirth:Date/age:Integer

«datatype»Customer

now:Data

isBefore(t:Date):BooleanisAfter(t:Date):Boolean=(t:Date):Boolean

Date is a utility class

0..*

programs

0..*

participants

CustomerCard

valid:BooleanvalidFrom:DategoodThru:Datecolor:Color/printedName:String

block()

1owner

0..*cards

ProgramPartner

numberOfCustomers:Integername:String

1..* partners

1..*

programs

Page 95: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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()

Page 96: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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).

Page 97: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

4. Only a customer associated to some programs could have some cards – every customer with at least one card is associated to some program

context Customerinv minServices: self.cards->size() > 1 implies self.programs->size() > 1

LoyaltyProgram

name: String

Customer

name:Stringtitle:StringisMale:BooleandateOfBirth:Date/age:Integer

«datatype»Customer

now:Data

isBefore(t:Date):BooleanisAfter(t:Date):Boolean=(t:Date):Boolean

Date is a utility class

0..*

programs

0..*

participants

CustomerCard

valid:BooleanvalidFrom:DategoodThru:Datecolor:Color/printedName:String

block()

1owner

0..*cards

ProgramPartner

numberOfCustomers:Integername:String

1..* partners

1..*

programs

Page 98: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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

Page 99: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

5. The number of valid cards for every customer must be equal to the number of programs in which the customer participates.

context Customerinv sizesAgree: programs->size() = cards->select( valid = true )->size()

LoyaltyProgram

name: String

Customer

name:Stringtitle:StringisMale:BooleandateOfBirth:Date/age:Integer

«datatype»Customer

now:Data

isBefore(t:Date):BooleanisAfter(t:Date):Boolean=(t:Date):Boolean

Date is a utility class

0..*

programs

0..*

participants

CustomerCard

valid:BooleanvalidFrom:DategoodThru:Datecolor:Color/printedName:String

block()

1owner

0..*cards

ProgramPartner

numberOfCustomers:Integername:String

1..* partners

1..*

programs

Page 100: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Iterator Variables

context Customerinv: Customer::allInstances()->isUnique(e-mail)

orcontext Customer

inv: Customer::allInstances()->isUnique(c | c.e-mail)orcontext Customer

inv: Customer::allInstances()->isUnique(c:Customer | c.e-mail)

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.

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.

Page 101: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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

Page 102: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

6. Attribute numberOfCustomers holds the number of customers who participate in one or more loyalty programs offered by this program partner

context ProgramPartner inv nrOfParticipants: self.numberOfCustomers = self.programs.participants->flatten()->asSet()->size()

LoyaltyProgram

name: String

Customer

name:Stringtitle:StringisMale:BooleandateOfBirth:Date/age:Integer

«datatype»Customer

now:Data

isBefore(t:Date):BooleanisAfter(t:Date):Boolean=(t:Date):Boolean

Date is a utility class

0..*

programs

0..*

participants

CustomerCard

valid:BooleanvalidFrom:DategoodThru:Datecolor:Color/printedName:String

block()

1owner

0..*cards

ProgramPartner

numberOfCustomers:Integername:String

1..* partners

1..*

programs

Page 103: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Preconditions and Postconditions

context Product::discount(percentage: Integer) : Realpre: percentage >= 0 and percentage <= 10 post:

let oldPrice : Real = self.price@prein self.price = oldPrice –

(oldPrice*percentage/100)and result = self.price

Preconditions and postconditions are constraints that specify the applicability and effect of an operation without stating an algorithm or implementation.

Preconditions and postconditions are constraints that specify the applicability and effect of an operation without stating an algorithm or implementation.

Page 104: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

7. Consider method CustomerCard::block – value of valid is set to false and old value of the attribute is returned.

context CustomerCard::block():boolean post: self.valid =false and result = self.valid@pre

LoyaltyProgram

name: String

Customer

name:Stringtitle:StringisMale:BooleandateOfBirth:Date/age:Integer

«datatype»Customer

now:Data

isBefore(t:Date):BooleanisAfter(t:Date):Boolean=(t:Date):Boolean

Date is a utility class

0..*

programs

0..*

participants

CustomerCard

valid:BooleanvalidFrom:DategoodThru:Datecolor:Color/printedName:String

block()

1owner

0..*cards

ProgramPartner

numberOfCustomers:Integername:String

1..* partners

1..*

programs

Page 105: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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();

Page 106: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

8. Derived attribute printedName of CustomerCard is determined based on the name and title of the card owner.

context CustomerCard::printedName:String derive: self.owner.title.concat(' ').concat(self.owner.name)

LoyaltyProgram

name: String

Customer

name:Stringtitle:StringisMale:BooleandateOfBirth:Date/age:Integer

«datatype»Customer

now:Data

isBefore(t:Date):BooleanisAfter(t:Date):Boolean=(t:Date):Boolean

Date is a utility class

0..*

programs

0..*

participants

CustomerCard

valid:BooleanvalidFrom:DategoodThru:Datecolor:Color/printedName:String

block()

1owner

0..*cards

ProgramPartner

numberOfCustomers:Integername:String

1..* partners

1..*

programs

Page 107: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

9. Let‘s introduce a derived attribute called turnover in class Service which would sum the amount attributes of the transactions on the account.

context Service def: turnover : Real = self.transactions.amount->sum()

LoyaltyProgram

name: String

Customer

name:Stringtitle:StringisMale:BooleandateOfBirth:Date/age:Integer

«datatype»Customer

now:Data

isBefore(t:Date):BooleanisAfter(t:Date):Boolean=(t:Date):Boolean

Date is a utility class

0..*

programs

0..*

participants

CustomerCard

valid:BooleanvalidFrom:DategoodThru:Datecolor:Color/printedName:String

block()

1owner

0..*cards

ProgramPartner

numberOfCustomers:Integername:String

1..* partners

1..*

programs

Service

1 partner

0..* deliveredServices

Transaction

points:Integerdate:Dateamount:Real

1generatedBy

0..*

transactions

1card

0..*

transactions

Page 108: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Initial values

• Attributes

context CustomerCard::valid : Boolean

init: true • Association role

context Customer::products : Set( Products)

init: Set{}

Page 109: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

10. A new CustomerCard is valid if and only if owner has already at least another one card.

context CustomerCard::valid: Booleaninit: self.owner.cards->exists(c| c != self and c.valid)

LoyaltyProgram

name: String

Customer

name:Stringtitle:StringisMale:BooleandateOfBirth:Date/age:Integer

«datatype»Customer

now:Data

isBefore(t:Date):BooleanisAfter(t:Date):Boolean=(t:Date):Boolean

Date is a utility class

0..*

programs

0..*

participants

CustomerCard

valid:BooleanvalidFrom:DategoodThru:Datecolor:Color/printedName:String

block()

1owner

0..*cards

ProgramPartner

numberOfCustomers:Integername:String

1..* partners

1..*

programs

Page 110: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Roots of UML

OMTObject Modeling Technique

J. Rumbaugh

OMTObject Modeling Technique

J. Rumbaugh

Booch Method...

G. Booch

Booch Method...

G. Booch

OOSEObject-oriented Software Engineering

I. Jacobson

OOSEObject-oriented Software Engineering

I. Jacobson

UMLUnified Modeling Language

Rational

UMLUnified Modeling Language

Rational

Standardized by OMG

Page 111: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

UML using

• Three modes:– as a sketch– as a Blueprint– as a programing language.

• Two directions:– forward engineering– reverse engineering

Page 112: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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

Page 113: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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

Page 114: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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

Page 115: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

UML as a programming language I

• another level of code generation• requires sophisticated tools• environment should provide better

productivity• requires a mass of users

Page 116: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

UML as a programming language II

• another level of code generation• requires sophisticated tools• environment should provide better

productivity• requires a mass of users

Page 117: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Clas Diagram

Structure Diagram

Diagram

BehaviorDiagram

CompositeStructureDiagram

ObjectDiagram

Component Diagram

Deployment Diagram

PackageDiagram

ActivityDiagram

Use CaseDiagram

State MachineDiagram

SequenceDiagram

CommunicationDiagram

InteractionOverviewDiagram

TimingDiagram

InteractionDiagram

UML diagrams

UML2

UML2

UML2

Page 118: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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

Page 119: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

UML in a software process – software requirements I

Page 120: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

UML in a software process – software requirements II

Page 121: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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.

UML in a software process – design I

Page 122: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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.

UML in a software process – design II

Page 123: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Documentation– only for highlighting most important parts

• understanding Legacy Code

UML in a software process – maintenance

Page 124: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Where to Start with UML

Page 125: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• majority of UML diagrams• types(classes) of object

and various kind of static relations among them

• constraints• feature – operation and

properties

Class diagrams

Order

DateRecieved: Date[0..1]IsPrepaid: Boolean[1]number: String[1]price: Money

DispatchClose

1*

association

multiplicity

class

Customer

name[1]address[0..1]

getCreditRating(): String

constraint

{if Order.customer.getCreditRating is"poor" then Order.isPrepaid must be true}

Order Line

quantity: Integerprice: Money

Product

*

1

navigable

* {ordered}lineitems

role name

1generalization

Personal Customer

creditCardNumber

{getCreditRating == "poor"}

Corporate Customer

contactNamecreditRatingcreditLimit

billForMonth(Integer)remind()

attributes

operations

Employee

*

salesRep 0..1

Page 126: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• structural features of a class• attributes:

Class diagrams – properties I

visibility name: type multiplicity = default {property-string}

Example: -name: String [1] = "Joe Daw" {readOnly}

• association show many similar information to attributes:

Page 127: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• structural features of a class• attributes:

Class diagrams – properties II

• association shows much similar information to attributes:

Order

+ dateReceived: Date [0..1]+ isPrepaid: Boolean [1]+ lineItems: OrderLine[*] {ordered}

Date Order Boolean

OrderLine

*0..1

+dateReceived

+isPrepaid

1

lineItems{ordered}

1

*

source

target

==

Page 128: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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)

Associations - multiplicity

Order

1

lineItems{ordered}

OrderLine

*

Page 129: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• a pair of properties that are linked together as inverse.

Bidirectional Associations

• label association by using a verb phrase.

Person

Car

owner

0..1 *

Person

Car

0..1 *

Owns

Page 130: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• the actions that a class knows to carry out

Class diagrams - operations

visibility name (parameter-list) : return-type {property-string}

direction name: type = default value

• parameters - similar way to attributes:

Example: + balanceOn (inout date: Date) : Money

Page 131: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Obvious inheritance• substatiability

– Subtyping– subclassing

Generalization

Page 132: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• can appear in any kind of diagram

Notes and Comments

Includes pick-upsand SUVs but notmotorbikes

Car

Page 133: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Change of one elements may cause definition of another elements

• Basically, it is not transitive.• Minimalize dependencies – lower coupling• Be selective with showing

Dependency

DiscountsWindow

client

Order

OrderDataGateway

DiscountsDataGateway

«use»

supplier

«use»

«use»

Page 134: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Minimalize dependencies – lower coupling• Be selective with showing

Dependency II

<<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.

Page 135: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Class diagram cannot indicate every constraint

• Name of constraint –

{disallow incest: husband and wife not be siblings}

Constraint rules

{if Order.customer.getCreditRating is"poor" then Order.isPrepaid must be true}

Order

IsPrepaid: Boolean[1]

Order

name[1]address[0..1]

getCreditRating(): String1*

Page 136: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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 – usage I

Page 137: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Class diagrams – usage II

Page 138: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• The most common interaction diagram in UML• Single scenario – objects, messages

Sequence diagrams

an Order

an Order Line

aProduct

aCustomer

calculatePrice

found message

getQuantity

getProduct

aProduct

return

getPricingDetails

calculateBasePrice

participant

self-call

calculateDiscounts

getDiscountInfo

message

lifeline

activation

Page 139: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Explicit deletion in gc environment is also available – it indicates that it is no longer needed

Sequence diagrams :Creating and deleting participants

a Handler

queryDatabase

new

creation

a QueryCommand

new a DatabaseStatement

execute

results

extract result

close

deletion fromother object

results

self-deletion

Page 140: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Possible use of another diagram• Interaction frames are available in a sequence

diagram

Sequence diagrams: Loops, Conditionals

procedure dispatch foreach (lineitem) if (product.value > $10K) careful.dispatch else regular.dispatch end if end for if (needsConfirmation) messenger.confirmend procedure

:Order

careful:

Distributor

regular:

Distributor

:Messenger

loop

dispatch

[for each line item]

[value >$10000]

[needsConfirmation]

dispatch

dispatch

alt

opt

confirm

frame

operator

[else]

guard

Page 141: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Common operators for interaction frames

Operator 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

Page 142: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Synchronous message

• Asynchronous message

Sequence diagrams: Synchronous and Asynchronous Calls

execute

dispatch

Page 143: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

When to Use Sequence Diagrams

Page 144: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Consider:1. Shep is a Border Collie.

2. A Border Collie is a Dog.

3. Dogs are Animals.

4. A Border Collie is a Breed.

5. 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

Classification and Generalization

Page 145: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Class Diagrams - Advanced Concepts: Multiple and Dynamic Classification

Female

Male

Person

Doctor

Physio-Therapist

Nurse

Surgeon

Family Doctor

Patient

sex

patient

role

discriminator

Page 146: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• It allows you to add: attributes, operations, and other features to associations

 

Class Diagrams - Advanced Concepts: Association Class

Attendance

attentiveness

Person

Meeting2..* *

assocation class

Attendance

attentiveness

Person

Meeting1 1* 2..*

Page 147: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• T is a placeholder for the type parameter• Use of a parameterized class is called derivation:

Class Diagrams - Advanced Concepts: Template (Parameterized) Class

class Set <T> {void insert (T newElement);void remove (T anElement);

T

Set

insert(T)remove(T)

template parametr

template class

Set <T::Employee>

T

Set

insert(T)remove(T)

template class

Set <T::Employee>

<T::Employee>

«bind»

bound element

binding for parameter

Page 148: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Shows a fixed set of values having only their symbolic values,

• <<enumeration>> keyword

Class Diagrams - Advanced Concepts: Enumerations

«enumeration»Color

redwhiteblue

Page 149: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• It has instance executing its own thread of control

Class Diagrams - Advanced Concepts: Active class

Control panel

Siren

Security sensor

Fire sensor

Security sensor monitor Fire sensor monitor

1

1

11

1

0..*

1

1

0..*

Page 150: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• You can tag every feature with:– + … public– - … private– # … protected– ~ …package

• their meaning dependents base on a used programming language

Class Diagrams - Advanced Concepts: Visibility

Page 151: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Class Diagrams - Advanced Concepts:Responsibilities

View

Responsibilities--display informationabout the model

Model

--domain logic

Input Controller

-- handles input events

Page 152: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Class Diagrams - Advanced Concepts: Static Operations and Attributes

Order

getNumbergetNextNumber

instance scope static

Page 153: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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.

Class Diagrams - Advanced Concepts: Aggregation and Composition

Person

Club

members

* *

Point

Polygon

{ordered}

3..*

Circle

1

center

Page 154: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Class Diagrams - Advanced Concepts: Derived properties

{length = start - end}Date Range

start: Dateend: Date/length: Integer

derivedattribute

Page 155: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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}.

Class Diagrams - Advanced Concepts: Abstract Classes

Abstract List

equalsgetadd

ArrayList

getadd

overriding

abstract class

abstract method

Page 156: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Class without any implementation – directly corresponds to JAVA, C#

• Label «interface» • Two kinds of relation with classes:

– Implements– Requires

Class Diagrams - Advanced Concepts: Interfaces

Abstract List

equalsgetadd

«interface»Collection

equalsadd

interfaceabstract class

abstract method

«interface»List

get

Order

Line Items [*]

dependency(requires inteface)

implementation(provides inteface)

Page 157: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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();

Class Diagrams - Advanced Concepts: Benefits of interface using

Page 158: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Lollipop notation was in the previous UMLversion

• Socket syntax – alternative syntax for dependency description; addition in UML 2.0

Class Diagrams - Advanced Concepts: Interface ball-and-socket notation

Order

Line Items [*]

ArrayList

List

Collection

Order

Line Items [*]

ArrayList

List

Collection

Page 159: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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»

Class Diagrams - Advanced Concepts: Reference Objects and Value Objects

Page 160: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Equivalent to associative array, maps, hashes, and dictionaries

Class Diagrams - Advanced Concepts: Qualified Associations

Order Order

Order Line

amount:Number

line item

0..1

Page 161: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• a snapshot of a system at a specific time• elements are underlined• useful for showing examples of objects

connected together

Object diagrams

Person

Organization

Party

location* children

0..1 parent

engineering: Organization

location = "Boston"

tools: Organization

location = "Chicago"

apps: Organization

location = "Saba"

Don: Person

location = "Champaign"

John: Person

location = "Champaign"

parent

parent

Page 162: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Package Diagrams

util

utilDate

util

Date

java::util

Date

util

Date

java

java::util::Date

Contents listedin box

Contents diagramed in box

Fully qualified package name

Nested packages Fully qualified class name

Page 163: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Packages and Dependencies I

leasingpresentation

Database

assetpresentation

leasingdomain

leasingdata mapper

assetdomain

assetdata mapper

UI framework

Page 164: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Packages and Dependencies II

leasingpresentation

Database

assetpresentation

leasingdomain

leasingdata mapper

assetdomain

assetdata mapper

UI framework

Page 165: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• One package contains a class implementing interface from another package.

Implementing Packages

ApplicationDatabaseGateway

OracleGateway

SQL ServerGateway

Test StubGateway

Page 166: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Shows system’s physical layout

• Shows communication paths and connected nodes

• Useful in showing what is deployed where.

Deployment Diagrams

BrowserClient browser

Rich Client(OS Windows)

herculesClient.exe

Web Server(OS Solaris

(web server: apache)(number deployed = 3)

herculesWeb.war

JoveGL.exe(vendor = romanScot)(component = General Ledger)

EJB Container herculesBase.earherculesAR.earherculesAP.ear

Oracle DBMS

http/Internet http/Lan

device mode

tagged value

communication path

deployed artifact

JDBC

Application Server

Java RMI LAN

Page 167: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• It is not mandatory – instead, diagrams concentrate on the textual content

• Graphical table of use cases

Use Case diagrams

TradingManager

TraderSalesperson

AccountingSystem

Set Limits

Analyze Risk

Deal Price

Capture Deal

Update Accounts

Value Deal«includes»

«includes»include

actoruse case

system boundary

Page 168: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Based on a finite automaton• Lifetime behavior of a single

object• Shows only what the object

directly observes or activates

State Machine Diagram

wait

Open

lock

safe closed

candle removed[door closed]/reveal lock

key turned[candle out]/release killer rabbit

final state

state

Initial pseudostatetransition

key turned[candle in]/open safe

Page 169: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

State Machine Diagrams – Internal activities

Typing

entry/highlight allexit/update fieldcharacter/ handle characterhelp[verbose]/ open help pagehelp[quiet]/ update status bar

Page 170: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• States when objects do something• Marked with do/• Can be interrupted

State Machine Diagrams – Activity states

Searching

do/ search for new hardware

activity

Page 171: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Often several states share common transitions and internal activities – shared behavior into a superstate

State Machine Diagrams – Superstates

Enter PhoneNumber

Choose Sharedor Solo

Enter Name

Show Connections

next

back

next

back

save

Enter Connection Details

new

cancel

Page 172: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• States can be broken down into several orthogonal state diagrams that run concurrently

• History pseudostate restores the last state

State Machine Diagrams – Concurrent states

Playing Radio

time

Playing CD

H

Radio CD

historical pseudostate

Display CurrentTime

Display AlarmTime alarm

On

concurrent boundary

Off

on off

Page 173: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Good for describing a single object across several use cases

• Not good at describing behavior that involves a number of objects collaborating

State Machine Diagrams – when to use I

Page 174: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

State Machine Diagrams – when to use II

Page 175: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Activity diagrams - I

ReceiveOrder

FillOrder

Send Invoice

OvernightDelivery

RegularDelivery

initial mode

fork

action

decision

merge

ReceivePayment

flow/edge

join

CloseOrder

activity final

[priority order]

[else]

Page 176: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Activity diagrams – II

ReceiveOrder

FillOrder

Send Invoice

OvernightDelivery

RegularDelivery

initial mode

fork

action

decision

merge

ReceivePayment

flow/edge

join

CloseOrder

activity final

[priority order]

[else]

Page 177: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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)

Activity diagrams – decomposing an action

ReceiveOrder

FillOrder

Send Invoice(Order::sendInvoice)

ReceivePayment

CloseOrder

Deliver Order

rake indicates sub activity diagram

methodinvocation

[else]

RegularDelivery

OvernightDelivery

[Rush Order]

inputparameter

activity name

Deliver Order

outputparameter

Order Order

Page 178: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Work flow and process modeling• Representation of behavioral logic• Description of use case

Activity diagrams - when to use

Page 179: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Activity diagrams – partitions

ReceiveOrder

FillOrder

Send Invoice

DeliverOrder

CloseOrder

ReceivePayment

Customer Service FinanceFullshipment

Page 180: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Actions can also respond to signals.

Activity diagrams – signals

Two hoursbefore flight

Pack Bags

Taxi Arrives

Leave for Airport

time signal

accept signal

Page 181: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Sending a signal is also supported – communication with external process

Activity diagrams – sending and receiving signals

Reserve Itinerary

send Itinerary

ItineraryConfirmed

wait 48 hours

Cancel Itinerary

Book Itinerary

accept signal

send signal

Page 182: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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.

Activity diagrams – tokens

Page 183: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Activity diagrams – flows and edges

ReceiveInvoice

MakePayment

ReceiveInvoice

ReceiveInvoice

ReceiveInvoice

MakePayment

MakePayment

MakePayment

A

connector

A

Order

object mode

Order

Order

pin

Page 184: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Activity diagrams – pins and transformations

CancelAppointment

Notify Patient

«transformation»appointment.cancellationNotice

«transformation»appointment.patient

Message Patient

Appointmentpin for parametr

transformation expression

Page 185: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Activity diagrams – expansions regions

Choose Topics

Write Article Review ArticlePublish

Newsletter

expansion region

list of topics

list box pin

-concurrent-

keyword

Choose Topics

Prepare ArticlePublish

Newsletter

Page 186: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Activity diagrams – flow final

Choose Topics

PublishNewsletter

Write Article Review Article

«concurrent»

list of topics

[accept]

[reject]

flow final

Page 187: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Join specification – another involved rule attached to a join

Activity diagrams – join specification

Select Drink

Insert Coin

DispenseDrink

{joinSpec = A and B and value ofinserted coins >= price of selected drink}

join specification

Page 188: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Communication diagrams

an Order

an Order Line

a Customer

a Product

1: calculatePrice

2: getQuantity()

3: getProduct()

4: getPricingDetails()

«local»

transparent link type

5: calculateBasePrice()6: calculateDiscounts()

self link

! non-normative

7: getDiscountInfo

Page 189: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Communication diagrams - transient links

Page 190: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Legal numbering style should be nested

• It resolves ambiguity with self-calls

• Many people prefer a flat numbering scheme – simpler

Communication diagrams - decimal numbering

an Order

an Order Line

a Customer

a Product

1: calculatePrice

1.1: getQuantity()

1.2: getProduct ()

1.3: getPricingDetails

1.4: calculateBasePrice()1.5: calculateDiscounts ()

!non-

normative

1.5.1: getDiscountInfo

Page 191: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Sequence diagrams are more common• Personal preference• Easier to draw on a white board – good for

exploring alternatives

Communication diagrams - when to use

Page 192: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Hierarchically decompose a class into an internal structure

• Allow to take a complex object and break it down into parts

Composite structures

controls:

TVPresenter

:Generator[1]

TV Viewer

1

TV control UI

multiplicity

display

TV control API

picture streamtuning

delegating connector

connector

part

Page 193: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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

Composite structures – interfaces

controls:

TVPresenter

:Generator[1]

TV Viewer

1

TV control UI

multiplicity

display

TV control API

picture streamtuning

delegating connector

connector

part

Page 194: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Show runtime grouping (packages are compile time grouping)

• Similar to a component

Composite structures – when to use

Page 195: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Annotated class in UML 2.0 – no additional syntax

Component diagram

Widget

Widget

UML 1 notationUML 2 notation

Page 196: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Component diagram – example

Till

Massage Queue

TransactionProcessor

AccountingDriver

AccountingSystem

Sales Serversales

message

Page 197: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Beware of overly fine-grained components – hard to manage.

• Components and their interrelationship through interfaces.

Component diagram – when to use

Page 198: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• 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.

Collaborations

Auction

buyer offer

lotseller

*1

*

1

11

rolecollaboration

/seller b1/buyer b2/buyer

advertise lot

submit offer

accept offer

reject offer

submit offer

Page 199: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Collaboration occurrence

Party

Bid

House

*

*

1

* *

1buyer

seller

Auction

buyer, sellerlot

other

role binding

collaboration occurance

Page 200: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Activity and sequence diagram together

Interaction Overview Diagrams

sd

:Customer

:XmlParser

load

parse

getName

getOrders

:OrderSummary

new

:OrderSummary

new

:Customer

:Customer

select from customers and orders

sd

ref

Format Order Summary Repoůrt

Page 201: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Inspiration from electrical engineering• States as a line vs. states as an area

Timing Diagrams

On

Off

On

Off

state

waterEmpty

event

Pu

mp

Ho

tpla

te

objects{>10s}

{>15m}

state change

t iming const raint

Off

OnOff

state

waterEmpty

event

Ho

tpla

te

object{>10s}

{>15m}

t iming constraint

Off

On Off

state change

Pu

mp

Page 202: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 203: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Pattern name• Problem• Solution• Consequences

General structure of design patterns

Page 204: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Pattern Name and Classification• Intent• Also Known As• Motivation• Applicability• Structure• Collaborations• Consequences• Implementation• Sample Code• Known Uses• Related Patterns

Structure of design patterns in software design

Page 205: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

• Pattern Name and Classification• Intent• Also Known As• Motivation• Applicability• Structure• Collaborations• Consequences• Implementation• Sample Code• Known Uses• Related Patterns

Structure of design patterns in software design II

Page 206: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 207: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 208: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Factory Method Example

+newDocument()+createDocument() : Document

Application

1 *+open()+close()+save()

Document

PDFDocument WordDocument

+createDocument() : Document

WordApplication

+createDocument() : Document

PDFApplication

«instantiate»

«instantiate»

return new WordDocument

Document d = self.createDocument()

Page 209: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Factory Method Design Pattern

+factoryMethod()+anOperation()

Creator Product

ConcreteProduct

+factoryMethod() : Product

ConcreteCreator «instantiate»

...p = factoryMethod()...

return new ConcreteProduct()

Page 210: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Abstract Factory Example

+createWindow() : Window+createScrollBar() : ScrollBar

WidgetFactoryWindow

MSWindow MotifWindow

ScrollBar

MSScrollBar MotifScrollBar

+createWindow() : Window+createScrollBar() : ScrollBar

MotifWidgetFactory

+createWindow() : Window+createScrollBar() : ScrollBar

MSWidgetFactory

«instantiate»

«instantiate»

«instantiate»

«instantiate»

Client1

1

1

*

1

*

Page 211: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Abstract Factory Design Pattern

+createProductA() : AbstractProductA+createProductB() : AbstractProductB

AbstractFactoryAbstractProductA

ProductA1 ProductA2

AbstractProductB

ProductB1 ProductB2

+createProductA() : AbstractProductA+createProductB() : AbstractProductB

ConcreteFactory2

+createProductA() : AbstractProductA+createProductB() : AbstractProductB

ConcreteFactory1

«instantiate»

«instantiate»

«instantiate»

«instantiate»

Client1

1

1

*

1

*

Page 212: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Prototype Example

+insert()

Tool

+draw(in position)+clone() : Graphic

Graphic

+draw(in position)+clone() : Graphic

Rectangle

+draw(in position)+clone() : Graphic

Circle

1

-prototype

1

g = prototype.clone()while (user drags mouse) { g.draw(new position);}insert symbol into drawing;

return copy of self return copy of self

Page 213: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Prototype Design Pattern

+operace()

Client

+clone() : Prototype

Prototype

+clone() : Prototype

ConcretePrototype1

+clone() : Prototype

ConcretePrototype2

1

-prototype

1

p = prototype.clone()

return copy of self return copy of self

Page 214: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Builder example

Page 215: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Builder design pattern

Page 216: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Singleton design pattern

Page 217: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 218: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Composite Example

Client

+add(in g : Graphic)+remove(in g : Graphic)+getChild(in index : int) : Graphic+draw()

Graphic

+draw()

Rectangle

+draw()

Circle

+add(in g : Graphic)+remove(in g : Graphic)+getChild(in index : int) : Graphic+draw()

Drawing

1

-component

*

1 1

for (all graphics in picture) component.draw()

Page 219: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Composite Design Pattern

Client

+add(in c : Component)+remove(in c : Component)+getChild(in index : int) : Component+operation()

Component

+operation()

Leaf

+add(in g : Component)+remove(in g : Component)+getChild(in index : int) : Component+operation()

Composite

1

-component

*

1 1

for (all components) component.operation()

Page 220: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Adapter Example

DrawingEditor

+getBoundingBox() : Rectangle

Shape

+getBoundingBox() : Rectangle

LineShape

+getBoundingBox() : Rectangle

TextShape

+getExtent() : Rectangle

TextView

1 *

1

-text

1

return text.getExtent()

Page 221: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Adapter Design Pattern

Client

+request()

Target

+request()

Adapter

+specificRequest()

Adaptee

1 1

1

-text

1

adaptee.specificRequest()

Page 222: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Decorator Example

+draw()

VisualComponent

+draw()

TextView

+draw()

-

Decorator

+draw()+drawBorder()

BorderDecorator

+draw()+scrollTo()

ScrollDecorator

1

-component

1

component.draw()

super.draw()scrollTo()

super.draw()drawBorder()

component

aBorderDecorator

component

aScrollDecorator

aTextView

Page 223: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Decorator Design Pattern

+operation()

Component

+operation()

ConcreteComponent

+operation()

-

Decorator

+operation()+addedOperation1()

ConcreteDecorator1

+operation()+addedOperation2()

ConcreteDecorator2

1

-component

1

component.operation()

super.operation()addedOperation2()

Page 224: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Proxy Example

DocumentEditor

+draw()+getExtent()

Element

+draw()+getExtent()

-extent-content

Text

+draw()+getExtent()

-imageImp

Image

+draw()+getExtent()+load()

-fileName-extent

ImageProxy

1 *

-image

1 1

if (image == null) image = load(fileName)image.draw()

if (image == null) return extentelse return image.getExtent()

Page 225: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Proxy Design Pattern

Client

+request()

Subject

+request()

RealSubject

+request()

Proxy

1 *

-real

1 1

real.request()

Page 226: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Facade design pattern

Page 227: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Flyweight example

Page 228: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Flyweight design pattern

Page 229: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

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.

Page 230: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Chain of Responsibility Example

Client

+handleHelp()

HelpHandler

+handleHelp()+showHelp()

Application Widget

+handleHelp()+showHelp()

Dialog

+handleHelp()+showHelp()

Button

1 1 1

-handler1

handler.handleHelp()

if (can handle) showHelp()else super.handleHelp()

handler

aClient

handler

aButton

handler

aDialog

handler

anApplication

Page 231: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Chain of Responsibility Design Pattern

Client

+handleRequest()

Handler

+handleRequest()

ConcreteHandler1

+handleRequest()

ConcreteHandler2

1 1 1

-successor1

successor.handleRequest()

Page 232: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Command Example

+add(in doc : Document)

Application

+open()+close()+cut()+copy()+paste()

Document

+add(in m : MenuItem)

Menu

+clicked()

MenuItem

+execute()

Command

1 * 1 * 1

-command

1

+execute()

PasteCommand

1

* +execute()+askUser() : string

AddCommand-document

1 1

1

-application 1command.execute()

document.paste()

name = askUser()doc = new Document(name)application.add(doc)doc.open()

Page 233: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Command Desing Pattern

Client

+action()

Receiver

Invoker

+execute()

Command

1

-command

1

+execute()

ConcreteCommand

1

1

-receiver

1 1

receiver.action()

«instantiate»

Page 234: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Iterator Example

+createIterator() : Iterator

Collection Client

+first()+next()+isDone()

Iterator

+createIterator() : Iterator+append()+remove()+get(in index)

List

+createIterator() : Iterator+pop()+push()+top()

Stack

+first()+next()+isDone()

StackIterator

+first()+next()+isDone()

ListIterator

1 1 1 1

1 1

«instantiate»

11

«instantiate»

Page 235: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Iterator Design Pattern

+createIterator() : Iterator

Aggregate Client

+first()+next()+isDone()

Iterator

+createIterator() : Iterator

ConcreteAggregate

+first()+next()+isDone()

ConcreteIterator

1 1 1 1

1 1

«instantiate»

Page 236: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Observer Example

+attach(in o : Observer)+detach(in o : Observer)+notify()

Subject

+update()

Observer

1 -observer*

-subject

1 1

+getData() : float

-data[] : float

StockMarket

+update()+print(in data[])

TextArea

+update()+draw(in data[])

BarChart

for all observers observer.update()

data = subject.getData()print(data)

data = subject.getData()draw(data)

Page 237: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Observer Design Pattern

+attach(in o : Observer)+detach(in o : Observer)+notify()

Subject

+update()

Observer

1 -observer*

-subject

1 1

+getState()

ConcreteSubject

+update()

ConcreteObserver

for all observers observer.update()

subject.getState()

Page 238: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

State Example

+open()+close()+acknowledge()

TCPConnection

+open()+close()+acknowledge()

TCPState

+open()+close()+acknowledge()

TCPEstablished

+open()+close()+acknowledge()

TCPListen

+open()+close()+acknowledge()

TCPClosed

1

-state

1

state.open()

Page 239: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

State Design Pattern

+request()

Context

+handle()

State

+handle()

ConcreteState1

+handle()

ConcreteState2

1

-state

1

state.handle()

Page 240: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Strategy Example

+format()

Document

+align()

Alignment

+align()

Left

+align()

Center

+align()

Justify

1

-alignment

1

alignment.align()

Page 241: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Strategy Design Pattern

+execute()

Context

+algorithm()

Strategy

+algorithm()

ConcreteStrategy1

+algorithm()

ConcreteStrategy2

1

-strategy

1

strategy.algorithm()

Page 242: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Interpreter example

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

Page 243: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Interpreter design pattern

Page 244: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Visitor example

Page 245: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Visitor design pattern

Page 246: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Mediator example

Page 247: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Mediator design pattern

Page 248: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Memento design pattern

Page 249: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Template method example

Page 250: Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava jan@kozusznik.cz

Template method design pattern