Vous êtes sur la page 1sur 74

Software Engineering Problems and Solutions; A Student's Review Booklet

Dr. Constantinos Constantinides Department of Computer Science and Software Engineering Concordia University

This is a collection of problems and solutions which I have used in assignments and examinations over the years of teaching Software Engineering and related courses in a number of different institutions. The marking scheme and guidelines were left as is. This collection can make a good review guide. Thanks to Venera Arnaoudova and Guillaume Theoret for reviewing and proof reading this booklet. Dr. Constantinos Constantinides, Concordia University, September 2006.

QUESTION 1 Consider a conference room reservation system that is used by a college facility. The system maintains a directory of rooms and a book that includes all reservations. Each room may be reserved at a number of time slots. UC1: Make Reservation (success scenario): A client accesses the system in order to make one or more reservations on a given room and time slot. The client has to enter his name and a short description of the reservation (e.g. seminar, lecture, etc.). The system will place the reservation in a reservations book and it will respond with a confirmation message. At the end of the session, the system will display an informative message. UC1: View Reservations (success scenario): A client accesses the system in order to view all reservations. The system responds with a list of reservations. (a) Create a domain model for the conference room system. (5)

(b) Create a system sequence diagram (SSD) with respect to the first scenario (Make Reservation). (2) (c) Create a set of operation contracts for the SSD of Make Reservation. Clearly illustrate the relationships between the operation contract and the domain model. (9) (d) Create interaction diagrams for the operation contracts of (c), clearly illustrating the deployment of all applicable responsibility paterns. (9)

Solution: (a) The domain model is shown below:

(b) The SSD is shown below:

(7)

:Client

:ConferenceRoom ReservationSystem

loop makeReservation (roomNumber, holder, description, timeSlot) Confirmation, reservation number

(c) Contracts are shown below: Contract CO1: MakeNewReservation Operation: MakeNewReservation() Cross References: Use Case Make Reservation. Pre-conditions: Clerk has been authenticated by the system. Post-conditions: A MakeReservationSession instance mrs was created. (instance creation) mrs was associated with Terminal (association formed) mrs was associated with Directory (association formed) Contract CO2: addReservation Operation: addReservation() Cross References: Use Case Make Reservation. Pre-conditions: Reservation session is under way. Post-conditions: A Reservation instance r was created. (instance creation) r was associated with Directory (association formed) r was associated with ReservationsBook (association formed) Contract CO3: endReservation Operation: makeNewEnrollment () Cross References: Use Case Make Reservation. Pre-conditions: Reservation session is under way. Post-conditions: Attribute isComplete of mrs was set to true (modification of attribute)

QUESTION 2 (a) Define and distinguish between the terms responsibility and method. (2) (b) Describe the term responsibility pattern. (3)

(c) Consider the domain model below. A clerk would enter a student id to the system to request the calculation of a students Grade Point Average (GPA). The GPA is calculated as follows: To find out your grade points for a class you have taken, multiply your grade by the credit hours assigned to the course. Say you took English, which weights three credits, and you earned a 2 in the course. Just multiply 2 (your mark) x 3 (credit hours) = 6. So, for this class, you have six grade points. Once you have figured out your grade points you can compute the average. You arrive at an average by first adding a group of numbers and then dividing one total by another. Since your task is to compute your grade point average, you need to total your grade points. Next divide the total grade points by the total credits attempted. (c) Explain what is wrong with the domain model, and do any modifications necessary. (5) Which is the appropriate responsibility pattern to deploy in order to calculate a students GPA? Utilize this pattern in order to answer this question and comment on the notion of partial responsibilities where applicable. (15)

Solution: (a) Responsibilities are related to the obligations of an object in terms of its behavior. A responsibility is not the same thing as a method, but methods are implemented to fulfill responsibilities. Methods either act alone, or collaborate with other methods and objects. (b) A (responsibility) pattern is a named description of a problem and a solution that can be applied to new contexts; it provides advice in how to apply it in varying circumstances. (c) Reduntant information in class Class. Attributes (description, credits and id are the same for all instances). Need to provide specification.

(d) To calculate the GPA we deploy the Expert pattern. The semantics of the Expert patern are as follows: Problem: what is a general principle of assigning responsibilities to objects? Solution: Assign a responsibility to the information expert - the class that has the information necessary to fulfill the responsibility.

It is necessary to know about all the Class instances of an Enrollment and the sum of the credit points. An Enrollment instance contains these, i.e. it is an information expert for this responsibility. What information is needed to determine the credit points? Credit and grade. Class should be able to determine the credit points. This means that Enrollment needs to send a getCreditPoint() message to each of the Class instances and sum the results. To fulfil the responsibility of knowing and answering its credit points, a Class needs to know about credit. The ClassSpecification is the information expert on answering its credit. To fulfil the responsibility of knowing and answering the Enrollments GPA, three responsibilities were assigned to three design classes. Partial responsibilities are assigned as follows: Class Responsibility Enrollment Knows GPA Class Knows credit points ClassSpecification Knows credit

QUESTION 3 Consider the interaction diagram below:

(a) Provide skeletal code listings for any appropriate classes in order to discuss all applicable types of visibility. For each type, describe its temporal properties. (15) (b) Create a class diagram from the interaction diagran above, clearly illustrating all applicable elements. (10)

10

Solution: (a) Consider the diagrams below: There is attribute visibility from Server to MyList. This is a permanent visibility; it persists as long as both Server and MyList exist.

There is parameter visibility from Server to Spec; This is a relatively temporary form of visibility; it persists within the scope of method doIt(). There is also a parameter visibility from Transaction to Spec. It persists only within the scope of method produce().

There is parameter visibility from Item to Spec; It can transform into attribute we shown:

11

(b) The class diagram is shown below:

12

QUESTION 4 Consider an email client software. The client has one mailbox which consists of a number of diferent folder. Each folder contains a number of messages. A message cannot exist in more than one folders. A user can invoke a view on a message and in fact a user may have various views, each corresponding to one message. (a) Illustrate the appropriate mechanisms in order to identify concepts and their associations. (5) (b) Create a domain model for the email client. (13)

(c) Define the term multiplicity expression and show its applicability on the domain model. (2) (d) Define the term aggregation (and its different types) and clearly illustrate its applicability to the domain model. (5)

13

Solution: (a) Domain model 1. Noun-phrase identification: Mailbox, Folder, Message, View (1) 2. Conceptual class category list: Containers of other things: Mailbox, Folder (2) 3. Common associations list: (2) A logical part of B: (Mailbox, Folder), (Message, Folder) A is a description of B: (View, Message) A is captured in B: (View Message) (b) The domain model is shows below:

Marking scheme: 4 conceptual classes: 4 3 associations: 3 2 aggregations: 2 2 notes (0.5 each): 1 3 sets of multiplicity expr: 3 Total:13 (c) The following is defined as follows: Multiplicity: How many instances of one type may be associated with an instance of another type at one point in time. (2) Mailbox Folder: one-to-many, Folder-Message: many-to-many, Message-View: many-to-many

(d) The following terms are defined as follows: Aggregation: defines a whole-part association. (1) Composite aggregation: multiplicity at composite end is 1. Mailbox-Folder (2) Shared aggregation: Multiplicity at composite end is more than one.

14

Folder-Message

(2)

15

QUESTION 5 Given the UML interaction diagrams below, create a UML class diagram.

16

Solution:

Marking scheme: aggregation association: 2 Multiplicity in above: 1 5 other associations: 5 LogSession class: 4 Terminal class: 4 Registered class: 3 PostSession and Queue (2 each): 4 NewsItem, User (1 each) 2 Total:25

17

QUESTION 6 Our system is the Registrar office of a University where students go in order to enrol for classes. Consider the following success scenario of use case Process Registration: A student arrives at the Registrars office in order to enroll in one or more classes. The clerk will access the terminal in order to initiate a new enrollment session (you may assume that they already have been authenticated by the system). Each enrollment session captures the date and time it was initiated. The clerk will proceed to enroll the student in each class requested. For each class, the clerk will enter the student name and identification number and the class identification number. In response to each entry, the system will display a description and a confirmation. At the end of the session, the system will display a confirmation of the procedure and the total amount of tuition fees due. The clerk will then initiate a payment of tuition fees and the system will respond with the change due and a receipt. (a) Create a domain model based on the above scenario. (5)

(b) Describe what a system sequence diagram (SSD) is and create one with respect to the above scenario. Use the SSD to define the terms system event and system operation and public system interface. (10) (c) Define the terms operation contract, precondition, and postcondition, and create an operation contract for the system operation deployed to initiate the enrollment session. Clearly illustrate the relationships between the operation contract and the domain model. (10)

18

Solution: (a) The domain model is shown below: (5)

(b) An SSD is a diagram that shows, for a particular scenario of a use case, the interactions between an actor the the system as a black box. (1.5) The SSD is shown below: (7)

19

The following terms are defined as follows:

(1.5)

1. System event: message (request) generated by actrors to system. 2. System operation: Operations that the system (as a black box) offers in its public interface to handle incoming system events. 3. Public system interface: the entire set of system operations across all use cases.

(c) The following terms are defined as follows:

(4)

1. Operation contract: document that describes system behavior. 2. Precondition:Assumption about the state of the system before execution of the operation. 3. Postcondition: Assumption that refer to the state of the system after completion of the operation. (creation/deletion of instances, formation/bgreaking of associations, modification of attribute) The operation contract for makeNewEnrollment is as follows: (6)

Contract CO1: makeNewEnrollment Operation: makeNewEnrollment () Cross References: Use Cases: Process Enrollment. Pre-conditions: Clerk has been authenticated by the system. Post-conditions: An Enrollment instance e was created. (instance creation) e was associated with Terminal (association formed) e was associated with Student (association formed) Attributes of e were initialized (modification of attribute)

20

QUESTION 7 (a) Explain what is meant by the concept of a role. (1)

(b) Define the term navigability and dependency relationship and describe situations suggesting a need to define them in UML. (2) (c) Use the diagram below to create an appropriate UML artifact that illustrates software components (together with state and behavior where applicable) and how they relate, and clearly identify any navigability and dependency relationships. (7)

addLineItem(id, qty)

:Register

2 : makeLineItem(spec, qty)

1:spec := getSpecification(id)

:Sale

:ProductCatalog 2.2 : add(sl) 1.1:spec := find(id) 2.1 : create(spec, qty)

:ProductSpecification

:SalesLineItem

sl:SalesLineItem

21

Solution: (a) Each end of an association in a UML Domain Model or a Class Diagram is a role, which has various properties such as name, and multiplicity. The role name identifies an end of an association and ideally describes the role played by objects in the association. (1) (b) Navigability is a property of the role implying attribute visibility of the source to target class. Here are common situations suggesting a need to define an association with navigability from A to B: 1. A sends a message to B. 2. A creates an instance of B. 3. A needs to maintain a connection to B (1) Dependency relationship on the other hand is a property of a role indicating non-attribute visibility. (1) (c) Consider the class diagram below: (7)

ProductCatalog Looks-in Contains vector specs; getSpecification() 1

ProductSpecification

1 Describes 1 Register Captures 1 addLineItem() 1 Sale vector lineItems; makeLineItem() 1 Contains * SalesLineItem

SalesLineItem to ProductSpecification: can be illustrated either by navigability or dependency relationship depending on whether parameter spec is saved in an attribute or not.

Navigability is illustrated with arrow over associations. Dependency relationship is illustrated with dotted arrow.

22

QUESTION 8 (a) (b) (c) (d) Compare the notion of design pattern to responsibility pattern. What are the advantages of design patterns? (1) Describe the Observer design pattern. (1) Illustrate your answer in (c) with UML diagrams to show: Interactions, and (8) The static structure of the system. (6) (e) Describe the advantages provided by the Observer design pattern. Solution: (a) A pattern is a documentation of specific reoccurring problems (and solutions). Responsibility patterns refer to choices in where to assign object responsibilities and they are commonly considered during the creation of interaction diagrams. Design patterns, on the other hand, are abstractions of common design occurrences. (2) (b) Advantages of design patterns are: (1) No need to solve every problem from first principles, but basing new designs on prior experience. Avoids (or minimizes) re-design. Improve the documentation and maintenance of existing systems. (c) The Observer design pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. More specifically, a model (subject) maintains some data values (state). A number of views (observers) can attach themselves to represent the state of the model in various ways. Whenever the models data changes, the model notifies views that depend on it. In response, each view gets an opportunity to update itself. (1) (2)

(2)

23

(d) The following UML diagrams describe the semantics of the Observer design pattern. 1. Interaction diagram 1: (4)

:Subject

Obs1: Observer

Obs2:Observer

attach(this)

attach(this)

2. Interaction diagram 2:

(4)

:Subject setState()

Obs1: Observer

Obs2: Observer

sendNotification()

update() getState() update() getState()

24

3. Class diagram.

(6)

<<interface>> SubjectIF attach(Observer) detach(Observer) sendNotification() 1 *

<<interface>> ObserverIF update()

Subject getState() setState() subjectState

Observer

observerState

(e) The following advantages can be identified: (2) Developers can attach multiple views to a model to provide different presentations. Can create new views for a model without rewriting it. Reflects a design that decouples views from models.

25

QUESTION 9 Consider a consulting company with a number of employees (consultants). The company offers a number of services (jobs) to clients. Each job is paid for according to some fixed rate (may be different for each job type), for example SQL tutorial, rate: $200 per hour. Consultants may undertake a number of jobs a day, each over different periods of time. At the end of each job, a consultant would enter their name and identification number into a computer system, the start and end time they worked on the job, the job description and identification number, and the date. For example:
john smith; JS001; 08:30; 10:00; SQL tutorial; SQLTUT, 27-3-04

At the end of each week the system calculates a payment for each employee based on the total number of jobs undertaken by each one during that time. In order to maintain company expences, the system keeps a 5% of the grand total of senior consultants, and a 20% of that of a junior consultant. (a) Create a domain model based on the above specification that contains only what is applicable to the payment subsystem. (3) (b) Create a UML interaction diagram to capture the creation of all weekly payments. Identify all applicable responsibilities. (4) (c) Create a UML class diagram for the subsystem responsible to create payments. (3)

26

Solution: (a) The domain model is shown below:

(b) The UML interaction diagram is shown below:

The following are partial experts: Consultant Knows its total and rank Job Knows its hours JobSpecification Knows its rate

27

(c) The UML class diagram is shown below:

28

QUESTION 10 (a) Define the term responsibility and describe its two different types. (b) How are responsibilities related to methods? (1) (1) (3)

(c) In which context during development, are responsibilities considered?

(d) Consider the domain model of a rental system like the one used in a video store, where customers approach the register with items to rent. At the end of the rental, the clerk must initiate a payment by entering some amount. Create a domain model and provide a rationale on who should be the prime candidate to create payments. Comment on the notions of cohesion and coupling based on your model. (2) (e) Provide two alternative designs (in the form of interaction diagrams) in order to create a payment, and comment on the assignment of responsibilities to objects in the context of GRASP patterns. Clearly illustrate and describe any visibility relationships (including their types and their temporal properties). (8) (f) Define navigability and dependency relationship and describe the context where they are used during software development. (1) (g) Describe common situations where a navigability relationship is defined. (1) (h) Create an appropriate UML artifact in order to illustrate visibility relationships for the system that poses the lower level of coupling in (e). (3)

29

Solution: (a) Responsibilities are related to the obligations of an object in terms of its behavior. Two types of responsibilities: 1. Doing: a. Doing something itself (e.g. creating an object, doing a calculation) b. Initiating action in other objects. c. Controlling and coordinating activities in other objects. 2. Knowing: a. Knowing about private encapsulated data. b. Knowing about related objects. c. Knowing about things it can derive or calculate. (b) A responsibility is not the same thing as a method, but methods are implemented to fulfill responsibilities. Methods either act alone, or collaborate with other methods and objects. (c) Within the UML artifacts, a common context where these responsibilities (implemented as methods) are considered is during the creation of interaction diagrams. (d) The domain model is shown below:

Terminal would be a prime candidate according to the Creator pattern (it has all initializing data). However, this would create unecessary coupling between Terminal and Payment, and a lower level of cohesion in Terminal. (e) For the figures below: 1. Figure 1: Higher level of coupling. It also poses a low level of cohesion for the Terminal class. Visibility between Terminal and Payment (attribute) and between Rental and Payment (parameter, or possibly a transformation from parameter to attribute). Attribute visibility is permanent, parameter visibility is bound within a method scope.

30

2. Figure 2: Lower level of coupling, higher level of cohesion. Visibility between Terminal and Rental (attribute, permanent visibility).

(f) Navigability is a property of the role implying visibility of the source to target class. Attribute visibility is implied. Add dependency relationship lines to indicate non-attribute visibility. The above is used during the creation of a class diagram. (g) Common situations suggesting a need to define an association with navigability from A to B: A sends a message to B. A creates an instance of B. A needs to maintain a connection to B

31

(h) The UML class diagram is shown below:

32

QUESTION 11 Use cases Process Sale, Process Rental and Handle Returns are initiated by the cashier who is the principal actor. The cashier must first be authenticated by the system before being able to interact with the system. How would you model the Authenticate use case? Identify concrete/abstract use cases as well as base/addition use cases. Solution: None of the Process Sale, Process rental or Handle Returns need to perform authentication as part of their interactions. They all assume that authentication is successfull before they are invoked. So the include/extend relationship will not be applicable in this case. Use case Authenticate would have to be modelled as a standalone use case. All use cases in this example are concrete and base.

33

QUESTION 12 In the context of a domain model: 1. Define generalization. 2. How are entities that participate in generalization related? 3. Define 100% rule and is-a rule. 4. What would make a conceptual class abstract? Solution: 1. Generalization: The activity to identify commonalities between concepts and defining superclass (general concept) and subclass(-es) (specialized concepts). 2. Entities that participate in a generalization are related in terms of set membership: All members of a conceptual subclass set are members of their superclass set. 3. 100% rule: Subclass must fully conform to the attributes and associations of its superclass; is-a rule: A conceptual subclass should be a member of the set of the superclass. 4. If every member of a conceptual class must also be a member of a subclass (or a member of one of its subclasses), then the superclass is called an abstract conceptual class.

34

QUESTION 13 Express the way the following artifacts are related, using an appropriate UML notation: functional requirements, request event, domain model, operation contract, postcondition, use case, precondition, scenario, SSD, system operation, statechart, interaction diagram, class diagram. Solution:
FRs 1..* 1 expressed-as Statechart 1 1 expressed-as SSD 1 System operation defines-classes-and-state-for Domain model 1 expressed-as 1 Operation contract
preconditions postconditions

Request event 1 corresponds-to 1

Use case

Scenario

Class diagram Interaction diagram

defines-operations-for

35

QUESTION 14 [Example taken from M. Fowler, UML Distilled, 3rd ed.] Consider a controller for a secret panel in a Gothic castle: In this castle I want to keep my valuables in a safe that is hard to find. To reveal the lock to the safe I have to remove a strategic candle from its holder but this will reveal the lock only while the door is closed. Once I can see the lock, I can insert my key to open the safe. For extra safety, I make sure thst I can open the safe only if I replace the candle first. If a thief neglects this precaution I will unleash a nasty monster.

Solution on Fowler, page 108.

36

QUESTION 15 Model the following scenario as a UML activity diagram: A customer arrives at an ATM. They insert their card and then they enter their password. If the password is not accepted they have to re-enter it. If the password is accepted they select the type of transaction they wish to conduct and then they perform the transaction. Once the transaction is complete they have the option to select and perform more transactions, otherwise they get back their card and their interaction with the ATM terminates. Solution:

37

QUESTION 16 Provide brief definitions of the terms requirements validation and requirements verification and describe the stages at which these procedures take place. Solution: Requirements validation deals with the question on whether we are building the right product and it takes place during requirements analysis. Requirements verification deals with the question on whether we have built the product right and it takes place at the testing stage. QUESTION 17 In the literature it is claimed that for medium- to large-scale systems, a linear software development process is not realistic. Briefly explain what it meant by not realistic and describe two problems usually associated with the linear (waterfall) process model. Solution: As requirements tend to change, it is usually not feasible to fully complete and freeze the requirements specification, then fully complete the design, build and then test the software. Two associated problems with the linear model is 1) risks are not addressed early but can be encountered late in the development, and 2) lack of flexibility of changing requirements. QUESTION 18 In the literature we frequently read of iterative development. Provide a brief description what is meant by iteration and how does it relate to development. In your answer take into consideration the following: 1) the organization of development during an iterative process, 2) the relation between an iteration and the software system under development, and 3) the outcome of an iteration in terms of testing and integration. Solution: An iteration is a mini-project representing a complete development cycle. It includes its own treatment of requirements, analysis, design, implementation and testing activities. An iteration tackles new requirements (or revisits already implemented requirements) and incrementally extends the system. Development is organized into a series of (usually short and fixed-length) iterations. The system grows incrementaly over time, iteration by iteration. The outcome of an iteration is a tested, integrated and executable system.

38

QUESTION 19 List the phases of the linear model. Where do these phases get their names from? How does this model relate to the phases of the Unified Software Development Process (UP)? Solution: The names of the phases of the linear model are: Requirements, Analysis, Design, Implementation, and Testing. The names refer to the activities entailed in each phase. On the contrary, the phases of the UP contain all activities in various workloads. QUESTION 20 Briefly describe three advantages of an iterative process. Solution: Three advantages of an iterative process can be the following: 1. Risks are identified early. 2. Handle evolving requirements (through feedback and adaptation). 3. Attain early understanding of the system. QUESTION 21 Briefly describe what is meant by timeboxing and what is the motivation behind short iterations. Solution: Timeboxing is a term that refers to the fixed length of iterations. Long iterations increase project risk. On the other hand, short iteration lengths allow for rapid feedback and adaptation. QUESTION 22 How can use cases become an indicator of software quality? Solution: At a milestone (the end of an iteration) the executable can be demonstrated against the use case scenarios.

39

QUESTION 23 Briefly describe how each of the waterfall model, the spiral model and the unified software development process (UP) tackle risk. Solution: Each model works as follows: 1. The waterfall model does not explicitly tackle risk. 2. The spiral model includes a risk analysis stage (stage 2, after planning) which explicitly tackles risk before development. The model evaluates an iteration through customer evaluation (stage 5) and feedback (stage 6) to facilitate refinements in order to monitor and handle the risks. 3. The UP addresses critical use cases (those that capture high-risk and high-value requirements) during the Inception and Elaboration phases in order to minimize risk. QUESTION 24 Briefly describe the primary objectives of the Elaboration phase of the Unified Software Development process. In your answer take into consideration the outcome of the previous phase. Solution: The primary objectives of the Elaboration phase are: 1) to produce an executable core of the system and 2) to address the critical use cases identified in the Inception phase. QUESTION 25 Consider the Unified Software Development Process (UP). Briefly describe what is meant by the term artifacts of the process and describe the two dimensions over which we can view artifacts. What is the relation between artifacts and deliverables? Solution: The term artifact is used to describe the documentation of an activity. We have two dimensions of artifacts: 1) the set of artifacts (across all disciplines) over a single iteration, and 2) the set of artifacts of one discipline (activity) throughout the entire development (throughout all phases). A deliverable is a document that describes sets of artifacts by the end of an iteration.

40

QUESTION 26 Consider and comment on the following quote: During the Inception phase all requirements are defined. The purpose of the Elaboration phase is to produce a design of the system. Construction, as its name suggests, builds the system. Solution: The above quote misinterprets the Unified Process. The Inception phase defines the scope of the project, the Elaboration phase builds the core architecture of the system and the Construction phase builds the remaining features. Iterations in all phases contain work in most disciplines. QUESTION 27 Provide brief definitions for the two broad categories of requirements. In the context of the Unified Software Development Process (UP), briefly describe when requirements are captured, and which artifacts are used to capture them. Solution: Functional requirements deal with the observable behavior of the system. In the UP they can be captured in use case scenarios as these describe the interactions between end-users (actors) and the system. Nonfunctional requirements describe constraints and qualities of the system. NFRs are normally captured in the Use Case Model and in the Supplementary Specification. Both artifacts start during the preliminary iteration (of the Inception phase) and can be refined in subsequent iterations. QUESTION 28 Briefly explain what is meant by critical use cases within the context of the Unified Software Development Process (UP) and what is the motivation behind this notion. Solution: Critical use cases contain high-risk and high-value requirements and the UP addresses them during the Elaboration phase. The motivation is to drive down the risk of the entire development so that if the project is going to fail it will do so early, not late.

41

QUESTION 29 Consider the code below:


class MyClass { ... void calculate() { <XType> x = <expression>; <YType> y = <expression>; ... // task X -- begin // long computation ... x = <expression>; y = <expression>; ... // task X end // task Y -- begin // long computation ... x = <expression> <ZType> z = <expression that contains y> ... // task Y -- end } }

Task 1: Can you deploy Extract Method to refactor the code? To what degree is this possible and if not, what refactoring strategy can you deploy to improve the quality of the above code? Task 2: Illustrate how there is no difference in the overal (black-box) behavior of your program after the refactoring. Solution: Task 1: We would like to deploy Extract Method but this is not straightforward. If x,y of the same type, then we can pass them as arguments to a new method (e.g. task1()) which can then return an array of this type. The long method calculate() uses local variables in such a way that we cannot apply Extract Method. A better solution is to apply Replace Method with Object, so that calculate() turns into its own object and all local variables become fields of that class. Method calculate() can now be decomposed into other methods on the same object.
class Calculation { // instance variables <XType> x = <expression>; <YType> y = <expression>; task1() { ... x = <expression>; y = <expression>; } task2() {

42

... x = <expression> <ZType> z = <expression that contains y> } }

Task 2: Before:
MyClass c1 = new MyClass() c1.calculate()

After: Behavior is still the same, but implementation has changed:


MyClass c1 = new MyClass() c1.calculate() Class MyClass { ... calculate() { Calculation c = new Calculation(); c.task1(); c.task2(); } }

Some additional comments: 1. The question asks you to start with Extract Method. This is meant both as a requirement as well as to give you a hint. Ignoring this and starting with some other approach means that you are not addressing the question. 2. Addressing <expression> as a method is wrong, first because you are not starting with Extract Method refactoring and second because you may not assume that all instances of <expression> refer to the same expression. The two tasks make heavy usage (and modification) of both local variables. This is what the code tells you. 3. Moving local variables to fields is wrong first because you are not starting with Extract Method and second because this approach is based on the assumption that x, and y may obtain class scope. This assumption is wrong. Moving the two local variables outside the method breaks the concern of calculate(). 4. Performing Extract Method for task#2 only is partially correct but it will not solve the problem.

43

QUESTION 30 A spreadsheet can be represented by a number of views. Consider the following Java program.
class Spreadsheet { double state; double getState() { return state; } void setState(double value){ this.state = value; } class BarView { void update(){ double value = s.getState(); //... } BarView(Spreadsheet s) { this.s = s; } Spreadsheet s; } class HistoView { void display(){ double value = s.getState(); //... } HistoView(Spreadsheet s) { this.s = s; } Spreadsheet s; }

The system is initialized as follows:


Spreadsheet model = new Spreadsheet(); BarView view1 = new BarView(model); HistoView view2 = new HistoView(model);

Task 1: Update the spreadsheet and its view with value. Answer:
model.setState(value); view1.update(); view2.display();

44

Task 2: Reverse engineer the system, clearly illustrating state, behavior and visibility. Answer:

BarView

Spreadsheet state setState() getState()

HistoView

update()

display()

Task 3: Perform model transformation or otherwise engineer the model in order to implement the following two new requirements: 1. The views must automatically be updated every time the state of the spreadsheet changes. 2. Any class which wishes to act as a view must provide a well-defined interface. Answer:
<<interface>> SubjectIF attaches-to attach (); detach (); update(); update(); <<interface>> ObserverIF

Spreadsheet getState(); setState(); state; notifies-on-update

View display()

BarView

HistoView

45

Task 4: Forward engineer your design and map it to Java (skeletal) code. Answer:
public class Spreadsheet implements SubjectIF { public Spreadsheet () { observers = new Vector(0); } public void attach (ObserverIF observer){ observers.addElement(observer); System.out.println(observers.size()); } public void detach (ObserverIF observer) { observers.removeElement(observer); } public void update() { ObserverIF tempObserver; for (int i = 0; i < observers.size(); i++) { tempObserver = (ObserverIF)observers.elementAt(i); tempObserver.update(); } } public double getState() { return state; } public void setState(double state) { this.state = state; this.update(); } private Vector observers; private double state; } public class BarView extends View { protected void display() { double state = getState(); //... } } public class HistoView extends View { protected void display() { double state = getState(); //... } } public abstract class View implements ObserverIF { public View(Spreadsheet subject) { this.subject = subject; this.subject.attach(this); } public void update() { state = this.subject.getState(); display(); } protected double getState() { return state; } protected void abstract display(); private Spreadsheet subject; private double state; }

Task 5: Update spreadsheet and its views with value2. Answer:


model.setState(value2);

46

QUESTION 31 A system is used by an airline company to provide reservation services to its customers (frequent flyer account holders). The requirements and analysis activities of the system are illustrated by the following collection of artifacts:
CustomerCatalog 1..* Customer name accountNumber frequentFlyerMiles Booking customer flight date time is-included ReserveFlightSession Console captures

uses

Flight flightNumber source destination 1..* Contained-in FlightCatalog

Figure 1. Domain model Reserve Flight main (success) scenario: A customer accesses an on-line console maintained by an airline carrier in order to make a booking of one or possibly more flights. The system maintains a catalog of all flights supported by the carrier and presents this catalog to the customer. For each flight booking request, the system must display a confirmation. The customer must complete the session initiating the console to capture (save) all flights booked in a transaction record. Preconditions: 1. Customer has been authenticated from a database (customer catalog). Postconditions: 1. One(or more) bookings have been made on a given customer. 2. Frequent flyer miles information of customer has been updated.

47

:Customer

:System

initiateFlightReservation(customer, flightCatalog) flight catalog information: list of flight numbers, with source and destinations loop

The actor can navigate through the catalog to choose flights.

addFlight(flightNumber, date, time) confirmation

endFlightReservation() confirmation

Figure 2. System sequence diagram (SSD) of main scenario of Reserve Flight use-case. Contract CO1: initiateFlightReservation Preconditions: Customer has been authenticated. Postconditions: 1. An instance of ReserveFlightSession rfs was created. (instance creation) 2. Instance rfs was associated with Console. (formation of an association) 3. Instance rfs was associated with Customer. (formation of an association) 4. Instance of a Booking multiobject has been created and initialized (instance creation and attribute modification). Contract CO2: addFlight Preconditions: A flight reservation session is under way. Postconditions: 1. An instance of Booking booking was created. (instance creation) 2. Instance booking was associated with ReserveFlightSession. (formation of an association) 3. Customer.frequentFlyerMiles has been modified (attribute modification) Contract CO3: endFlightReservation Preconditions: A flight reservation session is under way. Postconditions: 1. ReserveFlightSession.isComplete was set to true. (modification of an attribute) NOTE: Attribute isComplete is not part of the domain model, but it will have to be added at this point. 48

a. (15 pts) For each system operation contract create a UML communication diagram, using comment boxes to indicate the deployment of all appropriate responsibility (GRASP) patterns. Answer:

By Controller

By Creator

:Booking

initiateFlightReservation(customer, catalog)

2: create() 1: create(customer)

:Console

:ReserveFlightSession

:Customer

49

:Customer By Controller 5. updateAccount() 2: makeNewFlight(flight, date, time) :ReserveFlight Session

addFlight(flightNumber, date, time) :Console

By Expert

1. getFlight(flightNumber)

4: add (booking)

By Expert

:FlightCatalog

:Booking By Creator

1.1 flight = find(flightNumber)

3: booking := create(flight, customer, date, time) :Booking

:Flight

By Controller

By Expert

endFlightReservation()

1: becomeComplete()

:Console

:ReserveFlight Session

50

b. (5 pts) Create a UML design class diagram based on the above figures, clearly illustrating state, behavior, multiplicity expressions, association names, navigability and dependency relationships.
CustomerCatalog 1..* Customer name accountNumber frequentFlyerMiles updateAccount() Booking

* is-included 1

Console initiateFlightReservation() addFlight() 1 endFlightReservation()

ReserveFlightSession isComplete: Boolean * makeNewFlight(Flight, Date,


Time) becomeComplete()

Flight FlightNumber source 1..* destination FlightCatalog Contained-in getFlight()

c. (5 pts) Create skeletal code listings in Java for classes Booking and ReserveFlightSession. In your code, place comments to indicate any visibility relationships.
public class Booking { Flight flight; Customer customer; Date dateTime; Booking(Flight flight, Customer customer, Date dateTime) { this.flight = flight; this.customer = customer; this.dateTime = dateTime; } } public class ReserveFlightSession { private Customer customer; private Vector bookings; private Boolean isComplete; ReserveFlightSession(Customer customer) { // form associations this.customer = customer; // create and initialize Booking multiobject this.bookings = new Vector(); } public void makeNewFlight(Flight flight, Date dateTime) { Booking booking = new Booking(flight, customer, dateTime); bookings.add(booking); } public void becomeComplete() { isComplete = true; } }

51

QUESTION 32 Task 1: The Observer design pattern supports a many-to-one dependency from a number of observer objects to one subject object where observers attach themselves to a subject. The main objective is for observers to maintain the same state as the subject. Upon a change of state, the subject must deploy a notification mechanism on its observers. The pattern can support two models of notification: 1. In the Pull model, upon a change of state in the subject, the subject activates a notification mechanism whereby it sends a message to all observers indicating that a change of state has occured. The observers will then explicitly request the details of the change. The following code illustrates the Pull model of the Observer design pattern:
public interface SubjectIF { public void attach (ObserverIF observer); public void detach (ObserverIF observer); public void update(); } public class Subject implements SubjectIF { public Subject () { observers = new Vector(0); } public void attach (ObserverIF observer){ observers.addElement(observer); } public void detach (ObserverIF observer) { observers.removeElement(observer); } public void update() { for (int i = 0; i < observers.size(); i++) { (ObserverIF)observers.elementAt(i).update(); } } public double getState() { return state; } public void setState(double state) { this.state = state; update(); } private Vector observers; private double state; } public interface ObserverIF { public void update(); }

public class Observer implements ObserverIF { public Observer(Subject subject) { this.subject = subject; this.subject.attach(this); } public void update() { double state = subject.getState(); //display state } private Subject subject; }

2. In the Push model, upon a change of state in the subject, the subject activates a notification mechanism whereby it sends its own state to all observers (whether they want it or not). Refactor the above code in order to support the Push model, showing only the modified parts of the class definitions. Solution:
public class Subject implements SubjectIF { ... public interface ObserverIF { public void update(double

52

public void update() { ObserverIF tempObserver; for (int i = 0; i < observers.size(); i++) { (ObserverIF)observers.elementAt(i).update(state); } } ... }

state); } public class Observer implements ObserverIF { ... public void update(double state) { this.state = state; display(); } ... private double state; }

Task 2: Reverse engineer the Push and Pull models into UML interaction diagrams. In your design, use one subject and two observers.

:Subject setState() update()

Obs1: Observer

Obs2: Observer

update() getState()

update() getState()

Figure. Notification mechanism in the Observer design pattern (Pull model)

:Subject setState() update()

Obs1:Observer

Obs2 :Observer

update(this.state)

update(this.state)

Figure. Notification mechanism in the Observer design pattern (Push model)

53

Task 3: Consider the figure below:


LibraryControl checkOutItem(Item) checkInItem(Item) addItem(Item) deleteItem(Item) printCatalog() sortCatalog() searchCatalog(Key k) editItem() lookUpItem() listCatalogs() doInventory() issueLibraryCard() archiveCatalogs() addMember(Member) deleteMember(Member) lookUpMember(Key) editMember(Member) Item title ISBN author publisher cost dateIn quantity

LibraryMember name userID itemsOut

Catalog

topic inventory

itemCatalog currentItem memberCatalog

Figure. Class diagram of a library information system 1. In no more than two lines for each, identify and describe three problems with the above design. 2. Perform model transformation to explicitly address the problems you identified above. Your solution should illustrate proper associations, multiplicity expressions and any aggregation relationships. Solution: 1. Problems: 1) This is not an object-oriented design, 2) Low cohesion of class LibraryControl as unrelated operations are encapsulated into this class, 2) High coupling of class LibraryControl as this class is associated with all other classes.

54

2. The restructured class diagram is shown below:


LibraryMember edit() LibraryControl checkOutItem(Item) checkInItem(Item) addItem(Item) deleteItem(Item) printCatalog() sortCatalog() searchCatalog(Key k) editItem() lookUpItem() listCatalogs() doInventory() issueLibraryCard() archiveCatalogs() addMember(Member) deleteMember(Member) lookUpMember(Key) editMember(Member) itemCatalog memberCatalog Item checkOutItem() checkInItem() edit() title ISBN author publisher cost dateIn state

name userID itemsOut

MemberCatalog addMember(Member) deleteMember(Member) editMember(Member) lookUpMember(Key) members

Catalog checkOutItem(Item) checkInItem(Item) editItem() addItem(Item) deleteItem(Item) printCatalog() sortCatalog() searchCatalog(Key k) lookUpItem() topic items

55

QUESTION 33 In the context of iterative development, describe the following concepts in no more than three lines for each: 1. Iteration (what are the objectives of an iteration? What is the outcome of an iteration? What is time-boxing?) 2. Critical use-cases. 3. Incremental development. 4. How does the Unified Software Development Process (UP) explicitly address critical use-cases? 5. What are functional and nonfunctional requirements and how can the use-case model be utilized to capture any of these? Solution: 1. Iteration is a mini-project that includes its own set of activities on requirements engineering, analysis, design, implementation and testing. The outcome of an iteration is a tested executable that forms part of the overal system. Time-boxing is enforcing short length iterations. 2. Critical use-cases are those that address high-risk and high-value functional requirements. 3. Incremental development refers to the process whereby the project is broken down into a series of iterations, so that the system is built incrementally over time, iteration by iteration. 4. The UP suggests that critical use-cases are implemented during the elaboration phase. 5. Functional requirements (FRs) are those that have observable behavior whereas nonfunctional requirements (NFRs) refer to qualities and constraints of the system. FRs are captured in the use-case model.

56

QUESTION 34 Briefly describe and illustrate the 3-tier architecture of your (COMP354-R) project of this term. Solution: 1. User interface includes a graphical user interface. 2. Application Logic inlcudes buisiness logic (impleemntation of use cases) 3. Technical services includes general purpose objects and subsystems that provide supporting services. In this project we have persistence.

User Interface

GUI

Application Logic

Authorize User, Create Ticket, View Ticket, Process Ticket

Technical Services

Persistence

Figure. 3-tier architecture of trouble ticketing system.

57

QUESTION 35 An automatic teller machine (ATM) provides basic banking services to customers who maintain one or more types of accounts at the bank. Currently the bank provides three types of accounts: Checking, Savings and Credit. Once authenticated by providing their card number and PIN, customers may access an ATM in order to check the balance of one of more accounts, transfer money from one account to another, withdraw money or deposit money. The ATM must maintain a record of all transactions undertaken by maintaining information on the date, account number and type of transaction. Consider the main (success) scenario of the use-case Withdraw Money: The customer initiates a withdraw request. The system responds with a number of options which include all available accounts maintained by the customer. The customer must make a decision on which account they wish to withdraw money from, and the system asks the customer to enter the amount they wish to withdraw. The customer enters the amount. The system reads the amount and proceeds to supply the money. The system asks the customer if they wish to have a receipt, by presenting the option for a written or displayed receipt. The receipt contains the amount withdrawn, the account number and the new balance. If the customer wishes to obtain a receipt, the system will either display the information on the transaction or provide a written receipt. 1. Based on the above specification, identify use cases and create a UML Use Case diagram.

ATM Authenticate User

Check Balance Withdraw Money Customer Deposit Money Transfer Money

2. Add pre- and postconditions to the main scenario of use-case Withdraw Money.

58

Preconditions: Postconditions:

Customer is identified and authenticated. Withdraw money transaction was saved.

3. Based on the specification and on the main scenario of use-case Withdraw Money use the following mechanisms to build a UML Domain Model: (a) a Conceptual Class Category List, (b) noun identification, and (c) Common Associations List. Where information is available from the specification and the use-case scenario, your domain model should include attributes and multiplicity expressions. Noun identification:
An automatic teller machine (ATM) provides basic banking services to customers who maintain one or more types of accounts at the bank. Currently the bank provides three types of accounts: Checking, Savings and Credit. Once authenticated by providing their card number and PIN, customers may access an ATM in order to check the balance of one of more accounts, transfer money from one account to another, withdraw money or deposit money. The ATM must maintain a record of all transactions undertaken by maintaining information on the date, account number and type of transaction. Consider the main (success) scenario of the use-case Withdraw Money: The customer initiates a withdraw request. The system responds with a number of options which include all available accounts maintained by the customer. The customer must make a decision on which account they wish to withdraw money from, and the system asks the customer to enter the amount they wish to withdraw. The customer enters the amount. The system reads the amount and proceeds to supply the money. The system asks the customer if they wish to have a receipt, by presenting the option for a written or displayed receipt. The receipt contains the amount withdrawn, the account number and the new balance. If the customer wishes to obtain a receipt, the system will either display the information on the transaction or provide a written receipt.

Conceptual class category list: CONCEPT CATEGORY Physical or tangible objects Specifications, designs, or descriptions of things Places Transactions Transaction line items Roles of people Containers of other things Common associations list: CATEGORY A is a physical part of B A is a logical part of B A is physically contained in/on B A is logically contained in B A is a description of B A is a line item of a transaction or report B

ATM, money, receipt Account Bank WithdrawalTransaction Customer

59

A is known/logged/recorded/captured in B A is a member of B

WithdrawalTransaction - ATM Customer ATM (bank)

WithdrawalTransaction 1 1..* initiated-by captured-on 1 ATM accesses Client CardNo PIN 1 has 1..* 1

Receipt

accesses

Account type

4. Use the scenario above to build a UML System Sequence Diagram (SDD).
:System :Customer initiateWithdrawalRequest() list of available accounts

selectAccount() amount to withdraw withdrawAmount()

initiate device to supply money option to provide a receipt [option=yes] chooseReceipt() [option=yes]receipt

60

5. From the SSD we can identify the following system operations: System
initiateWithdrawalRequest() selectAccount() withdrawAmount() chooseReceipt()

61

QUESTION 36 The domain is a flight reservation system. Consider the main scenario of use-case Reserve Flight, and the associated domain model and system sequence diagram (SSD) below: Reserve Flight main (success) scenario: A customer accesses an on-line console maintained by an airline carrier in order to make a booking of one or possibly more flights. The system maintains a catalog of all flights supported by the carrier. For each flight booking request, the system must display a confirmation. The customer must complete the session initiating the console to capture (save) all flights booked in a transaction record.

Booking

1..* is-included 1 Customer accesses 1 1 .Console 1 accesses uses Flight number source destination * Contained-in 1 1 1 FlightCatalog captures 1 * ReserveFlightSession isComplete: Boolean 1

62

:Customer initiateFlightReservation()

:System

loop

addFlight() [valid] confirmation [invalid] errorMessage

endFlightReservation() confirmation

Your assignment is to perform the following tasks: 1. Identify system operations: 2. Build operation contracts corresponding to the system operations of the SSD. 3. For each operation contract you must create a UML interaction diagram, by deploying any necessary responsibility (GRASP) patterns. In order to reason about Low Coupling and High Cohesion, supply and compare alternative designs.

63

Solution: 1. Based on the SSD, the system operations are the following.

System
initiateFlightReservation() addFlight() endFlightReservation()

2. The operation contracts are defined as follows: Contract CO1: initiateFlightReservation Preconditions: None. Postconditions: 1. An instance of ReserveFlightSession rfs was created. (instance creation) 2. Instance rfs was associated with Console. (formation of an association) 3. Instance rfs was associated with FlightCatalog. (formation of an association) Contract CO2: addFlight Preconditions: A flight reservation session is under way. Postconditions: 1. An instance of Booking b was created. (instance creation) 2. Instance b was associated with ReserveFlightSession. (formation of an association) Contract CO3: endFlightReservation Preconditions: A flight reservation session is under way. was Postconditions: FlightReservationSession.isComplete (modification of an attribute)

set

to

true.

NOTE: Attribute isComplete is not part of the domain model, but it will have to be added.

64

3. UML interaction (communication) diagrams are defined below (rationale of GRASP patterns is illustrated by comments).

ReserveFlightSession creates an empty multiobject which will hold Booking instances. This is implied to take place within the constructor of ReserveFlightReservation.

By Creator

:Booking

2: create() initiateFlightReservation() 1: create()

:Console

:ReserveFlightSession

By Controller

:FlightCatalog

By Controller

By Creator

addFlight()

2: makeNewFlight(f)

3: b:= create(f)

:Console

:FlightReservation Session

:Booking

1. f:= getFlight()

4: add (b)

:FlightCatalog By Expert

:Booking

65

According to the domain model you were given, both Console and FlightReservationSession are coupled to FlightCatalog. This implies that both of them are Information Experts on obtaining a Flight instance. An alternative design to the above would include FlightReservationSession to obtain a Flight instance from FlightCatalog before creating a Booking instance. A problem with that design would be a low level of cohesion of FlightReservationSession. The design above is OK as long as the Console will not be designed many responsibilities in the future (thus affecting its cohesion).

By Controller

By Expert

endFlightReservation()

1: becomeComplete()

:Console

frs:FlightReservation Session

66

QUESTION 37 This assignment is based on a room reservation system where clients can reserve any of a list of available rooms on given time slots. Consider the following artifacts: Use Case UC1 Primary Actor Preconditions Postconditions Main success scenario Make Reservation Client None The requested rooms are reserved on the given time slots. A client reserves a room for a given room and time slot. The system responds with a confirmation and a reservation number. Optionally a client may make subsequent reservations. Figure 1. Main scenario of use-case Make Reservation Use Case UC2 Primary Actor Preconditions Postconditions Main success scenario View Reservations Client None None. A client requests to view all reservations. The system responds with a list of reservations. Figure 2. Main scenario of use-case View Reservations

CustomerCatalog

1..*

Customer name accountNumber frequentFlyerMiles

Booking customer flight date time is-included ReserveFlightSession

Console

captures

uses

Flight flightNumber source destination 1..* Contained-in FlightCatalog

Figure 3. Domain model

67

Figure 3. SSD of main scenario of use-case Make Reservation

:Client

:ConferenceRoom ReservationSystem

viewReservations()

list of reservations

Figure 4. SSD of main scenario of use-case View Reservations

68

Operation Crossreferences Preconditions Postconditions

makeReservation UC1: Make Reservation Room available on given time slot.

Room availability has changed. A Reservation instance r was created. r is added to ReservationsBook

Figure 5. Operation contract for makeReservation


makeReservation()

1. getRoom(timeSlot)

:Console

:Directory

2. makeReservation(room, holder, timeSlot)

1.1. room := find(timeSlot) 1.2 [room available] setAvailability(room, timeSlot, false)

:ReservationsBook :Room
3. create(room) 3.1 add(r)

r:Reservation

:Reservation

Figure 6. Communication diagram for makeReservation()

viewReservations()

:Console

1: view ()

:ReservationsBook

2: display()

Figure 7. Communication diagram for viewReservations() 69

Your assignment is as follows: 1. On the UML interaction diagrams, indicate the deployment of any GRASP patterns by placing comment boxes. For each comment box, write a very short (one-line) comment on your rationale.

Consider the UML interaction diagrams with comments:

makeReservation()
By Controller 1. getRoom(timeSlot) By Expert

:Console

:Directory

2. makeReservation(room, holder, timeSlot)

1.1. room := find(timeSlot) 1.2 [room available] setAvailability(room, timeSlot, false)

:ReservationsBook
By Creator 3. create(room) 3.1 add(r)

:Room

r:Reservation

:Reservation

viewReservations()

By Controller

:Console

1: view ()

:ReservationsBook

2: display()

By Expert

For the rationale behind the deployment of GRASP patterns, please look at your lecture slides to see the conditions where each pattern is applicable.

70

2. Create a UML design class diagram. The UML design class diagram is shown below:
CustomerCatalog 1..* Customer name accountNumber frequentFlyerMiles updateAccount() Booking

* is-included 1

Console initiateFlightReservation() addFlight() 1 endFlightReservation()

ReserveFlightSession isComplete: Boolean * makeNewFlight(Flight, Date,


Time) becomeComplete()

Flight FlightNumber source 1..* destination FlightCatalog Contained-in getFlight()

3. Create skeletal code in Java. Consider the class definitions below:


public class Console private Directory directory; private ReservationsBook reservationsBook; public void makeReservation() {...} public void viewReservations() {...} } public class ReservationsBook private Vector reservations; makeReservation(Room room, String holder, TimeSlot time) { Reservation r = new Reservation; reservations.add(r); } view() { this.display; } display() {...} } public class Reservation { private int roomNumber; private TimeSlot timeSlot; private String holder; private int myReservationNumber; private String description; } public class Directory { private Vector rooms; getRoom(TimeSlot time) {...} public void setAvailability() {...} }

71

public class Room { private int number; private String description; private Boolean availability }

72

QUESTION 38 Consider a building elevator. One can press a button to move to any floor. Once the elevator reaches a destination it will stop for 10 seconds to let people get in or out, and it will move to the next destination if there is a pending request; otherwise, it will become idle until it accepts a request to move to another floor. Assignment Model the above specification as a UML statechart using four states. You may assume that the statechart has a mechanism to know about pending requests and you do not need to model this mechanism in the statechart. Use the State design pattern (see Resources) to implement the statechart in a Java program. In your program, simulate (hard code) the following sequence of events: (Elevator initially at ground floor) Move to floor 5 Move to floor 15 Move to floor 9 Move to floor 4 The output of your program is a sequence of all states it undergoes.

73

Solution: The statechart is shown below:

Moving Down

Stop

Moving Up

Idle

The output of the program is: Idle Moving up Stop Moving up Stop Moving down Stop Moving down Stop Idle

74