uml

Document Sample
uml Powered By Docstoc
					Object Oriented Analysis & Design
     with the Unified Modeling Language
Introduction to Analysis & Design
   Why is Programming Hard?
 It’s complicated.


     Computer programs are among the most complex things
      people build.


     Most people can only think of 7  2 things at a time.

 It gets more complicated as the system gets bigger.


     Why is the curve of effort vs. size exponential?

                                                              3
   Why is Programming Hard?




 Modularity helps to flatten this curve.

     With good design and abstraction you can work on a module
      — a part of the program — as though it were a single small
      program.

                                                               4
The Tasks of Software Development

 Figure out what problem to solve / what system to build.
    Analysis

 Build the system to solve the problem.
    Design
    Implementation / Programming

 Analysis is harder.

 What tools do we use to manage complexity and help with
  communication? (Not just in software, but everywhere.)
                                                             5
                         Modules
 A module is a part of a program or model that can be
  considered as an entity separate from the rest.

 A module should have high cohesion.

     It should do one thing, have a single responsibility, at its
      level of abstraction.

 A module should have low coupling.

 The kind of module we will be most interested in during this
  course is the object.

                                                                     6
                          Models
 The kind of model we will talk about most is an abstraction
  made up of modules and relationships between them.

 For example, the mathematics operations in our programs are
  abstractions.

 This abstraction allows us to focus on just a few things at a time,
  and also allows us to work at a constant level.

 One of the most important attributes of a model, regardless of its
  perspective, level, or purpose, is that it is clear and can be
  easily read and understood.

                                                                    7
                        Modeling
 Our choice of models to build is driven by our perception of the
  problem as much as it drives our understanding of the problem.

 Determine the purpose of the model before building it.

 For each model we must choose the level of abstraction.

 It’s useful for our models to be well grounded in reality.

 The UML is not complete. Explore other kinds of models. Data
  Flow Diagrams. Entity Relationship Diagrams. Etc.

                                                                     8
                    Perspective
 In software engineering we view our work and build our models
  from three different perspectives.

 Domain perspective (also called Conceptual or Essential
  perspective) is concerned with the domain, the context of the
  problem.

 Specification or Requirements perspective is about what the
  proposed system should do.

 Design or Implementation perspective describes the internal
  organization and operation of the system we propose to build.

                                                                  9
                 A Little History
 First we programmed in machine language by setting switches
  and jumper wires to represent machine language instructions.

 John von Neumann contributed the idea of treating the program
  just like data which led to assemblers and compilers and other
  ways the computer helps us to program it.

 Mnemonics for the machine instructions allowed us to replace
  0100 1011 with ADD. This is assembly language.

 The early High Level Languages (FORTRAN, COBOL, LISP)
  allowed us to get away from the machine a bit.

                                                                 10
                        Objects
 Objects are better modules.


 Objects give us more abstraction, better modularity, more
  flexibility.


 Before OOP we thought first of the operation: What’s it do?


 Each of these advances in abstraction, modeling, and
  modularity gave us the power to build larger systems with less
  effort by managing communication problems.

                                                                   11
                       Change
 Specifications change.

    This can cause poor communication between us and them.

    They don’t know what they need till we give them what they
     say they want.

    Specifications change as we and they learn more.

    Specifications change as the business domain changes.

    The later we change the more it costs.

                                                              12
                        Change




 The solid line is the classical curve of effort to change the
  system vs. the point in the development cycle at which we
  begin. (The same graph describes the cost of fixing a bug vs.
  the length of time it went undiscovered.)

                                                                  13
                  User Interface
 User interfaces present one of our biggest challenges.

     They're another communication problem.

 We have tools like use cases to help us find out what the users
  want and need.

     We must also pay attention to the underlying metaphor.

 Object Oriented Domain Analysis helps us to understand how
  the users and the client think about the problem and its context.

                                                                  14
                New Paradigms
 Adopting new technology such as OOP is difficult, confusing,
  expensive, and can frustrate both managers and programmers.
  Ignoring new technology is even more expensive.

 Training — more projects have foundered from too little training
  than from too much.

 Mentoring — some shops that have a training organization
  often send a teacher out as mentor to a team about to begin
  working with objects.

 Learn something new with each project, even if there is a cost.

                                                                    15
Objects
                 Encapsulation
 Encapsulation is the most important feature of Object Oriented
  Programming. Without it, the other big ideas (inheritance and
  polymorphism) are useless.

 There are two aspects to encapsulation as we use it in OOP.

    One is selecting a group of things (data and/or operations)
     and putting them together to create a module.

    The other is making some of the things accessible from
     outside the module, and making the rest inaccessible.
     (Information Hiding)
                                                                   17
                     Abstraction
 Abstraction is ignoring those aspects of something that do not
  contribute to your task in order to focus on those aspects that
  do.

     This is particularly useful in software development.

 Objects allow programmers to realize the benefits of abstraction.

     The details of data representation and the details of the
      methods are hidden from the programmers who use the
      object in their code (client programmers).

                                                                    18
                         Objects
 An object is a kind of module, used in models and programs,
  that can contain both data (often called attributes) and
  behavior.

 An object can send messages to other objects invoking their
  methods (calling their functions), and respond with appropriate
  behavior to similar messages from other objects.

 Operations (or methods) are invoked in response to messages.

 For example, a Date object might have attributes called day,
  month, and year.

                                                                    19
                         Classes
 A class is like a template for creating objects.

 Every object is an instance of some class.

 Then, in the program, you can create as many objects or
  instances of a particular class as you need, and they will each
  have everything declared in the class.

 The distinction between object and class is frequently abused.
  The literature and the people sometimes say object when they
  mean class. Strictly speaking an object is an instance of a
  class, but sometimes the word object refers to the class and its
  instances.
                                                                    20
             Instance Creation
 Often an object must create another object during the operation
  of the program (runtime).

    A bank system creates a new checking account, for
     example.

 In the source code a new object is created much the same as a
  new integer.

 Here is the UML syntax for some object creating an instance of
  the Date class at run time . . .

                                                                21
             Instance Creation


 Here some_object creates an instance of Date at runtime.

    After the creation some_object has access to the new
     Date object via a pointer or reference.

    Note that the new Date object has no name.

    Often you will see the name new() instead of create().

                                                              22
                Responsibilities
 Early in the process, as we begin to identify the objects in an
  existing or proposed system, we think about the responsibilities
  of the objects.


     Responsibilities are abstract.


 Note the deep relationship between the data and the
  responsibilities.


     Either drives the other.

                                                                 23
                        Attributes
 An attribute is a data item that belongs to an object; it is a
  member of an object.


 The values of an object’s attributes determine the object’s state.


 Attributes are usually private, and thus not accessible from
  outside the object.


 The data types of the attributes are often omitted in the early
  stages.

                                                                    24
            Composite Objects
 An object can contain another object as an attribute.
    For example, a Memo object might have a date associated
     with it which we might want to represent with a Date object.




    We can represent that by putting a Date attribute inside the
     Memo class, using the class name as the datatype.

                                                                25
      Operations and Methods
 A method is a function that belongs to an object.


 A method is invoked by sending a message to a particular
  object.


 An operation is similar to a method but at a more abstract level.


 The methods must eventually fulfill the responsibilities we
  assigned to the object earlier in the process.

                                                                 26
                         Visibility
 The members of an object, its attributes and methods, may be
  visible and accessible from outside the object or not.

     We call accessible from outside public and inaccessible
      private.

     In the UML public gets a plus sign at the left, private gets a
      minus.

 Attributes are almost always private.

 Methods may be public or private.

                                                                       27
                       Inheritance
 Inheritance allows you to create a new class that contains all
  the attributes and methods of an existing class and then add to
  them.

 A subclass also inherits the responsibilities of the superclass.

 Inheritance is first a logical relationship.

 Inheritance helps us avoid representing the same thing twice by
  allowing us to put attributes and methods that are common to
  several classes (subclasses) in a single common superclass.

                                                                     28
Inheritance Example




                      29
          Inheritance Example
 Objects of the Student class have names and addresses and
  so forth which they inherit from the base class Person.

 Students also have attributes of their own, not inherited, such
  as GPA.

 Likewise with operations: some are inherited, some are unique
  to Student.

 Let's imagine that in our school we always format the names of
  students last name first, while other people’s names have their
  first names first.

                                                                30
                       Visibility II
 The methods of a subclass cannot access private data or
  methods in its superclass but must use the public methods of
  the superclass just as unrelated objects must.


 A third access specifier, protected, is indicated with a # at the
  left of the line.


 Is the protected access mechanism necessary?


 It's better to make attributes private by default, and change
  specific attributes to protected only if you need to

                                                                      31
Objects II
   Constructors & Destructors
 A constructor is a class method that executes automatically
  whenever an instance of the class is created.

     Constructors may take arguments so that a new object can
      be initialized with data passed in.
     A class may have several constructors with different
      argument lists.

 A destructor is a method of a class that executes automatically
  when an instance of the class is destroyed.

     A class cannot have more than one destructor.

                                                                    33
                           Scope
 In a program or a design for a program, a module such as an
  object, a function, or even a primitive variable like an integer has
  a characteristic called scope.

 A variable may be local to a disk file, to a group of objects (a
  package), to an object and its children, to a single object, to a
  function, or even to a part of a function.

 Items in different scopes may have the same name but not
  interfere with each other.

 It’s a good idea to restrict the scope of each item.

                                                                      34
                   Class Scope
 An attribute of a class may have class scope.


    This means there is one copy of the attribute regardless of
     how many instances of the class are created.


 A method may also have class scope.


    A class scope method may be called on the class in a
     situation where there are no instances of the class, or the
     calling code does not have access to one.

                                                                   35
   Runtime Type Identification
 Every object is created from a class.


 Most OO languages allow you to identify the type of an object at
  runtime.


 Often when you find it necessary to identify the type of an object
  at runtime it is a cue that you should reconsider your design.


 Runtime Type Identification (RTTI) is useful primarily to
  developers of tools like debuggers.

                                                                  36
               Abstract Classes
 An abstract class is one that cannot be instantiated; it exists for
  the sake of an inheritance hierarchy.

     In UML, show that a class is abstract by italicizing its name.




     You can also use a stereotype.



                                                                   37
              Abstract Classes
 Abstract classes often contain one or more method declarations
  which have no code.

    Note that draw() above is in italics to indicate that it has no
     implementation (code).

    The Graphic class could not draw itself even if it had code.
     It doesn’t know what shape it is.

 Abstract classes are intended to by used by subclasses that
  provide implementations for the code-less methods.

                                                                   38
                 Polymorphism
 Polymorphism allows a program to create objects of different
  (but related) types and manage them all in the same way using
  the same code.

 Polymorphism is a powerful technique that can make your code
  much more readable, or much less.

 In strongly typed languages like C++ and Java polymorphism is
  implemented among classes that share a common ancestor.

 Polymorphism requires dynamic binding (also called late or
  runtime binding) as opposed to static binding.

                                                               39
       Polymorphism Example
 We are writing a drawing program. We create an abstract base
  class called Graphic. It has a draw function but no code for it,
  since a graphic has no shape and you can’t draw it. Then we
  create subclasses called Square, Circle, Triangle, etc.
  Each provides code for the draw method to draw its own shape.




                                                                 40
       Polymorphism Example
 Now we write the code for the rest of the program. As a user
  creates shapes and places them on the screen we create
  objects of the proper types. We store the shapes in a list of
  Graphics.



 When the user hits the refresh button the program iterates
  through the list of Graphics and calls draw() on each. This
  works because Graphic has a draw function. What we get, of
  course, is two triangles, a circle, a square, three more circles,
  etc. Whatever the user created, and the program put on the list.


                                                                  41
           Multiple Inheritance
 When a class inherits from more than one superclass it's called
  multiple inheritance.




    The subclass inherits the attributes, responsibilities,
     operations, methods, and relationships of all the
     superclasses.




                                                                42
            Multiple Inheritance




 As with all inheritance relationships, multiple inheritance must
  be logical as well as functional.


                                                                     43
  Problems with Multiple Inheritance

 As you can see from the diagram on the previous page, multiple
  inheritance can be useful to model situations from the real
  world.


    Unfortunately there are some potential problems.


    Fortunately we can solve them.


 The OO languages each handle multiple inheritance differently.

                                                               44
  Problems with Multiple Inheritance

 Multiple inheritance can be ambiguous when the superclasses
  each contain members with the same name.

    Does Working_student inherit one or two names?


    If two, how do you distinguish between them in the
     subclass?




                                                                45
   Solving Multiple Inheritance Problems

 Since many languages don’t support multiple inheritance and
  since it can cause implementation problems, you may want to
  avoid using it in your designs.

 You can get the same effect by duplicating some code (here it’s
  in the public transport part) and inheriting from it.




                                                                46
   Solving Multiple Inheritance Problems

 Another way to get the effect of multiple inheritance is by using
  composition. Here Public_transport objects are part of
  Bus and Cruise_liner. (We will talk more about composition
  later.)




                                                                 47
                       Interfaces
 An interface is like a class that has only a public interface and
  no private part.


 Indicate an interface with a stereotype.




                                                                      48
                       Interfaces
 We say Graphic implements Drawable even though it looks
  like inheritance (note that the line is broken instead of solid).

     This means Graphic and Text inherit the method
      declarations of Drawable.


 In Java interfaces are part of the language.

 Interfaces are not part of the C++ language but you can get the
  same effect by creating abstract classes with no code or
  attributes.

                                                                  49
Use Cases
                    Use Cases
 A Use Case can be succinctly described as:

    A coherent unit of functionality.
    A single interaction between a system and a user to attain a
     single result for the user.
    An interaction between a user and the system consisting of
     one (or more commonly a set) of operations that together
     accomplish some goal.

 We often draw Use Case diagrams in the early stages to model
  the most important things the client needs from our system.

                                                                51
                   Use Cases II
 A Use Case is initiated by an actor, represented by a stick
  figure with its name underneath.

     The actor is outside the system we are developing.
     The actor is usually a person, but may be another system.
     The actor’s name is often a role.




                                                                  52
                  Use Cases II
 The UML uses an oval to represent a use case. The name goes
  inside.




 The line between them shows that this actor performs this use
  case.




                                                                  53
            Use Case Diagram
 A use case model represents some or all of the use cases for a
  system. It shows the actors and the use cases that each can
  invoke.




                                                               54
            Use Case Diagram
 Occasionally we will draw a rectangle to show the boundaries of
  the system we are considering. Usually it is obvious, since we
  know that the actors are outside the system, so we omit the box.

 There isn’t a great deal of information here. We are just
  beginning to find out what our system will have to do and who
  performs each task.

    Such a model is easy for non-programmers to understand. It
     helps our communication with the domain people.
    It’s useful for getting an initial idea of the scope of the
     project.
                                                                  55
           Include and Extend
 Use case A may include use case B (indicated by a stereotype).
  Every time use case A executes, use case B also executes as
  part of it.


    Use case hire teacher includes use case get teacher list.


 Use case A may extend use case B. When use case B
  executes it will sometimes execute use case A.


    Use case add teacher to list extends use case hire teacher.
     Hire teacher sometimes adds the teacher to the list.

                                                                 56
            Include and Extend




 A use case can be a specialization of another use case, as hire
  teacher is a specialization of hire employee. The hire teacher
  use case has all the elements of hire employee, plus a few
  peculiar to teachers. This is similar to inheritance between
  classes and uses the same notation.

                                                                57
                Other Systems
 Sometimes the system under consideration will communicate
  with other systems. Suppose our university contracts with an
  outside organization for financial services. Our computer
  communicates with their computer and they send out the bills.




                                                                  58
                 Other Systems
 When a student registers for a course our system sends the
  information to the computer at the financial services house so
  that they can bill the student for the course.


 In one sense this is outside our mandate because it represents
  things the user, the student, is not aware of when registering for
  a course.


 In another sense, if you were walking around our system and
  observing all its interactions with the domain you would see this
  information passing to the billing service.

                                                                   59
                       Narrative
 Use Case diagrams identify use cases, they do not define them.
  We’ll need more information.



 The text narrative contains details that we cannot put in a
  diagram.



 The UML has no standard for these narratives. As always, you
  should include only as much information as you need.


                                                                60
              Using Use Cases
 Use cases identify what a system does for the user.

    They describe what the users use the system for and how.
    They can also model the user interface.

 We may build use case models of an existing system which we
  propose to replace. This usually happens during domain
  analysis.

 We will sometimes build simple use case models of our
  proposed system during inception to help us define the scope of
  the project.
                                                                61
Classes and Their Relationships
                   Class Models
 The class model is the central model in OOA&D.

 A class model is a static model of one or more classes and
  (optionally) the relationships among them at a particular level of
  abstraction.

 A model of a single class can show its attributes with or without
  datatypes, its operations or methods with or without arguments
  and return types, and its responsibilities.

 A class model can show several classes and the relationships
  among them.

                                                                   63
                    Associations
 Association is a weaker relationship than aggregation or
  composition.



 Here we say there is an association between a Teacher and a
  Student.
     There is a relationship between them, but neither is a part of
      the other and neither is a kind of the other.

 The nature of this relationship is implied by the class names.
    Teacher teaches Student.

                                                                   64
                   Associations
 Where the relationship is not obvious from the class names, put
  a word or phrase on the line to explain it.


    A Student may have an advisor who is a Teacher.




 There may be more than one association between two classes.




                                                                65
                      Multiplicity
 An association can involve more than one object on each side.

     Suppose each teacher advises exactly 37 students.



 Show how many objects of a class can participate in the
  association by putting the number on the association line next to
  the class.

     The default is exactly 1, thus the above diagram says each
      teacher advises exactly 37 students, and each student is
      advised by exactly 1 teacher.
                                                                   66
                     Multiplicity
 In the diagram below we say each student takes from zero to
  five courses while each course is taken by zero to many
  students.

    The asterisk means any positive number, including zero.

    0..n or simply n mean the same as *, although it’s not
     standard notation.



 These numbers pertain to a particular moment, not the lifetime
  of the system.

                                                                   67
        Qualified Associations
 Suppose the university enrolls a large number of students. In
  order to deal with the lookup problem there will be some
  unambiguous way to identify a particular student. For example,
  a unique student ID number.



 This model says that each Student is associated with a single
  ID.


    It implies that there are many students associated with the
     university, otherwise we wouldn’t need an index.

                                                                   68
         Qualified Associations
 The qualified association syntax can be used in a slightly
  different situation. Suppose an Order object has a Line_Item
  for each product ordered.




 This says that each line item is associated with a single product
  and no two products have the same line item. The association
  between product and line item is one to one (for a particular
  order).

                                                                  69
                          Roles
 There is another way to show that the Teacher is associated
  with the Student in a role other than Teacher.


    Instead of naming the association (advises) as we did
     previously, we can name the role.




 Here we say there is an association between a Teacher and a
  Student in which the Teacher’s role is advisor (rather than the
  default role of teacher).

                                                                70
                           Roles
 When objects of the same class are associated with each other
  it’s called a reflexive association. The objects may take
  different roles.



 Here we have an Employee in the role of boss supervising
  other Employees in the role of worker.


    Don’t put all three qualifiers (boss, supervises, worker) on
     the association unless you need them. In this case either
     boss or supervises would be sufficient.

                                                                    71
           Association Classes
 An association itself may have attributes that you cannot
  reasonably put in the associated classes.


     There is an association between Person and Play which
      we call ―attends‖. Where do we put the date that the
      Person attends the Play?




 A Person can attend many plays on different dates, so the date
  cannot go in the Person.

                                                              72
           Association Classes
 An association class is connected to its association by a
  broken line, and contains the features of the association.




     In this case the association class models the ticket, a real
      object from the domain.


 According to the UML constraints there can be only one
  instance of the association class between two associated
  objects.
                                                                     73
 Composition and Aggregation
 Composition is a part–whole relationship in which one class,
  the part or component, belongs to or is a part of another class.

     This is often described as contains, is part of, or has a.

     Composition often implies that the part can belong to only
      one whole and that the lifetimes of the part and the whole
      are the same.

     A Door is part of a Car object and is tightly tied to the Car
      and cannot have an independent existence (not counting
      junkyards).

                                                                      74
 Composition and Aggregation




 Aggregation is another part–whole relationship that is a little
  looser, and less strict than composition.

 We usually assume a 1 at the diamond end of aggregations and
  compositions.

                                                                    75
           Using Class Models
 Class models show the nature of the objects and the static
  relationships among them.

 We model the individual objects as we discover them during
  domain modeling.

 We generally build one or more high level class models using
  objects from the domain fairly early on.

 Usually in Requirements Analysis we use the class models from
  the domain if we use any at all.

                                                                 76
Interactions Over Time
           Sequence Diagrams
 A sequence diagram is a dynamic model.

 Here the task is to change the number of credits for a course.




 The broken vertical lines are the lifelines of the objects.

                                                                   78
          Sequence Diagrams
 The department secretary sends a get_credits message to
  the course requesting its credits.


    Messages are solid lines with arrows. Usually the message
     is written above the line.


 The course returns the credits.


 Finally the secretary sends a set_credits message with the
  new value and the course changes its data to match.

                                                               79
                      Decisions
 If you must show explicitly what happens to a return value, you
  can assign it to a local variable.

     The UML assignment operator is colon equals (:=).

     We assume that credits is a local variable in dept_sec.




                                                                    80
                       Decisions
 If the current value of credits is the same as the new value
  we do not need to send the second message, so the message is
  only sent under certain conditions.


     You can add a condition in square brackets above or before
      the message. This is called a guard condition.


 It doesn’t take much conditional branching to make a model
  difficult to follow. If you need to model multiple paths through a
  complicated operation it’s often better to draw multiple sequence
  diagrams.

                                                                  81
                       Iteration
 The university has decided to change the name of the Computer
  Science department to Information Technology.


 The boxes behind boxes show that there are many courses.




                                                             82
                         Iteration
 The syntax for iteration is similar to that for a conditional
  message, with the addition of the asterisk. A statement inside
  square brackets describes the iteration.


     The general symbol for iteration is the asterisk, which may
      be used alone if the meaning is clear.


 As the secretary does this, and the skin slowly wears off his
  fingertips, he’s probably thinking about the desirability of
  representing each thing in only one place (a collection of items),
  the way we try to do in our programs.

                                                                    83
 Creating and Destroying Objects
 When the department decides to offer a new class (OOA&D for
  example) the department secretary has to create it.

    As you can see below, the object comes into existence as
     the result of a message called create (some people use
     new).




                                                                84
 Creating and Destroying Objects
 We can imagine the secretary getting out a file folder, writing the
  course name and number on the tab, and filling it with the forms
  that hold the data for a course.


 After the object is created other objects can send messages to
  it, just like an object that existed from the beginning.


 Then the department chairperson calls to say that the
  department board has reconsidered the new course since three
  of the members don’t think object oriented programming is here
  to stay.

                                                                   85
                       Activation
 The narrow vertical rectangles on the lifelines of the objects in
  this diagram show when each object is active, either doing
  something or waiting for a message to return.


 Note the secondary activation under warehouse, where the
  warehouse sends a message to itself to reorder if the stock is
  low.


 Arguments and return values are omitted when it’s clear what
  they would be.

                                                                      86
Activation




             87
                  Sync & Async
 In a domain model like the one above, modeling the way the
  business works, we are often less than perfectly rigorous. This
  diagram is typical.

 In reality, the order clerk doesn’t want to wait for the warehouse
  to complete its tasks, i.e., check stock and possibly have to
  order items to fill the order; she wants to go on to the next
  customer and create another order.

 With the increased popularity of agent oriented and distributed
  systems we often find that our programs will run on several
  processors or systems.

                                                                    88
Sync & Async




               89
  The Objects Drive the Interactions

 Building a sequence diagram is figuring out how something
  works, how its parts interact, whether you are modeling
  something that exists or designing something new.


    Note that the objects drive the structure of the interactions
     between the objects, just like in the real world.


    We are guided by the collaborators we discovered earlier, by
     the distribution of attributes among the objects, and by the
     distribution of responsibilities, operations, and methods
     among the objects.

                                                                     90
  Evaluating Sequence Diagrams
 Is it readable? Do the users and the domain experts agree?

 One of the easiest ways to spoil a model is to put too much on it.
  Stick to a single topic and a single level of abstraction.

 Limit your use of conditional execution and branching.

 Iteration seems to be less confusing than conditional execution.
  But you still have to pay attention to elegance and clarity.

 Not all sequence diagrams begin with a message from a user.

                                                                  91
    Using Sequence Diagrams
 In domain analysis sequence diagrams show us how the parts
  interact to perform the functions of the system.

 Sequence diagrams may be used to model an exchange
  between a user and a system, as we did with some of the
  simple ones above (to illustrate a use case, for example).

 In design they help us to see what we’ve missed.

 In design a sequence diagram that realizes a use case shows
  that our proposed system can perform that use case, and how it
  will be done.

                                                               92
Interactions Over Space
       Collaboration Diagrams
 Collaboration diagrams hold the same information as sequence
  diagrams but they emphasize the links between the objects
  instead of the time sequence.

 The syntax is similar to what we saw in the object chapters and
  the sequence diagram.

 The time sequence of the messages is shown by their numbers.

 The collaboration diagram shows the links between the modules
  and helps you understand them and their navigability. There
  must be a link of some kind everywhere a message goes.

                                                                94
Collaboration Diagrams




                         95
     Collaboration Diagrams II
 The previous collaboration diagram uses the links represented
  in the class diagram. That’s how we knew where we could send
  messages.


     Of course in a domain model we are checking the links in the
      class diagram as much as using them. These messages go
      where they go, and if there is no link we must add a
      permanent one or create a temporary one.


 Arrows on the link lines show the direction in which each link
  may be traversed.

                                                                   96
     Collaboration Diagrams II
 One approach is to draw in the arrows on the existing links (from
  the existing class diagram, whatever your perspective) as you
  discover the need for them in your interaction diagrams.




                                                                 97
  Evaluating Collaboration Diagrams

 Does it correspond to the appropriate class diagrams?

 Does it have too many conditional branches? Draw another
  diagram instead.

 Does the flow make sense:
    To the domain people, if a domain model?
    To the next programmer to work on it, if a design model?

 If you are assigning responsibilities and operations at this level
  be careful about cohesion and coupling.

                                                                       98
Using Collaboration Diagrams
 We use collaboration diagrams to show the dynamic operation
  of a system along with the relationships between the modules.

 This may occur while modeling the domain, but usually we use
  more sequence diagrams in domain models.

 Collaboration diagrams are most useful in designing the
  software.

 Note that collaboration diagrams, in contrast to sequence
  diagrams, do show the links between the objects over which the
  messages pass.

                                                                  99
State Machines
                 What is State?
 State is the condition, mode, or internal situation of something.

 In the broadest sense the state of an object, for example a
  student, consists of the values of all of its attributes.

 When we talk about state we will mean that part of the general
  state which affects the logical behavior of the object.

 A state machine is a model of the states a module may be in, its
  behavior while in each of those states, the stimuli and conditions
  that cause transitions between those states, and the actions
  associated with the transitions.

                                                                  101
                   State Notation
 The round cornered rectangle is a state.

 The filled circle is the starting point and the bull’s-eye is the end.

 The lines with arrows are transitions between states.

 The plain text on the transition line is the event that triggers
  that transition.




                                                                     102
                 State Notation
 A state diagram may have more than one end point and they
  may have labels.




 A simple state machine has only one starting point.


                                                              103
       Transitions and Guards
 The trigger for a state transition may be a condition instead of
  an event. Here, as soon as a freshman achieves thirty credits or
  more he makes the transition to the exalted state of sophomore.




                                                               104
        Transitions and Guards
 Obviously one’s class standing cannot advance if one owes a
  library fine.




 The clause in the square brackets is a guard condition. It is
  evaluated after the trigger event or condition, and the transition
  occurs only if it is true.

                                                                   105
         Registers and Actions
 The previous diagram is expressive as it is. We just assume
  that there is some means of representing credits and adding
  credits from courses passed, because we have a shared idea of
  how schools work.



 If we need to be more formal, perhaps because we do not all
  share a common understanding of the thing under
  consideration, here’s how we might do it. This is called a
  register state machine and the register is called credits.



                                                                106
          Registers and Actions




 The loop at the top is called a self transition. It is triggered by
  the pass course event, denoted to the left of the slash.

                                                                   107
                   More Actions
 Our university has a rule that freshmen must live in the
  dormitory.




 Note that a transition may have more than one action (effect).

                                                                   108
                  More Actions
 The only thing wrong with this is that move out of dorm is shown
  twice.




 We can put entry and exit actions inside a state, to be
  executed upon entering and exiting the state.
                                                               109
            Internal Transitions
 By the merest coincidence there is a handy bit of syntax to solve
  that problem. We can put an internal transition inside the state
  to handle the distribution of credits and remove the self
  transition.




                                                                110
            Internal Transitions
 Just to illustrate one more bit of syntax, suppose a student gets
  a part time job in the library.



 Note that the do is not an atomic action but an activity that can
  go on for a period of time. This activity goes on whenever you
  are in the state.


 These don’t do anything you couldn’t do with multiple states and
  self transitions, but they can help you build a simpler and more
  readable model.

                                                                 111
   Superstates and Substates
 Suppose we want to expand this state machine to include junior
  and senior.




 This is not a good diagram. It has duplications and crossed
  lines and generally too much complication.
                                                                112
   Superstates and Substates
 If you think about it, there is another state that encompasses
  these.




 This model is simpler and clearer than the one above, but the
  difference between two models will not always be this obvious.

                                                                   113
Concurrent States




                    114
             Concurrent States
 When an object can be in two or more states at the same time
  and neither is inside the other (like substates inside a
  superstate) they are called concurrent states.


 When both of the concurrent state machines reach the sync bar
  (the heavy vertical line) the transition from the enrolled state
  to graduate occurs.



 If there are concurrent state machines that are not inside the
  same superstate you will probably model them separately.

                                                                   115
         Using State Machines
 We use state diagrams to model anything that has complex
  state. In other words, when the behavior of a module depends
  in a complex way on its past history as well as its current inputs.


 One of the indicators is describing something in text and finding
  yourself saying ―and then if this happens you do that but if that
  happens you do this . . . ‖


 The things you model are usually objects or user interfaces. A
  state machine can be useful in describing a user interface with
  complex sequences.

                                                                  116
                Implementation
 Traditionally, state machines have been implemented in code as
  case (or switch) statements that select behaviors according to
  the value of a variable which represents the current state. This
  works fine, in simple cases.


 For more complex situations, create an object as a member of
  your main object to represent its state. The state object can
  hold all the behavior (the methods) that vary between states. It
  also knows when and how to change state. All these state
  objects are used polymorphically, so inherit from a base class
  (or an interface).

                                                                117
               Implementation




 There are two ways to manage the state objects.

                                                    118
Activities
                Activity Notation
 Activity diagrams are similar to flow charts.

 The notation of activity diagrams is much the same as that of
  state diagrams.

     The main difference is that most of the nodes in a state
      model are states (although some may represent activities)
      while most of the nodes in an activity model represent
      activities (although some of them may represent states).




                                                                  120
               Activity Notation
 Partly because most nodes are activities, most transitions are
  triggerless.

 There can be guard conditions like those in state charts.




                                                                   121
         Decisions and Merges




 If you don’t want to make the testing an explicit activity but just
  branch on the results you can replace the test activity with a
  decision diamond. The testing happened somewhere, perhaps
  as part of the write a program activity.

                                                                   122
        Decisions and Merges




 If you believe the program needs to be checked again after
  debugging (whatever are you thinking?) you can run the path
  back around through another diamond called a merge.

                                                                123
                Synchronization
 One of the strengths of activity diagrams is their ability to model
  parallel processes.

 When a single transition encounters a synchronization bar
  (heavy vertical or horizontal line) it continues along the paths on
  the other side in parallel and asynchronously.

 The second synch bar means that all the incoming transitions
  must arrive before the outgoing transition may leave.

 A sync bar may have multiple arrows arriving on one side, and
  multiple arrows leaving on the other.

                                                                   124
                   Drilling Down
 Activity diagrams are usually easier to understand than, say,
  collaboration diagrams with the same number of nodes.

 If we want to add detail to a section of this model we would
  probably do it on another diagram, both to avoid making this one
  more complicated, and to avoid adding material at a different
  level of abstraction. This is called drilling down.

 We expanded the put coffee in filter node to create
  this new model with more detail.




                                                                  125
Drilling Down




                126
                       Iteration
           add Item to order




                         / *[for each]



                                         / [out of stock]
                         check stock                           Reorder

Authorize Payment
                          / [in stock]
                                                / [in stock]



                       Put item in box




                                                                         127
                       Iteration
 We can model iteration on an activity diagram as we do on other
  dynamic models.

    Note that the decisions and branches of control are clearer
     than they were in sequence and collaboration models.

 In the diagram on the facing page the activity check stock is
  done for each item.

 The second iteration operates over three activities. For each
  item you check stock, reorder as necessary, and add the items
  to the order when possible.

                                                               128
                     Swimlanes
 This activity model illustrates swimlanes. The labeled vertical
  bands show who is responsible for each of the activities.




     Use swimlanes when you need the activity model to show
      complicated flow of control and who does what.




                                                                129
       Using Activity Diagrams
 Activity diagrams are mostly about the flow of control. The
  activity model is particularly good at showing complicated
  branching and parallelism in control.

 Activity diagrams are good for modeling the operation of an
  existing paper system that you intend to replace, if it is more
  about control than information.

 Activity models are useful for modeling user interfaces.

 Activity models are often used to illustrate branching in the
  operation of use cases.

                                                                    130
Process
                                      Goals
   There are two groups involved: the client organization and the development organization.


   Take care of the Client.
      Give the client control and ownership
      Make sure the system can easily be changed
      Build something the user will like


   Do right by the Development Team.
      End with a stronger team than started with
      Mandatory overtime burns people out
      Learn something new with each project


   Even if you are not a manager, knowledge of project management is useful.


                                                                                           132
                        Process
 Process is our plan to complete all the tasks and deliver the
  system our client needs on time and under budget.

 We need a plan to help us organize what to do when and how
  and with whom.

 Processes differ in formality and ceremony over a wide range
  because projects differ in size and complexity and every other
  metric, over a wide range!

 One of the best reasons to have a process is that you can then
  improve your process.

                                                                   133
                          People
 The people contribute more to the success of a project than any
  other factor. Five of the very best can do the work of fifty with
  better quality.
 Staffing is difficult, but crucial. Find those five!
 Give your people work that interests them – based on individual
  preference and circumstances.
 Protect your people from problems and hassles that aren't part
  of their work.
 Involve your people in setting the goals.
 Avoid manipulative motivation – be sincere, provide good
  workspace and the tools they need
 Never ask for less than their best.

                                                                 134
                 Business Case
 The business case is a study of the business effects of the
  project.
    How the resulting system will fit into the operation of the
      business.
    Cost/benefit analysis, funding sources, opportunity costs,
      etc.
 The business case is the study of all the non-technical factors
  that go into your company’s decision to go ahead with this
  project or not.

 It’s the responsibility of the business people, not the developers,
  but it’s a crucial part of the project.

                                                                    135
                Risk Management
   A little risk management can make a big difference in your chances to
    deliver on time and under budget.


   Risk management requires a commitment from management, a place
    in the plan, and funding.


   Then you need a risk officer – the consummate pessimist
      Need to maintain a list of risks and actions to mitigate them
       (prevention, detection, and correction)


   A way for people on the team to suggest risks anonymously is
    important.
   If a risk is too great, it may be enough to cancel the project.

                                                                        136
                                           Test
   Like risk analysis, quality assurance requires a commitment from management, funding, and
    a place in the plan.


   You’ll need a formal system for tracking defects and fixes. If a lot of the problems come from
    one area of code, rewrite it.


   Test before code: test domain models and requirements models too! That’s the major
    reason why we develop the models.


   Test new code as it is written. Some projects even write the tests before the code. (Tests
    are specifications.)
      Do it right, prove it, and go on.
      Keep the test code at each step
      Make small changes and test those
   Final test is the acceptance test run by the users.



                                                                                              137
Test




       138
                           Reviews
   Research on real projects shows that reviews find more defects earlier
    for less effort than any sort of testing.

   Reviews should start with the first domain models.

   Review the domain models and specifications for readability,
    completeness, self-consistency, and agreement with the needs of the
    users and the client.

   Review the designs. Now your reviewers will be the analysts,
    designers, and programmers.
      Satisfy Requirements?
      Complete and consistent?
      Buildable?


                                                                        139
  Code Review(Xtreme Prog.)
 If you know it will be reviewed by a peer, then more
  careful in writing.
 Will find defects you can’t see.
 Can offer suggestions for improvement of structure,
  clarity, and readability.
 Some reviews are done before the code is even
  compiled
 Small groups work best > 4
 ―Paired Programming‖ has two people writing the
  code together – continuous review.

                                                     140
           Tools and Techniques
   CASE (Computer Aided Software Engineering) tools are available to help you
    with your visual modeling.

   Some teams prefer a plain drawing tool like Visio.

   Some people feel that the power and simplicity of the whiteboard make it the
    best modeling tool.
      Easier to see
      Easier to change
      Can photograph it
      Takes a conscious effort to decide to save it

   The file cards (CRC cards) that some teams use early in the process to discover
    objects and assign responsibilities can play a part in design too.



                                                                                   141
                    Refactoring
 Your first design for the new system may not be perfect. Really!


 Success comes not from perfection from the beginning but from
  finding problems early and fixing them right.


 We should improve the structure of the program (or model)
  every time we touch it. This is called refactoring.


 Refactoring is improving the structure of a system without
  changing its operation.

                                                               142
                     Refactoring
 Discover a ―pattern‖ that fits your problem and then implement it
 Refactor as you change
    1st iteration – simple structure
    Next iterations – refactor to support new features
    If good OO design then may have to discard only 10-20% of
     previous work
    Can’t anticipate everything at the beginning – adapt as you
     go
 Consider changing the structure before making local changes




                                                                 143
                          History
 The waterfall process was popular in the days of small projects
  and homework assignments.

     Unfortunately in the real world you cannot complete one step
      before beginning the next.

 The waterfall has been largely replaced by various iterative
  processes.


 Iterative processes give you a chance to recognize a problem
  with the process and change it as you go.

                                                                 144
History




          145
History




          146
              The Unified Process
   The Unified Process is flexible enough to represent almost any iterative process.


   It starts with some specified amount of initial activity (Inception and Elaboration)
    which is done once at the beginning of the project and never repeated.
      High level analysis and architecture design
      Decide whether to proceed


   Then we go into the Construction phase and repeat a cycle of analysis, design,
    code, and test which produces an increment of functionality each time around.
      Deliver on time even though not fully functional


   The final phase is Transition, in which you train the users and deliver the final
    working product.
   Keep adding functionality during each cycle.

                                                                                     147
                Agile Processes
 The variations among iterative processes usually lie in how
  much is done up front and how much is left to the iterations.
    eXtreme Programming has a very small inception phase and
     iterates on nearly everything else.

 The theory is that if you understand Structured Design and use
  it wherever it applies, if you understand OOA&D and use them
  appropriately, and if you understand Refactoring and practice it
  diligently, then you can change direction in the middle of the
  project without paying a high cost. SD, OOA&D, and
  Refactoring give us flexibility, the ability to respond to change.

 Each iteration in construction starts over, as much as practical.
  You don’t plan beyond the end of the next iteration.

                                                                  148
  Agile Construction Iterations
 If you plan ahead to far it’s just a guess
 Design what you need now and refactor to accommodate new
  functionality
 Discuss with users what they would like next
 Document it, model it and analyze it
 Refactor based on the new information (if necessary)
 Write tests
 Design changes, write code, test it – include regression tests
 Present to users for feedback
 Cycles can be as short as a week or two


                                                               149
    Essential of Agile Process
 Individuals and interactions over processes and tools
 Working software over comprehensive
  documentation
 Customer collaboration over contract negotiations
 Responding to change over following a path




                                                     150
The Project
                      Inception
 What’s called for here is a problem statement, which should be
  fairly short — a paragraph to a few pages.
 Now there’s a problem statement with punch.
 A Vision can be useful, inspiring to all concerned.

 Begin to accumulate information. Talk with the domain experts,
  users, and client – contacts valuable throughout the project.

 Evaluate interest among users and management.
    Find a ―champion‖ in management if possible
 Decide whether to go ahead or not

                                                               152
                    Elaboration
 Continue to learn about the scope.
     High level use cases
 Think about the high level architecture.
 Build or buy? There might be something available for sale, and
  if it’s at all suitable you may save a lot of time and money.
 Refine your guesses about the time and cost involved.
 Continue working on the business case.
     Profit and loss in widest sense (not just $$$)
     Who are stakeholders
     Consider project as development opportunity
     Consider project as way to introduce new development tools
        and processes

                                                              153
                  Elaboration II
 Begin risk analysis.

 Start on the user manuals early. It’s more likely they will be
  ready when the software ships, and there are other benefits too.

 Domain analysis starts here.

 Do a review with the appropriate people.
    Management, users, domain experts, and others
    Get a time commitment from all involved

 Decide again whether to go forward or quit.
                                                               154
           Construction Iterations
   Iterate on analysis, design, code, test.
       Let the client choose the functionality for the next iteration
       If possible, pick something easy and impressive
       Each iteration will help develop detailed requirements for the functionality to
         be added
   Test each module before you put it into the build, and every time you change it.
       Automate the testing
       Should return simple results easy to evaluate
       Regression tests each time
   Build often and test the whole thing every time you build.
       Add tests every time you add a feature
   Keep on reviewing analysis, design, and code.
   If you get behind, slip functionality rather than date. You may have to add an
    iteration at the end.



                                                                                    155
  Iterations II - The Other Stuff
 Continue with your risk management.
    Getting commitment needed
    Staffing okay
    Technical risks
    Continued management support
 Keep up with the business case. Does it still look like making a
  profit? That can offset a lot of management’s complaints.
 Hold reviews on your models, designs, and code.
    Need a third set of eyes to catch what you missed
    Bring someone from outside the project if possible
 How is your process working? How do you know? How can
  you improve it for the next iteration?
 Continue to consider the go/quit decision.

                                                                156
Domain Analysis
    Top View - The Domain Perspective
   Most domain modeling (also called conceptual or essential modeling) occurs during inception and
    elaboration.
   This phase is mostly about communication with the client, domain experts, and users.
      Establish common vocabulary
      Understand the business
      Understand the business environment
      Understand the existing system
      Where’s the payoff?
   The most important model here is usually the class diagram.
      Describe objects in the domain
      Assign attributes and responisibilities
      Model static relationships
   We often build simple top level use case models to identify the main use cases.
      Some model existing system
      Some model top level functionality
   Sequence models can be used to show interactions
   Activity Models can explain complicated use cases or algorithms
                                                                                                      158
                Data Dictionary
 Now’s also a good time to start a data dictionary to catch the
  suggestions that turn out to be too simple to be objects.
    It can help find details about your objects too.
    The data dictionary will contain simple data objects as well
     as structured data and may contain classes, but we will be
     documenting the classes in other ways so it’s not necessary
     to do it here.
    Start out simple, similar to a glossary, and add detail as you
     go along.
    When get to detailed design most of the work of data
     definition will be done
    There is no UML syntax for this

                                                                 159
            Finding the Objects
 Brainstorm
    Get the team together and start listing possible objects on
     the board.
    Nouns from the domain.
    Verbs too — some objects come from actions instead of the
     other way round. But think of them as things.
    Don’t criticize, just write everything down. Try to make
     everyone feel safe to make mistakes.
    Aim for high level objects
    Solicit ideas from users
    Get as many as possible and discard the extras later
    Think of objects as parts of the domain, forget what they do

 These objects will be the foundation of your work from now on.

                                                               160
 Responsibilities, Collaborators, and Attributes

 Each object should have at least one responsibility. (Verbs from
  the domain can indicate responsibilities.)
     This will be the main thing the object does or knows.
    Objects from the domain may not be as cohesive as later
     objects in programs.
    ―Knowing‖ is a perfectly good responsibility
 Some responsibilities will be too big for a single object to
  handle.
    ―Registration‖ can be a collaboration among objects
 Responsibilities imply attributes and vice versa.
     Reporting something implies having some data

                                                                 161
                    CRC Cards
 Class – Responsibility – Collaboration (CRC) cards are a good
  way to document your objects in the early stages.
 Add responsibilities to the CRC cards.
 Add collaborators and we can start thinking of class models with
  multiple classes.
    Collaborations imply relationships between classes
    Represent operational relationships rather than structural
    Select collaborators based on their responsibilities
 Some people write attributes on the back of the cards.
 Don’t worry about inheritance until later, unless something’s
  really obvious or the domain people force it on you.

                                                               162
                         A CRC Card

Class Name:        Account
Superclass:
Subclass:

        Responsibilities         Collaborators
  Know account number
  Know account balance
  Deposit funds
  Withdraw funds
  Report Balance




                                                 163
                    Another Example

Class Name:     Pizza
Superclass:
Subclass:

        Responsibilities                   Collaborators
Know Customer                   Customer
Determine Cooking Time          Crust, Toppings, Sauce
Determine Delivery Time
Compute its Price               Crust, Toppings, Sauce
Report Cooking Time and Price   GUI




                                                           164
                      Class Models
   It is usually worth while to build a top level class model for the domain,
    or the part of it that affects our work. There are several reasons
      Establish common vocabulary
      Help learn static structure of the domain
      Many of the objects will end up in code


   This diagram should model the most important objects in the university,
    and the static relationships between them, all based on the real world.


   We may also start modeling the individual classes, and these models
    will show the attributes and operations as we need or discover them.



                                                                            165
              Use Case Models
 We might build some domain-perspective use case models for
  the university.

 We are modeling existing processes which we intend to replace,
  and new use cases that the existing system does not handle.

 We will need a text narrative to define pre and post conditions,
  invariants, exceptions, and multiple paths. The narrative need
  not be as detailed as the one in the appendix.

 You may find that an activity diagram is a great help with a use
  case that has multiple branches in its flow.

                                                                 166
                         Other Models
   We may build state models of any objects that have complex state.
   If we model some use cases from the existing system we can look for an object
    to take the initial responsibility for each use case, along with collaborators to
    handle any parts the primary object cannot.
   It all changes with point of view.
      Student may view Registrar as having responsibility for scheduling course
      Registrar may view Department as having responsibility to schedule
       courses
   Business Rules could be considered requirements but can also be part of the
    domain.
   May consider:
      Activity models of complex processes
      Sequence and Collaboration models to show interactions
      Even Data Flow Diagrams

                                                                                   167
     Judging the Domain Model
   We’re doing this for the communication. The main criterion is how well
    we (the analysts and developers) are communicating with them (the
    client, the domain experts, and the users).
   Domain models need not follow our rules (coupling, cohesion, etc.) for
    design. If the domain expert describes a dread mess you grin and nod
    your head and model a dread mess. Your current goal is to
    understand, not to improve, what's there.
   Build only the models you need.
   Throw away models that are not important enough to maintain.
      The process of modeling is more important than the model
      Maintaining models is expensive
      Before throwing away make note of what you learned from the
        model

                                                                        168
Requirements and Specification
                         The Goals
 The main activity is . . . anyone? . . . yes, that’s right, it’s
  communication.


 There are two parts to this: the tasks that our new system must
  perform, and everything else.


     The tasks will include the data in and out, the actions
      performed by the user and the system, pre and post
      conditions, and whatever else we need to characterize the
      interaction between the user and the system.

                                                                     170
                 The Goals
 The rest of the requirements:
   Cost
   Completion Date
   Hardware/software interfaces, protocols, etc
   Hardware
   Security
   Performance
   Reliability
   Maintainability
   Tradeoffs among requirements allowed
                                                   171
      Understand the Problem
 In Domain Analysis we learned about the context and the
  background, and we built up a common vocabulary and
  understanding with the domain experts, the client, and the
  users. Now we will study the problem we are to solve, the
  system we are to build.


 There are several possible situations, You may be:
    Replacing an existing software system.
    Enhancing an existing system — this requires analysis too.
    Replacing an existing non-computer system.
    Doing something new.

                                                               172
             Specify a Solution
 The main model for specification is the Use Case. We may have
  already drawn some simple use case diagrams to help define the
  scope of the project. Now we will expand them and add others.
    Write narratives as you discover the material to put in it
    Activity diagrams helpful if a lot of branching
 Brainstorm with the client; ―What’s going to be most useful to
  you?‖ Brainstorm with the users; ―How can we make your jobs
  easier?‖
 Continue to work on the data dictionary. Add detail and entries.
 Continue work on the user manual you began earlier.
 Don’t forget the risk analysis and business case
 Go into detail only where useful
                                                              173
                     Prototyping
 Build prototypes of the user interface.


 A prototype helps our communication with users, client, and
  domain people.


 A prototype reveals missing specifications. ―Well, what happens
  when I do this, then?‖ or ―How do I get into the part about the
  payroll?‖

 A prototype finds hard parts in the communication between the
  program and the user.

                                                                174
                  Prototyping
 Can substitute for a lot of detail in the use case
 Dummy screens without functionality
 Keep refining the prototype until the user is excited
  about it
 Prototype code at this point may not end up in the
  final product
 Prototypes can raise user expectations to believing
  that it’s almost done



                                                          175
            The Complex User
 Don’t neglect the parts of the user that a Use Case cannot
  model.
 The user may be a little deeper than the single (and simple)
  minded cardboard cutout actor that a use case models. The
  user has other concerns than just registering for a course.
    Can I get in a section around my work schedule
    Can I get a schedule that works with my girlfriends schedule
    Can I get a schedule so that I don’t have an early morning
     Friday course (Thursday night at Tiff’s!)
 One way to represent these things is to model the user as an
  object with volition and complex mental state. In other words,
  as an agent.
 There may be atypical users.

                                                               176
                  Other Models
 Activity diagrams are often included in use cases to describe
  complex paths through the operations.
 State charts can be used here to describe objects with complex
  state.
 Interaction diagrams are used infrequently to model interactions
  between our system and other parts of the business, or between
  parts of our system.
 The class diagrams from domain analysis are useful here.
 The user manual is another type of model of the system
 Prototypes, use case models, and the user manual may have a
  great deal of overlap of contents
    Don’t duplicate effort but…
    Do need to communicate well

                                                               177
Judging the Requirements Model
 A Requirements Model
     Must be clear and easily understandable by all concerned.
     Must offer the client and the users the information they need
       to decide whether this is the system they want.
     Must be self consistent.
 How can you tell? How do you test it?
     Review it (with the users and the client of course).
 Are the requirements models and documents understandable to
  the users and the client? Do they agree?
 Do the requirements specify only what needs to be done and not
  how it needs to done?
 Do any of the requirements lack needed detail?
 Have we noted areas likely to change?
 If information wasn’t available when will it become available?
                                                                178
Design of Objects
                         Design
 The primary tasks in Object Oriented Design are the selection of
  objects and the allocation of data and operations among them.
  (Factoring)
     Make public object interfaces narrow and clean
     Do not expose implementation
     Do not expose the data
 The design of the code inside an object is governed by
  traditional rules of Structured Design. (Coupling and cohesion)
 Next comes the allocation of permanent links among the
  objects.
 Finally the dynamic structure of the interactions among them
  pretty much emerges on its own.

                                                               180
                     Design
 Start with good objects and figure out interactions
   More flexible and adaptable
   If interactions become too complex, redesign
     objects involved
 Good structure, simplicity at each level, and
  readability yield:
   Code that isn’t there can’t have a bug
   Code that isn’t there is very quick to right
   Code that isn’t there takes not time to understand
   Code that isn’t there executes quickly

                                                     181
                      Factoring
 Factoring is breaking the system into modules and determining
  their boundaries.
 The first consideration is the Law of Least Astonishment. Do
  the reasonable thing. Make your objects logical and cohesive
  and true to their (carefully chosen) names. Put in them what a
  reasonable programmer would expect to find there.
 Locate an operation or method with the data it needs.
 Locate an attribute with the methods that need it.
 Keep cohesion high by giving objects only what truly belongs to
  them
 Keep coupling low by keeping objects as independent as
  possible
 Balance cohesion with coupling
 Simplify – small, simple cohesive modules

                                                               182
                Encapsulate
 Difficult decisions in objects – e.g. data structures
 Foreseeable change – if one object may change for
  two different reasons, maybe make two objects
 Things the client thinks may change
 Things you think may change




                                                      183
   Design of Software Objects
 Some teams use CRC cards in design to find the objects and to
  represent them with their responsibilities, attributes, etc. To play
  their roles in realizing the use cases.
 Responsibilities can come from the object itself and from the
  needs of the system.
     What goes with the objects nature
     Will generally change operations more than responsibilities
 Note that having a responsibility as perceived by the rest of the
  program and being able to do all of the work involved (or even
  any of the work) are separate – e.g. persistence.

                                                                   184
                     Features
 The public features of an object should be complete
  and primitive.
 The features of an object are complete if the object
  offers all the services that are needed by the code
  that uses it and that should reasonably belong to this
  class; that are part of the central responsibility of this
  class.
 The features of an object are primitive if each one is
  highly cohesive, no two operations overlap in
  functionality, and there are as few operations as
  practical.

                                                          185
                   Methods
 Methods should be short and simple and should
  delegate complication to other methods.
 Names are very important.
 Watch for methods that call other methods from a lot
  of other classes – best for a method to call other
  methods from as few other classes as practical.
 Stamp out duplicated code!
 If a method gets a lot of its data from some other
  class perhaps it belongs in that class.
 Shorter argument lists are usually better.

                                                     186
             Cohesion of Objects
   Cohesion applies to Objects themselves as well as their methods. An
    object should do or represent a single thing. It can have several
    responsibilities but they must each be appropriate to that thing.
      Keep objects small
      Cohesion is judged by its public interface and not by its
       implementation
   Mixed Instanced Cohesion describes a class that has a feature which
    is undefined for some instances of the class. Avoid it.
      A Car class could contain both a location and an amortization
       schedule.
      May use inheritance to have a location car and an amortization car



                                                                       187
    Coupling Between Objects
 In structured design we thought of coupling as how much one
  routine has to know about another to use it: the coupling
  between a function and another function it calls.
    Quality of coupling refers to how much one object depends
      on another for its functioning
    Quantity of coupling refers to how many other objects are
      needed
 The quality of coupling is the interdependence between modules
  that might make it necessary to change one of them in response
  to some change in the other. OOD allows new kinds of
  coupling. It comes in many forms and degrees.
 We can reduce coupling by eliminating unnecessary
  relationships between objects and by making the necessary
  relationships looser.


                                                             188
                    Coupling II
 If your language supports it, do not allow subclasses direct
  access to the private implementation of their superclasses. If
  you make them go through the public functions like anyone else
  then they are not affected by changes to that implementation.



 In a large system we identify subsystems and document them
  as packages.



 If you use the C++ friend syntax it breaks your encapsulation.


                                                               189
                       Inheritance
   As you work on the design look for inheritance relationships – kind of
   When overriding a method from an ancestor class you must ensure that
    your method does (logically) exactly what the method you are
    overriding does.
   Design for Polymorphism – what are the signs?
      A set of things that inherit from a common ancestor
      A set of different type things that you’d like to manage the same –
        e.g. checking, savings, and money market accounts
      A set of different type things that have a common interface – e.g.
        printable
      Large CASE statements that switch on a type
   Be alert for chances to simplify an inheritance hierarchy.
   Be alert also for a reason to move attributes and methods up or down
    an inheritance hierarchy.


                                                                       190
                           Contracts
   In order to do its job a method may have expectations about the state
    of the world or its arguments.

   The code that calls the method has expectations about what the routine
    does, and perhaps about the state of the world after it’s done.

   Preconditions are what the routine expects to be true when it is called,
    possibly including the values of its arguments if any.

   Post conditions are what the calling code expects after the routine
    has completed.
   Invariants are statements that are true at all times from the point of
    view of the calling code.

                                                                             191
            Enforcing Contracts
 It’s useful to think about pre and post conditions and invariants.


 Some languages have built in support for Programming By
  Contract (PBC). Eiffel for example. Other languages do not.


 C and C++ have assertions and C++ and Java have exceptions
  that are very useful for enforcing contracts.


 In our class models we can represent these pre and post
  conditions and invariants as text notes (a box with the upper
  right corner turned down) or as {constraints} in curly braces.

                                                                   192
      Inheritance and Contracts
   A subclass must fulfill the contracts agreed to by its superclass(s) and
    interfaces.
   An overriding method in a subclass must have the same or looser
    preconditions and the same or tighter post conditions than the method
    it overrides. Invariants must be exactly the same.
   The Liskov Substitution Principle states that if a function takes a pointer
    or reference to an object of class C as an argument it must also accept
    a pointer or reference to any object derived from C without knowing the
    difference.
       The program must compile
       The function called must do essentially the same thing no matter
         which object is passed
       Any two methods that have the same name should do logically the
         same thing

                                                                            193
System Design
                           Design
 Object Oriented Design (OOD) is not as mature as Structured
  Design. It’s a little more of an art, a little less susceptible to
  formal process. However, it still seems to work better.
 Remember the goal of keeping coupling low.
 As the system grows and changes, as the requirements change
  and we add new use cases and change old ones, we often find
  that the structure we built to serve an earlier system is
  inadequate or misleading. Then we refactor.
 Interactions are driven by the objects themselves, use sequence
  and collaboration diagrams to help flesh out the interactions
 Don’t design past the point where you should be proving the
  design with code – don’t overdesign!


                                                                       195
                   A Few Rules
 Don’t Repeat Yourself.
    If you have the same operation in two places figure out how
     to do both with the same code, factor it out into a function
     and call it twice.
    Don’t write comments that repeat what is in the code
    Replace duplicate literals with variable names

 Keep different things separate.
    For instance, the UI and the rest of the program.

 Design for Maintenance
    70% or so of the cost of a typical big system goes for
     maintenance.

                                                               196
                 Object Creation
 The dynamic (run-time) creation of objects is a special
  responsibility that has special considerations and produces a
  special kind of coupling between the creator and the created.
     It’s better to put that special coupling where there is already
      strong coupling.
 Object A should have the responsibility to create object B if: (in
  order of importance)
     B is part of A (composition or aggregation).
     A owns the container that stores B
     A is the main user of B
     A has the data to initialize B
 If an object has to be explicitly killed think first of its owner.


                                                                   197
                 Class Models
 Start with your class models from the Domain.
 Revise the objects from the domain for more cohesion and less
  coupling.
 Re-think the distribution of data and responsibilities.
 Look for duplication of function and data.
    Even though the real world contains much duplication,
     doesn’t mean our software should
 Reduce the number of links between classes as much as
  practical.
    Try to remove all bidirectional links
 Make classes simple, clear, understandable, and reasonable

                                                             198
          Interaction Diagrams
 The structure of these interactions is primarily driven by the
  responsibilities and the operations and attribute in the objects.
    The nature of the objects dictates their interactions – do
      objects first and let interactions fall out
 The interaction diagram does drive the links between objects
  (the kinds of links, not the syntax). Sometimes the interaction is
  more complex to save links.
    Hard links are knowledge, i.e., attributes, i.e., coupling.
    If the interaction diagram shows too much interaction
      between two many objects it implies too many links.
 Cohesive objects more important than too many links

                                                                  199
            Printing the Catalog
 We will figure out how our system will perform this use case,
  what messages pass between which objects carrying what data.
  We may discover omissions and errors from previous steps.


 The actor who initiates the use case is the university secretary.

 What object has the responsibility to print the catalog? If you
  look at the object models from the Design of Objects chapter
  and you won't find one.

 Can the university object do this by itself?

                                                                    200
Printing the Catalog




                       201
          Printing the Catalog II
 What about this alternate plan? Here the university gets the
  information from the courses one at a time and prints the entries

 The main objection is that the university is the king object and
  everyone else just stores data. This sort of solution occurs often
  among designers who are new to objects.

 It’s generally better to push responsibilities and parts of
  responsibilities down the chain as far as is reasonable.

 Here the university calls the department to get a pointer to a
  course so it can send a message to the course for its
  information

                                                                   202
Printing the Catalog II




                          203
         Printing the Catalog III
 Here’s the collaboration model equivalent to the first sequence
  diagram.

 It’s common for the code to differ from these models in physical
  detail.

 For that matter, it’s common for it to differ logically at any level.

 The second collaboration diagram shows mostly that it is easier
  to represent iteration of a set of messages on a sequence
  diagram.

                                                                      204
Printing the Catalog III




                           205
Printing the Catalog III




                           206
                           Links
 In order for these messages to pass there must be links
  between the objects. The sender of the message must know
  the address of the receiver.

 In the diagram on the facing page, there are arrows on the links
  from University to Department and from Department to
  Course to accommodate the messages we used to print the
  catalog (the first version of the diagrams).

 In the class models we showed the registration information in
  the Course. What does this imply about the link between
  Course and Student?

                                                                  207
Links




        208
                         Links II
 The links we talked about on the previous page were
  composition and aggregation. Links can also be based on
  association in similar fashion.
 Another kind of link exists between any object and a global
  object that is named in the program rather than being allocated
  dynamically. Any code can send a message to such an object –
  not a desirable situation!
 A temporary link is created when an object (baz) gets a pointer
  or a reference to another object (qux) as an argument to an
  incoming message or as a return from an outgoing message.
  The object baz can now send messages to qux and then may
  not use the link again.

                                                              209
Refactoring
                    Refactoring
 Refactoring is changing the structure of a running program
  without changing its operation.

 Object Oriented Programming makes Refactoring possible
  (practical).

 Refactoring makes lightweight processes possible.

 Lightweight processes help us deal with the specification (bad,
  changing, misunderstood) problems, early mistakes in design,
  and lots of other human frailties.
 Good OO design makes it possible to make local changes
  without blowing things up.


                                                                211
                Clues and Cues
 The most important thing is to develop an aesthetic sense that
  will tell you when the structure is going bad.

 One of the most important signs is duplication – data and/or
  functions

 Refactor when you start to add a new feature and realize that
  the present design will make it awkward.

 Refactor to clarify the code. Make it easier to figure out next
  time.

 Refactor as part of a code review.

                                                                    212
                How to Refactor
 Refactoring depends on good tests.
    Test before and again after refactoring

 Take small steps, as small as you practically can and still get to
  working code. Test after each step.

 If your tests do not give you confidence that they will catch any
  mistake you make while refactoring, fix the tests first.

 It’s important to have a test system that runs all your tests
  automatically and returns good or bad, so you that you don't
  have to compare results with what’s expected.

                                                                  213
  A Few Refactoring Patterns
 Move Method – A method uses more data and
  methods from another class than from its own.
 Move Attribute – An attribute is used more often by
  methods of another class than by those of its own.
 Extract Class – A class has become complicated and
  seems to have divergent responsibilities.
 Inline Class – A class doesn’t seem to have enough
  to do.


                                                        214
  A Few Refactoring Patterns
 Hide delegate. An object (the client) needs something
  from another object (the server). The server returns a
  reference to a third object and the client uses the
  third object. Hide the source of the third object from
  the client.
 Remove Middle Man. Opposite of Hide delegate. If
  there is a lot of interaction between client and third
  object, then remove the middle man.



                                                     215
                       Summary
 UML Diagrams
    Activity Diagrams
    Collaboration Diagrams
    Sequence Diagrams
    State Diagrams
    Static (Class) Diagrams
    Use Case Diagrams
 UML process
    Inception – Domain analysis
    Elaboration – Requirements and Specification
    Construction – analysis, design, code, test iterations
    Transition – Training and implementation

                                                              216

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:40
posted:7/22/2011
language:English
pages:216