Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Methods for Software Specification Jan Kožusznik. Dept. of Computer Science Technical University of Ostrava"— Presentation transcript:

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

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

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

4 Software development „reality“

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

6 Software process – key disciplines

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

8 Requirements Requirement is 1.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.

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

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

11 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

12 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

13 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

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

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

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

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

18 Creation of textual requirement I Specific thoughts Thoughts generalization distortion T o g s h u t deletion oug

19 Creation of textual requirement II Specific thoughts Thoughts generalization distortion T o g s h u t deletion oug

20 Creation of textual requirement III Specific thoughts Thoughts generalization distortion T o g s h u t deletion oug

21 Use cases Benefits: –goal identification, –exceptional situation. Use case is specification of a sequence of actions, including variants that a system (or other entity) can perform, interacting with actors of the system.

22 Requirements and use cases They are really requirements Cover only a part of requirements – it lacks: –External interface, –Data format –Business rules, –Complex formulae. Cover one third of all requirements.

23 Use case structure Scope: Level: Primary Actor: Stakeholders & Interests: Precondition: Minimal Guarantees: Success Guarantees:

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

25 Design scope I Design scope is the extent of the system

26 Design scope II "Enterprise" scope "System" scope "Subsystem" scope

27 Design scope III "Enterprise" scope "System" scope "Subsystem" scope

28 Design scope IV Design scope is the extent of the system "Enterprise" scope "System" scope "Subsystem" scope

29 THREE NAMED GOAL LEVELS

30 THREE NAMED GOAL LEVELS II

31 THREE NAMED GOAL LEVELS III

32 THREE NAMED GOAL LEVELS IV

33 Use case structure I Context of use: Scope: Level: Primary Actor: Stakeholders & Interests: Precondition: Trigger: Minimal Guarantees: Success Guarantees:

34 Use case structure II Context of use: Scope: Level: Primary Actor: Stakeholders & Interests: Precondition: Trigger: Minimal Guarantees: Success Guarantees:

35 Use case structure III Context of use: Scope: Level: Primary Actor: Stakeholders & Interests: Precondition: Trigger: Minimal Guarantees: Success Guarantees:

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

37 Scenarios and steps II Main success scenario Common surrounding structure –condition of scenario –goal to achieve –set of action steps –end condition, –possible set of extensions. The scenario body –an interaction between two actors, –a validation step to protect an interest of a stakeholder, –an internal change to satisfy a stakeholder.

38 Scenarios and steps III Main success scenario Common surrounding structure –Condition of scenario –a goal to achieve –a set of action steps –an end condition, –a possible set of extensions. Scenario body –interaction between two actors, –validation step to protect interest of the stakeholder, –internal change to satisfy the stakeholder.

39 Different level of goals and precondition The use case on the summary level gives context for use-cases on lower levels. The precondition indicates the use- case performed previously.

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

41 Action Steps – guidelines 2: It shows clearly, "Who has the ball“. At each step one actor "has the ball". That actor is going to be the subject of the sentence, the first actor named, probably as the first or second word in the sentence. The "ball" is the message and data that gets passed from actor to actor.

42 Action Steps – guidelines 3: It is written from a bird's eye point of view. Beginning use case writers write the scenario as seen by the system: –Get an ATM card and PIN number. Deduct the amount from the account balance. X A better form is: –The customer inserts the ATM card and PIN. –The system deducts the amount from the account balance. v

43 Action Steps - guideline 4: It shows the process moving distinctly forward Avoid small steps – find a slightly higher-level goal for a step, ask "Why is the actor doing that?“. Example: A user hits the tab key. Why is the user hitting the tab key? To get to the address field. Why is he trying to get to the address field? Because he has to enter her name and address before the system does anything. A user enters name and address.

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

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

46 Action Steps – guidelines 7: It doesn’t "check whether", it "validates“ Verifying step is often written as “System … checks” it is not a good action verb because it does not move process distinctly forward – it is followed by “If the (condition) … ” 2. The system checks whether the password is correct 3. If it is, the system presents available actions to the user. 2. The system checks whether the password is correct 3. 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.

47 Action Steps – guidelines 8: It optionally mentions the timing Feel free to put in the timing, but only when you need to. –At any time between steps 3 and 5, the user will... –As soon as the user has..., the system will...

48 Action Steps – guidelines 9: Idiom: "User has System A, kick System B“ The user hits the FETCH button, at which time the system fetches the data from system B. 4. The user signals to the system to fetch data from system B. 5. The system fetches the background data from system B." 4. The user has system A, fetch data from system B.

49 Action Steps – guidelines 10: Idiom: "Do steps x-y until condition" only one step being repeated "The user selects one or more products." "The user searches through various product catalogs until he finds the one he wants to use.„ 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

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

51 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

52 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 The system goes through the document, checking every word against its spelling dictionary. 4. The system detects a spelling mistake, highlights the word and presents a choice of alternatives to the user. 5. The user selects one of the choices for replacement. The system replaces the highlighted word with the user’s replacement choice.... Extensions; 4a. The system detects no more misspellings through the end of the document: 4a1. The system notifies the user, terminates use case. 5a. The user elects to keep the original spelling: 5a1. The system leaves the word alone and continues. 5b. The user types in a new spelling, not on the list: 5b1. The system revalidates the new spelling, returns to step 3.

53 Extensions Conditions condition under which the system takes different behavior. say extension instead of failure or exception 4. The user has the system save the work so far.... Extensions; 4a. System auto detects the need for an intermediate save: 4a b. Save fails: 4b1....

54 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

55 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

56 Action Steps – guidelines 11: The condition says what was detected. Write down what the system detects, not just what happened. put a colon (’:’) after the condition Customer forgets PIN. PIN entry time-out. Invalid PIN: Network is down: The customer walked away (time-out): Cash did not eject properly:

57 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 The user has PAF save the work 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...

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

59 Failures within failures Extensions 6a. The clerk decides to exit without completing minimum information: 6a1. The system warns the Clerk it cannot exit and finalize the form without date, name or policy number, or adjuster name provided. 6a1a. The clerk chooses to continue entering loss 6a1b. The clerk saves as "intermediate" report and exits. 6a1c. The clerk insists on exiting without entering minimum information: The system discards any intermediate saved versions and exits.

60 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

61 Technology & Data Variations It is not extensions – it is rather specialization Main Success Scenario: 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.

62 Linking Use Cases I Sub use cases Extension use cases The user saves the report The user saves the report (UC 35 Save a Report)

63 Linking Use Cases II Sub use cases Extension use cases –There is a main activity which can be interrupted. –It can be interrupted in a number of ways, without the main activity being in control of the interruptions.

64 Many asynchronous or interrupting services. Adding to locked requirement document. When to use extension use case

65 When are we done? You have named all the primary actors and all the user goals with respect to the system. You can capture every trigger condition to the system either as a use case trigger or an extension condition. You have written all the user-goal use cases, along with the summary and subfunction use cases needed to support them. Each use case is clearly enough written that: –the sponsors agree they will be able to tell whether or not it is actually delivered. –the users agree that it is what they want or can accept as system’s behavior. –the developers agree they can actually develop that functionality. The sponsors agree that the use case set covers all they want (for now).

66 Special use cases: CRUD

67 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:

68 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:

69 MISSING REQUIREMENTS UC is only „third chapter of SRS“ – it doesn’t contain – –contain performance requirements, –business rules, –user interface design, –data descriptions, –finite state machine behavior, –priority, etc. Could be attached: –use case priority, –expected frequency of occurrence, –performance needs, –delivery date, –list of secondary actors, –business rules (possibly), –open issues. Additional table: –primary actor –trigger –delivery priority –estimated complexity –probable release –performance requirement –state of completion –...and whatever else you need.

70 Data requirements Required by programmers – includes field check Three level of precision: –Information nicknames, –Field lists, or data descriptions, –Field details & checks. Information nicknames will: –speed up the requirement gathering –make use cases shorter and easier to read –make use case more durable –Enable to refer the same information to other use cases.

71 Data requirements: information nicknames only a nickname is used in UC, it will enable –speed up the requirement gathering, –make use cases shorter and easier to read, –make use case more durable –enable to refer the same information to other use cases.

72 Data requirements: field list describes what fields information links contain. many strategies for dealing with this level of precision: –a separate entry for each entry –a single entry for a parcel of information that arrives in a single UC step together (name, address, phone number)

73 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

74 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

75 Use Cases In Project Organization: Use cases cross releases A complete use case is delivered in one release very occasionally. More often: –Deliver the simple case in release 1 –Add high-risk handling in release 2 –Put preferred customer handling in release 3 Deliver complete scenario.

76 Use cases to design - I Design doesn’t cluster by use case – parts of business logic or mechanism occur in several use cases. During OO design - don’t mirror functional decomposition by classes.

77 Use cases to design - II Design makes use of scenarios Use cases name domain concepts

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

79 UML Limitations: Example

80 Correct Interpretation of Model

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

82 OCL – Object Constraint Language OCL is 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.

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

84 OCL Expressions context Payment inv: self.items->forAll (item | item.buyer = payer) context Customer inv: Customer::allInstances()->isUnique(e- mail) context Payment inv: 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 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.

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

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

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

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

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

90 Invariants Invariants on attributes context Product inv ofPrice: self.price >= 0 Invariants on associated objects context Payment inv ofAge: payer.age >= 18 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.

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

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

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

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

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

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

97 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 Customer inv minServices: self.cards->size() > 1 implies self.programs->size() > 1

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

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

100 Iterator Variables context Customer inv: Customer::allInstances()->isUnique( ) or context Customer inv: Customer::allInstances()->isUnique(c | c. ) or context Customer inv: Customer::allInstances()->isUnique(c:Customer | c. ) 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.

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

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

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

104 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 =

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

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

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

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

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

110 Roots of UML OMT Object Modeling Technique J. Rumbaugh OMT Object Modeling Technique J. Rumbaugh Booch Method... G. Booch Booch Method... G. Booch OOSE Object-oriented Software Engineering I. Jacobson OOSE Object-oriented Software Engineering I. Jacobson UML Unified Modeling Language Rational UML Unified Modeling Language Rational Standardized by OMG

111 UML using Three modes: –as a sketch –as a Blueprint –as a programing language. Two directions: –forward engineering –reverse engineering

112 UML as a sketch most common its essence is selectivity forward sketching – to discuss some issue in code, to help to communicate reverse sketching – to explain working of some parts of a system

113 UML as a blueprint its essence is completeness forward sketching – detailed design sufficiently complete for coding up reverse sketching – shows every detail about the selected part of a system

114 UML as a blueprint II. requires more sophisticated tools than sketches reasonable for interfaces Value of reverse-engineering depends on tools –Dynamics browser is valuable –Generating large documents is worthless

115 UML as a programming language I another level of code generation requires sophisticated tools environment should provide better productivity requires a mass of users

116 UML as a programming language II another level of code generation requires sophisticated tools environment should provide better productivity requires a mass of users

117 UML diagrams UML2

118 UML meaning Precise definition of language Not a formal definition of mapping into the source code Development teams follow their local convention UML Is Not Enough

119 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

120 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

121 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

122 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

123 Documentation –only for highlighting most important parts understanding Legacy Code UML in a software process – maintenance

124 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

125 majority of UML diagrams types(classes) of object and various kind of static relations among them constraints feature – operation and properties Class diagrams

126 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:

127 structural features of a class attributes: Class diagrams – properties II association shows much similar information to attributes:

128 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

129 a pair of properties that are linked together as inverse. Bidirectional Associations label association by using a verb phrase.

130 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

131 Obvious inheritance substatiability –Subtyping –subclassing Generalization

132 can appear in any kind of diagram Notes and Comments

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

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

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

136 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

137 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

138 The most common interaction diagram in UML Single scenario – objects, messages Sequence diagrams

139 Explicit deletion in gc environment is also available – it indicates that it is no longer needed Sequence diagrams : Creating and deleting participants

140 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.confirm end procedure

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

142 Synchronous message Asynchronous message Sequence diagrams: Synchronous and Asynchronous Calls

143 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

144 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

145 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

146 It allows you to add: attributes, operations, and other features to associations Class Diagrams - Advanced Concepts: Association Class

147 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 { void insert (T newElement); void remove (T anElement);

148 Shows a fixed set of values having only their symbolic values, > keyword Class Diagrams - Advanced Concepts: Enumerations

149 It has instance executing its own thread of control Class Diagrams - Advanced Concepts: Active class

150 You can tag every feature with: –+ … public –- … private –# … protected –~ …package their meaning dependents base on a used programming language

151 Class Diagrams - Advanced Concepts: Responsibilities

152 Class Diagrams - Advanced Concepts: Static Operations and Attributes

153 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

154 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

155 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

156 Class without any implementation – directly corresponds to JAVA, C# Label «interface» Two kinds of relation with classes: –Implements –Requires Class Diagrams - Advanced Concepts: Interfaces

157 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

158 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

159  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

160 Equivalent to associative array, maps, hashes, and dictionaries Class Diagrams - Advanced Concepts: Qualified Associations

161 a snapshot of a system at a specific time elements are underlined useful for showing examples of objects connected together Object diagrams

162 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

163 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

164 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

165 One package contains a class implementing interface from another package. Implementing Packages

166 Shows system’s physical layout Shows communication paths and connected nodes Useful in showing what is deployed where. Deployment Diagrams

167 It is not mandatory – instead, diagrams concentrate on the textual content Graphical table of use cases Use Case diagrams

168 Based on a finite automaton Lifetime behavior of a single object Shows only what the object directly observes or activates State Machine Diagram

169 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

170 States when objects do something Marked with do/ Can be interrupted State Machine Diagrams – Activity states

171 Often several states share common transitions and internal activities – shared behavior into a superstate State Machine Diagrams – Superstates

172 States can be broken down into several orthogonal state diagrams that run concurrently History pseudostate restores the last state State Machine Diagrams – Concurrent states

173 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

174 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

175 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

176 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

177 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

178 Work flow and process modeling Representation of behavioral logic Description of use case Activity diagrams - when to use

179 Activity diagrams – partitions

180 Actions can also respond to signals. Activity diagrams – signals

181 Sending a signal is also supported – communication with external process Activity diagrams – sending and receiving signals

182 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

183 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

184 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

185 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

186 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

187 Join specification – another involved rule attached to a join Activity diagrams – join specification

188 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

189 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

190 Legal numbering style should be nested It resolves ambiguity with self- calls Many people prefer a flat numbering scheme – simpler Communication diagrams - decimal numbering

191 Sequence diagrams are more common Personal preference Easier to draw on a white board – good for exploring alternatives Communication diagrams - when to use

192 Hierarchically decompose a class into an internal structure Allow to take a complex object and break it down into parts Composite structures

193 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

194 Show runtime grouping (packages are compile time grouping) Similar to a component Composite structures – when to use

195 Annotated class in UML 2.0 – no additional syntax Component diagram

196 Component diagram – example

197 Beware of overly fine-grained components – hard to manage. Components and their interrelationship through interfaces. Component diagram – when to use

198 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

199 Collaboration occurrence

200 Activity and sequence diagram together Interaction Overview Diagrams

201 Inspiration from electrical engineering States as a line vs. states as an area Timing Diagrams

202 Design Patterns The design pattern concept can be viewed as an abstraction of imitating useful parts of other software products. The design pattern is a description of communicating objects and classes that are customized to solve a general design problem in a particular context.

203 Pattern name Problem Solution Consequences General structure of design patterns

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

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

206 Classification of Design Patterns Creational patterns defer some part of object creation to a subclass or another object. Structural patterns compose classes or objects. Behavioral patterns describe algorithms or cooperation of objects.

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

208 Factory Method Example

209 Factory Method Design Pattern

210 Abstract Factory Example

211 Abstract Factory Design Pattern

212 Prototype Example

213 Prototype Design Pattern

214 Builder example

215 Builder design pattern

216 Singleton design pattern

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

218 Composite Example

219 Composite Design Pattern

220 Adapter Example

221 Adapter Design Pattern

222 Decorator Example

223 Decorator Design Pattern

224 Proxy Example

225 Proxy Design Pattern

226 Facade design pattern

227 Flyweight example

228 Flyweight design pattern

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

230 Chain of Responsibility Example

231 Chain of Responsibility Design Pattern

232 Command Example

233 Command Desing Pattern

234 Iterator Example

235 Iterator Design Pattern

236 Observer Example

237 Observer Design Pattern

238 State Example

239 State Design Pattern

240 Strategy Example

241 Strategy Design Pattern

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

243 Interpreter design pattern

244 Visitor example

245 Visitor design pattern

246 Mediator example

247 Mediator design pattern

248 Memento design pattern

249 Template method example

250 Template method design pattern


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

Similar presentations


Ads by Google