Friday, January 26, 2018

Domain Modelling and GRASP theory




Domain Modelling

  • The next step after developing use cases is to model the domain.
  • Purpose: to make a model that decomposes the problem and communicates
the important terms and how they are related.
  • Conceptual model of the real world, not of the software,
    • no software classes at this point in the modelling process.
  • Represented with (subset of) UML Class diagram notation.
  • Domain model shouldn’t contain,
    • software artifacts such as interface windows, database or responsibilities
                    or methods.



Conceptual Class
Identify classes as things, ideas, or objects in the problem domain, in terms of
symbol : word (or image) to represent the concept
intention : definition of what it is
extension : examples or properties which define the concept
For example: the concept Sale
Symbol  : sale
Intention : Sale represents a purchase transaction and has a date, time,
item and amount
Extension: examples of sales


Screenshot_2017-01-19_02-09-41.png




Process of Domain Modelling
  1. Identify concepts
  2. Draw a domain model (in simplified class diagram)
  3. Add associations to record relationships
  4. Add attributes for information required
Identify concepts from noun and noun phrases in the descriptions of the problem,
in the requirements document and use cases.


Screenshot_2017-01-19_02-12-01.png

Screenshot_2017-01-19_02-12-50.png

Keep only useful Classes
  • Redundant classes: If two classes express the same concept, remove one
(use most descriptive name)
  • Irrelevant classes: if class has little or nothing to do with domain remove it
  • Vague classes should be avoided
  • Implementation constructs shouldn’t be included


Flight Example
Screenshot_2017-01-19_02-15-14.png

Specification Concepts
Imagine the following scenario in a sales system:

An Item instance represents a physical item in a store; as such, it may even
have a serial number. 

An Item has a description, price, and itemID, which are not recorded anywhere else.

Every time a real physical item is sold, a corresponding software instance of 
Item is deleted from the system.

There is strong demand for the popular new vegetarian burger – ObjectBurger.
The store sells out, implying that all Item instances of ObjectBurgers are deleted 
from computer memory.


  • Now, If someone asks, “How much do ObjectBurgers cost?” no one can
answer, because the memory of their price was attached to inventoried
instances, which were deleted as they were sold.
  • Notice also that, if implemented in software as described, objects duplicate
data because the description, price, and itemID are stored for every Item
instance of the same product.


  • This suggests a need for specification classes: A XSpecification class
describes a class X.
Screenshot_2017-01-19_02-17-17.png

Screenshot_2017-01-19_02-18-05.png


Screenshot_2017-01-19_02-18-24.png


Screenshot_2017-01-19_02-18-40.png
--------------------------------------------------------------------------------------------------------------------------------



Assigning Responsibility


Responsibility


Responsibility is an obligation required of an object;
(A contract/obligation that a class/module/component must accomplish.)
two types:


  • doing  / behaviour
    • doing something itself, such as creating an object or doing a calculation
    • initiating action in other objects
    • controlling and coordinating activities in other objects


  • knowing / knowledge
    • knowing about private encapsulated data
    • knowing about related objects
    • knowing about things it can derive or calculate


Responsibilities and Interaction Diagrams


(Interaction Diagrams : All other Behavioural Diagrams except Use Case Diagram)


Interaction diagrams show choices in assigning responsibilities to objects
E.g. Sequence diagram shows that Sale objects have been given a
responsibility to create Payments.




GRASP - General Principles for Assigning Responsibility Patterns


Name chosen to suggest the importance of grasping fundamental principles to
successfully design object-oriented software.


Set of 9 simple design principles stated as patterns.
1. Information Expertwho is responsible?
2. Creator who creates object?
3. Low Coupling favour low dependency between objects
4. High Cohesionclass has moderate responsibilities in one functional area
5. Controlerwho should be responsible for handling an input system events?
6. Polymorphism who, when behavior varies by type?
7. Pure Fabrication service class made up to achieve low coupling, high cohesion
8. Indirection assigning responsibility of mediation to avoid coupling
9. Protected Variationprotects elements from the variations on other elements

  1. Information Expert : what class must accomplish it/ who is responsible


Problem: What is a general principle for assigning responsibilities to objects?


Solution: Assign a responsibility to the information expert, that is, the class that
has the information necessary to fulfill the responsibility.


Example: (from POS system) Who should be responsible for knowing the
grand total of a sale?


Start with domain model and
look for associations with Sale.
What information is necessary to calculate grand total and
which objects have the information?


Calculating Total….


From domain model can see that Sale contains SalesLineItems so it has
information necessary for total… (quantity)


Assign responsibility getTotal() to Sale




Benefits :
Encapsulation; low coupling
Distributes behaviour across classes with required info

Assign responsibility getSubTotal() to SalesLineItem


  1. Creator : who create object / who must instantiate object


Problem : Who should be responsible for creating a new instance of a class?
Solution : Class B has responsibility to create instance of class A if
B aggregates A objects / B depends heavily on A
B contains A objects
B records instances of A objects
B closely uses A objects
B has the initialising data for A / necessary information to instantiate A


Example: (from POS system) Who should be responsible for creating a new
SalesLineItem instance?

Start with domain model


Since a Sale contains SalesLineItem objects it should be responsible according
to the Creator pattern.







Sequence Diagram for create




Design Patterns : Factory, AbstractFactory


  1. Low Coupling : favour low dependency between objects / how to
minimize dependencies between classes


  • Assign responsibilities taking care of not to increasing coupling, but
“Zero coupling” is impossible.


  • Problem: How to support low dependency, low change impact, increased reuse?


  • Solution: Assign a responsibility so coupling is low or to minimize coupling.


What is coupling
  • Coupling is a measure of how strongly one element is connected to,
has knowledge of, or relies on other elements.
  • A class with high coupling relies on many other classes – leads to problems:
    • changes in related classes force changes (ripple effect)
    • harder to understand in isolation
    • harder to reuse
    • but excessive de-coupling also causes problems!


  • Concept of coupling (or dependency) was originally developed to assess
the degree to which each program module relies on each one of the other
modules.
– for Structured Design (Stevens, Myers & Constantine,1974)


From high coupling to low coupling
Content : one module modifies (or relies on) the internal workings of another module
Common : two modules share the same global data
Control : one module controlling the flow of another
Stamp : modules share a composite data structure and use only in part
Data : modules share data through, for example, parameter passing
Uncoupled : modules do not communicate


Coupling in Object Oriented Design
Examples of coupling in object-oriented design and programming languages
(adapted from Larman):
Class X has an attribute of Class Y
Class X calls on services of a Class Y object
Class X has a method that references an instance of Class Y
Class X is a subclass of Class Y
Interface Y, and Class X implements the interface


Who is responsible for payment
Example (from POS system)
Consider Payment, Register, Sale.
Need to create a Payment and associate it with a Sale, who is responsible?


Option 1:
Creator: since a Register “records” a Payment it should have this responsibility.
Register creates Payment p then sends p to a Sale => coupling of Register
class to Payment class.



Option 2:
Register requests Sale to create the Payment.


In both cases a Sale needs to know about a Payment.
However a Register needs to know about a Payment in first but not in second;
Option 2 is preferred.
15991579_1828334334056102_1037264714_o.png




  1. High Cohesion


Problem: How to keep complexity manageable?


Solution: Assign the responsibility so that cohesion remains high.

What is Cohesion
Cohesion is a measure of how strongly related and focused the responsibilities
of an element (class, subsystem, etc.)
Problems from low cohesion (similar to problems with high coupling):
hard to understand
hard to reuse
hard to maintain
fragile, easily affected by change


Like Coupling, Cohesion also developed originally for structured design
(Stevens, Myers & Constantine, 1974)

From best (high) cohesion to worst (low) cohesion
Functional : parts are grouped because they all contribute to a single well-defined task
Sequential : parts are grouped because the output from one part is the input to another
Communicational : parts are grouped because they operate on the same data
Procedural : parts are grouped because they always follow a certain sequence of execution
Temporal : parts are grouped by when they are processed at particular time
Logical : parts are grouped because they logically are categorized to do the same thing
Coincidental : parts are grouped arbitrarily



Coupling and Cohesion
Coupling and Cohesion are related



  1. Controler


Problem: Who should be responsible for handling a system event?


Solution: Assign the responsibility for receiving and/or handling a system event to
one of following choices:
РObject that represents overall system, device or subsystem (fa̤ade
  controller)
– Object that represents a use case scenario within which the system
  event occurs (a Use Case Handler)


  • Input system event is event generated by an external actor associated with
a system operation.
  • Controler is a non-UI object responsible for receiving or handling a system event
РControler class is often some kind of fa̤ade into the domain
  (application) layer from the interface (boundary) layer

What is System Class?
“System” class in System Operations represents system-level operations
E.g. System class for POST System


No class called system so the controller class is assigned responsibility for
system-level operations.


Controlling Input
Input events might come from
– GUI operated by a person, or
– call from a telecommunications switch, or
– signal from a sensor,


Be careful to NOT give Controlers too much responsibility
E.g. from Java EE






What is a Controller?





Controller
  • UI objects and presentation layer should not have responsibility for
fulfilling system events.
  • Problem of bloated controllers.
    • single controller class handling all system events
  • Controller is a façade into domain layer from interface layer.
  • Controller coordinates activity but delegates work to other objects rather
than doing work itself.
  • Façade controller representing overall system; use when there aren’t many
system events.
    • Otherwise use case controllers – different controller for each use case

Facade Controller




Analysis Classes
Such controller classes are sometimes called analysis classes and can be
identified after use-case analysis.
For example.
Suppose we have an application corresponding to a sports tournament.
Which is better:
champ.enterChampionship(Player p)
or
player.enterChampionship(Championship c);


Essence of the idea is:
Encapsulate the business functionality into a separate interface:
ChampionshipManager
Make persistent business data reuseable: Player


ChampionshipManagement mngr;
mngr.enterChampionship(Championship c, Player p);
Similarly, the GUI handler code is dealt with by a separate classs: Instead of
championship.enterButtonClicked(Event e)
or
manager.enterButtonClicked(Event e)
Encapsulate user interfaces into separate classes: PlayerEnterChampForm
These analysis classes can be identified after use-case analysis and are
sometimes written with the following notation:




Rules of Thumb for Analysis Classes
Structural restrictions for analysis classes
Entity: only attributes (+get/set/find methods)
Control: only methods: (at least) one method / UC
Boundary: both attributes and methods


Relationship between analysis classes (Layers)
Actors access only boundaries
One boundary class for each Actor-UC relation
Entities are only accessed by control objects
Control objects may communicate with all entities, boundaries,
and control objects

  1. Polymorphism


Problem: Who handles alternatives based on types?


Solution: When alternate behaviours are selected based on the type of an object,
use polymorphic method call to select the behaviour, rather than using if statement
to test the type.


  • Polymorphism is a property of object-oriented software by which an abstract
operation may be performed in different ways in different classes.
“Giving the same name to services in different objects”
  • Exists when several classes that each implement the operation either have
a common superclass in which the operation exists, or else implement an
interface that contains the operation.


authorise() example
Since the behaviour of authorizing varies by the type of payment – cash, credit
card or check, we should assign responsibility for authorizing to each subclass.


Easier to add additional behaviours (new payment methods) later on.






  1. Pure Fabrication


Problem: To not violate High Cohesion and Low Coupling?


Solution: Assign a highly cohesive set of responsibilities to an artificial class that
does not represent anything in the problem domain, in order to support high
cohesion, low coupling, and reuse.


  • High cohesion is supported because responsibilities are placed in a class
that only focuses on a specific set of related tasks

  1. Indication


Problem: To avoid direct coupling?


Solution: Assign the responsibility to an intermediate object to mediate between
other components or services, so that they are not directly coupled.


Sales to database example
Suppose, in POST example, we want to save Sale instances in a relational
database. By Information Expert, there is some justification to assign this
responsibility to Sale class. However...
  • Task requires a relatively large number of supporting database-oriented
operations and the Sale class would lack cohesion; and Sale class has
to be coupled to the relational database increasing coupling.
  • Saving objects in a relational database is a very general task for which
many classes need support so create new class.
  • This is both an example of Pure Fabrication and assigning responsibilities
to support Indirection.


PersistentStorageBroker
The Sale remains well designed, with high cohesion and low coupling
  • The PersistentStorageBroker class is itself relatively cohesive
  • The PersistentStorageBroker class is a very generic and reusable object




  1. Protected Variation


Problem: How to design objects and systems so that variation or instability in
these elements dies not have an undesired impact on other elements.


Solution: Identify points of predicted variation or instability; assign responsibilities
to create a stable interface around them.


Interface in the broad sense; it doesn’t have to be an interface in Java interface
sense.


Protected variation first described by A. Cockburn (1996)

Example : The Law of Demeter


Examples of Protected Variation include Polymorphism and Information Hiding
(Parnas)


Another example (which was given as one of the GRASP Patterns in the
1 st ed. of Larman) is Don’t Talk to Strangers or The Law of Demeter
(Lieberherr, Holland and Riel, 1988)


Problem: To avoid knowing about the structure of indirect objects?


Solution: If two classes have no other reason to be directly aware of each
other or otherwise coupled, then the two classes should not directly interact.

Don’t talk to strangers
It states that within a method, messages should only be sent to the
following objects:
this/self object
parameter of the method
attribute of self
element of a collection which is an attribute of self
object created within the method

Payment Example
Assume POST instance has an attribute referring to Sale, which has an
attribute referring to a Payment
and POST has an operation paymentAmount which returns the amount
tendered and Sale has payment operation that returns Payment instance




Violates Law





Supports Law




Screenshot_2017-01-19_02-02-51.png



Another example to Law of Demeter




Law of Demeter is also known as “Principle of least knowledge”.
This helps low coupling.


Here, the Teacher want to have some water. Teacher doesn’t directly get Water.
Student has the WaterBottle. WaterBottle has Water. So, Teacher calls Student
to bring some water.


If Teacher object want to call a method of Water, it doesn’t call to Water
(the stranger)  directly, the Teacher only know about Student object,
Student knows about WaterBottle, and WaterBottle knows Water. WaterBottle
calls Water’s getWater()  method, and Water will return some water to
WaterBottle, WaterBottle will return that to Student object and Student will
return it to Teacher. Now Teacher has some water.

CRC Cards - Class Responsibility Collaboration Cards


  • Class-responsibility-collaboration (CRC) cards are a brainstorming tool
used in the design of object-oriented software.
  • CRCs are suggested as a viable alternative to UML sequence diagram
to design the dynamics of object interaction and collaboration.
  • CRC cards are usually created from index cards.
Members of a brainstorming session will write up one CRC card
for each relevant class/object of their design.
  • The card is partitioned into three areas
  1. On top of the card, the class name
  2. On the left, the responsibilities of the class
  3. On the right, collaborators (other classes) with which this class
interacts to fulfil its responsibilities


  • Using a small card keeps the complexity of the design at a minimum.
  • It focuses the designer on the essentials of the class and prevents
her/him from getting into its details and inner workings at a time when such
detail is probably counter-productive.


  • It also forces the designer to refrain from giving the class too many
responsibilities. Because the cards are portable, they can easily be laid
out on a table and re-arranged while discussing a design with other people.


Screenshot_2017-01-11_13-04-38.png

Past Exam Questions
2014 OOD Question 3 (batch-2)
Screenshot_2017-01-10_18-11-30.png
2015 OOD Question 3 (batch-3)
Screenshot_2017-01-10_18-13-36.png


2016 OOD Question 3 (batch-4)
Screenshot_2017-01-10_18-11-30.png
Vocabulary

Screenshot_2017-01-19_02-37-33.png

No comments:

Post a Comment