software designheracleia.uta.edu/~sharifara/5324/7_design.pdfassigning responsibilities to objects?...
TRANSCRIPT
Software Design
CSE 5324, Summer 2017
Outline
• What and Why?• What is a Good Design?• Design Concepts• The GRASP Approach
CSE 5324, Summer 2017, Ali Sharifara 2
What is it?
• A plan or blueprint about how to build a software system or component
• In essence, it is an abstraction that captures important decisions about how to build software.
3CSE 5324, Summer 2017, Ali Sharifara
Why?
• Can we construct a building without a blueprint?
• One of the essential approaches to dealing with complexity
• Facilitates communication among team members
• A crucial document that allows a system to be understood by other people
4CSE 5324, Summer 2017, Ali Sharifara
What is a good design?
• A good design should be functionally correct, efficient, robust, easy to understand, easy to maintain, easy to extend, easy to use, …
• Given two designs, how to determine which one is better than the other?
5CSE 5324, Summer 2017, Ali Sharifara
FURPS
• Functionality: Feature set, and capabilities • Usability: Aesthetics, consistency,
documentation• Reliability: Robustness, mean-time-to-failure,
accuracy of output• Performance: Processing speed, response
time, resource consumption, throughput.• Supportability: Maintainability, testability,
configurability, compatibility
6CSE 5324, Summer 2017, Ali Sharifara
Coupling
• Coupling refers to links between different components.
• Two components are tightly coupled if they depend closely on many details of each other.
• A good design aims for loose coupling.– Understand one component without reading others– Change one component without affecting others.
7CSE 5324, Summer 2017, Ali Sharifara
Coupling (Example)
8CSE 5324, Summer 2017, Ali Sharifara
Loosely Coupled Some Dependencies
Highly Coupled Many Dependencies
Cohesion
• Cohesion refers to the the number and diversity of tasks that a single component is responsible for.
• A component has high cohesion if each component is responsible for one single logical task.
• A good design aims for high cohesion– Easier to understand what a component does– Easier to give descriptive names– Easier to reuse a component
9CSE 5324, Summer 2017, Ali Sharifara
Coupling Vs. Cohesion
10CSE 5324, Summer 2017, Ali Sharifara
Design for Changes
• Try to anticipate what changes are likely to be made in the future.
• Open-Closed Principle: Software entities should be open for extension, but closed formodification.– Design in a way so that new features can be
added without changing existing components.– If you have to change existing components, the
changes should be minimized and contained.
11CSE 5324, Summer 2017, Ali Sharifara
Making Choices
• Constantly making choices between different design alternatives
• Knowledge and experience make a huge difference.
• No one makes perfect design decisions up front.
• Be careful if a decision is difficult to change; otherwise do not spend too much time on it.
12CSE 5324, Summer 2017, Ali Sharifara
Abstraction
• A fundamental approach to dealing with complexity– Focus on essential information while ignoring
less important details(hiding implementation)
• Procedural abstraction describes what a procedure does, instead of how Input/output parameters, pre-/post-conditions, side effects, exceptions
• Data abstraction describes how a data object is used, instead of how it is represented
13CSE 5324, Summer 2017, Ali Sharifara
Separation of Concerns
• A concern is a feature or behavior that is specified as part of the requirements model.– Presentation, computation, business
process, data storage, security, concurrency, and others
• Essentially, a divide-and-conquer strategy to reduce complexity– Easier to solve a complex problem when you
break it into smaller problems.
14CSE 5324, Summer 2017, Ali Sharifara
Modularity
• Software is divided into a set of componentsthat can be developed independently and then plugged together.– Each module should have a well-defined interface,
high cohesion, and should be relatively independent from other modules
• The single attribute that allows software to be intellectually manageable– Easier to develop, test, debug and maintain
15CSE 5324, Summer 2017, Ali Sharifara
Information Hiding
• Information should be exposed to the outside only if it is necessary
• In particular, interface should contain as little information as possible– Design decisions, e.g., specific data representation, that are
subject to change should be hidden from interfaces
• Helps to localize changes, i.e., a component can be modified with no or minimal changes to other components
• Separate interfaces from implementations – Clients know only interface, not implementation– Implementations know only interface, not clients
16CSE 5324, Summer 2017, Ali Sharifara
Information Hiding
17CSE 5324, Summer 2017, Ali Sharifara
Refinement
• Details are added into a design in a sequence of steps
• A process of elaboration that reveals low-level details as design progresses
• Complementary to abstraction, which suppresses information about low-level details.
18CSE 5324, Summer 2017, Ali Sharifara
Refactoring
• The process of changing a software system to improve its internal structure without changing its external behavior
• Refactoring:– Redundancy, unused design elements,
inefficient algorithms, poorly constructed data structures, components that are not cohesive, and others.
– Cleaning up the mess
19CSE 5324, Summer 2017, Ali Sharifara
Refactoring - Example
20CSE 5324, Summer 2017, Ali Sharifara
1- The mess:It is unclear what is connected to what, how.2- Lines straightened up:
Making the connections between different parts more clear.3- Re-organization of parts:
Removing crossing lines and making clear how the path from A to B can be4- More clarification:
Knowing the path from A to B, we can make it more clear.5- Reduction and simplification:
Maybe we can even remove steps between A and B, for instance by refactoring the parts into one single object.6- The ultimate connection:
A straight line from A to B
Speculative Generality
• Good idea to design for the future, i.e., not only for the present.
• This, however, does come with a cost, and a balance needs to be maintained.
• Two principles: Build it now or when it is needed ?– Only design for changes that have a reasonable chance to
occur– What is the cost, if we do not build it now?
21CSE 5324, Summer 2017, Ali Sharifara
Speculative Generality - Example
22CSE 5324, Summer 2017, Ali Sharifara
Responsibility-Driven Design
• Think of software objects as similar to people with responsibilities who collaborate with other people
• Responsibilities are not the same as methods. Methods fulfill the responsibilities.– Small responsibilities may be implemented by only
one method• Example : responsibility to “create a sale”
– Big responsibilities can take hundreds of classes and methods.
• Example : responsibility to provide “access to relational databases”
23CSE 5324, Summer 2017, Ali Sharifara
Responsibilities Example
• The Sale class might define a method to know its total; say, a method name getTotal()
• To Fulfill that responsibility, the Sale may collaborate with other objects, such as sending a getSubtotal message to each SalesLineItem object asking for its subtotal
24CSE 5324, Summer 2017, Ali Sharifara
Types of Responsibilities (for objects)
• Doing responsibilities:– Doing something itself– Initiating action in other objects– Controlling and coordinating activities in other
objects• Knowing responsibilities
– Knowing about private encapsulated data– Knowing about related objects– Knowing about things it can derive or calculate
25CSE 5324, Summer 2017, Ali Sharifara
What is GRASP ?
• General Responsibility Assignment Software Patterns (or Principles)
• A collection of general objected‐oriented designpatterns related to assigning defining objects.
• GRASP helps us in deciding which responsibilityshould be assigned to which object/class.
• Define blueprint for those objects – i.e. class with methods implementing those responsibilities.
26CSE 5324, Summer 2017, Ali Sharifara
The GRASP Approach (Pattern)
• GRASP Design Patterns :– Creator– Information Expert– Low Coupling– Controller– High Cohesion– Polymorphism– Pure Fabrication– Indirection– Protected Variations
27CSE 5324, Summer 2017, Ali Sharifara
Creator
• Problem: – Who should be responsible for creating a new
instance of some class?– Assigned well, the design can support low coupling, increased
clarity, and reusability.
• Solution: – Assign class B the responsibility to create an instance of
class A if one of these is true• B “Contains” or compositely aggregates A.• B records A• B closely uses A• B has the initializing data for A that will be passed to A when it
is created. (Thus B is an Expert with respect to creating A.)
28CSE 5324, Summer 2017, Ali Sharifara
Creator – Example #1
29CSE 5324, Summer 2017, Ali Sharifara
NextGen POS: who should be responsible for creating a SalesLineItem instance? • By Creator, look for a class that aggregates, contains SalesLineItem
instances.
Example #1 (2)
30CSE 5324, Summer 2017, Ali Sharifara
A Sale contains (aggregates) many SalesLineItem objects
• Creator pattern suggests that Sale is a good candidate to have the responsibility of creating SalesLineItem instances.
• This leads to the design of object interactions shown below • This assignment of responsibilities requires that a makeLineItem
method be defined in Sale
Creator – Example #2
• Consider VideoStore and Video in that store.
• VideoStore has an aggregation association with Video. I.e, VideoStore is the container and the Video is the contained object.
• So, we can instantiate video object in VideoStore class
31CSE 5324, Summer 2017, Ali Sharifara
Creator – Example #2
32CSE 5324, Summer 2017, Ali Sharifara
Example diagram
Example for creator
Benefits (Creator)
• Low coupling is supported, which implies lower maintenance dependencies and higher opportunity for reuse.– The created class is likely already visible to the
creator class.
33CSE 5324, Summer 2017, Ali Sharifara
Information Expert
• Problem: What is a general principle of assigning responsibilities to objects?– A Design Model may define hundreds or thousands of
software classes, and an application may require hundreds or thousands of responsibilities to be fulfilled.
– If we’ve chosen well easier to understand, maintain, and extend more opportunity to reuse components.
• Solution: Assign a responsibility to the information expert– The class that has the information necessary to
fulfill the responsibility.
34CSE 5324, Summer 2017, Ali Sharifara
Information Expert - Example
35CSE 5324, Summer 2017, Ali Sharifara
• Example– NextGEN POS: some class needs to know the grand total of
all the SalesLineItem instances of a sale.– Who should be responsible for knowing that?
• Information Expert of the Domain Model : look for class that has the information needed to determine the total - Sale.
• Give the responsibility of knowing its total - method getTotal
Information Expert-Example (2)
36CSE 5324, Summer 2017, Ali Sharifara
• Who should know the line item subtotal?
• The SalesLineItem knows its quantity and its associated ProductDescription; therefore, by Expert, SalesLineItem should determine the subtotal.
• The Sale should send getSubtotal messages to each of the SalesLineItems and sum the results
Information Expert-Example (3)
37CSE 5324, Summer 2017, Ali Sharifara
• To fulfill the responsibility of knowing its subtotal, a SalesLineItemhas to know the product price.
• The ProductDescription is an “information expert” on answering its price;
• SalesLineItem sends a message asking for the product price
Information Expert
• To fulfill the responsibility of knowing and answering the sale's total.– Assign three responsibilities to three design classes of
objects in the interaction diagram.– Summarize the methods in the method section of a class
diagram.
38CSE 5324, Summer 2017, Ali Sharifara
Design Class ResponsibilitySale Knows sale totalSalesLineItem Knows line item subtotalProductDescription Knows product price
Benefits (Information Expert)
• Information encapsulation is supported since objects use their own information to fulfill tasks.
• Behavior is distributed across the classes that have the required information.– Lightweight classes are easier to understand and
maintain.
39CSE 5324, Summer 2017, Ali Sharifara
• Also called do-it-myself strategy• In object-oriented software, all software objects are alive, and they can
take on responsibilities and do things related to the information they know.
Low Coupling
• Problem: How to support low dependency, low change impact, and increased reuse ?
• Solution: Assign responsibilities so that coupling remains low. Use this principle to evaluate alternatives.
40CSE 5324, Summer 2017, Ali Sharifara
Coupling
41CSE 5324, Summer 2017, Ali Sharifara
• A measure of how strongly one element is connected to, has knowledge of, or relies on other elements.
• An element with low coupling is not dependent on too many other classes, subsystems, systems.
• High coupling problems: • Forced local changes because of changes in related
classes. • Harder to understand in isolation. • Harder to reuse because its use requires the additional
presence of the classes on which it is dependent.
Example
42CSE 5324, Summer 2017, Ali Sharifara
• NextGen POS • To create a Payment instance and associate it with
the Sale, What class should be responsible for this?
• Which design, based on assignment of responsibilities, supports Low Coupling?
• In both cases we assume the Sale must eventually be coupled to knowledge of a Payment.
Low Coupling – (Design 1)
43CSE 5324, Summer 2017, Ali Sharifara
• Since a Register "records" a Payment, the Creator pattern suggests Register as a candidate for creating the Payment.
• The Register instance could then send an addPaymentmessage to the Sale, passing along the new Payment as a parameter.
• Adds coupling of Register to Payment
Poor(high) couplingRegister is depending on both the classes
Low Coupling – (Design 2)
44CSE 5324, Summer 2017, Ali Sharifara
• The Sale does the creation of a Payment, does not increase the coupling.
• Purely from the point of view of coupling, prefer Design 2 because it maintains overall lower coupling.
Example for poor coupling
45CSE 5324, Summer 2017, Ali Sharifara
Class RentVideo knows about both VideoStore and Video objects. Rent is depending on both the classes.
Example low coupling
46CSE 5324, Summer 2017, Ali Sharifara
VideoStore and Video class are coupled, and Rent is coupled with VideoStore. Thus providing low coupling.
Benefits
• Not affected by changes in other components• Simple to understand in isolation• Convenient to reuse
• Classes that are generic in nature or a high probability for reuse should have especially low coupling.
47CSE 5324, Summer 2017, Ali Sharifara
Controller
• Problem: What first object beyond the UI layer receives and coordinates (“controls”) a system operation ?
• A controller is the first object beyond the UI layer that is responsible for receiving or handling a system operation message
• Deals with how to delegate the request from the UI layer objects to domain layer objects.
• when a request comes from UI layer object, Controller pattern helps us in determining what is that first object that receive the message from the UI layer objects.
48CSE 5324, Fall 2016, Jeff Lei
Controller
Solution: • Assign the responsibility to a class that
– Represents the overall "system," a "root object," a device that the software is running within, or a major subsystem.
• A controller can be a single point of contact on the backend (so that the connections between front and back end can be reduced).
49CSE 5324, Fall 2016, Jeff Lei
Guideline
• Typically, a controller should delegate to other objects the work that needs to be done.
• A controller does not do much work itself.
50CSE 5324, Summer 2017, Ali Sharifara
Example
51CSE 5324, Summer 2017, Ali Sharifara
Example
52CSE 5324, Summer 2017, Ali Sharifara
Example (3)
53CSE 5324, Summer 2017, Ali Sharifara
Controller- Good Design
54CSE 5324, Summer 2017, Ali Sharifara
Controller - Bad Design
55CSE 5324, Summer 2017, Ali Sharifara
Bloated Controllers
Controller class is called bloated, if– The class is overloaded with too many responsibilities.
Solution –Add more controllers
56CSE 5324, Summer 2017, Ali Sharifara
Benefits
• Increased potential for reuse and pluggableinterfaces– Application logic is not bound in the interface layer, it can be
replaced with a different interface.– Delegating a system operation responsibility to a controller
supports the reuse of the logic in future applications
• Opportunity to reason about the state of the use case– To ensure that system operations occur in a legal sequence, or we
want to be able to reason about the current state of activity and operations within the use case.
– E.g., to guarantee that the makePayment operation cannot occur until the endSale operation has occurred. To capture this state information somewhere; the controller is one reasonable choice.
57CSE 5324, Summer 2017, Ali Sharifara
High Cohesion
• Problem– How to keep objects focused, understandable,
and manageable, and as a side effect, support Low Coupling ?
– Cohesion: A measure of how strongly related and focused the responsibilities of a class or subsystem are.
• Solution– Assign a responsibility so that cohesion remains
high. – Use this to evaluate alternatives.
58CSE 5324, Summer 2017, Ali Sharifara
High Cohesion Cont.
• A class with low cohesion does many unrelated things or too much work. Such classes suffer from the following problems:– Hard to comprehend,– Hard to reuse,– Hard to maintain,– Constantly affected by change.
59CSE 5324, Summer 2017, Ali Sharifara
High cohesion is a principle to keep in mind during all design decisions.
High Cohesion - Example.
Example• POS: Low Coupling pattern for High Cohesion.
– To create a (cash) Payment instance and associate it with the Sale. What class should be responsible for this ?
60CSE 5324, Summer 2017, Ali Sharifara
High Cohesion - Design 1
• Since Register records a Payment in the real-world domain, the Creator pattern suggests “Register” for creating the Payment.
• The Register instance could send an addPayment message to the Sale, passing along the new Payment as a parameter
• To places the responsibility for making a payment in the Register.
• To continuous make the Register class responsible for doing most of the work related to more system operations
– It will become increasingly with tasks and become incohesive.
61CSE 5324, Summer 2017, Ali Sharifara
High Cohesion - Design 2
• The second design delegates the payment creation responsibility to the Sale supports higher cohesion in the Register.– The second design is desirable, since it supports both high
cohesion and low coupling
• In practice, the level of cohesion alone can't be considered in isolation from other responsibilities and other principles such as Expert and Low Coupling.
62CSE 5324, Summer 2017, Ali Sharifara
Benefits
• Clarity and ease of comprehension of the design is increased.
• Maintenance and enhancements are simplified.
• Low coupling is often supported.• Reuse of fine-grained, highly related
functionality is increased.
63CSE 5324, Summer 2017, Ali Sharifara
Bad cohesion usually causes bad coupling, and vice versa.
Polymorphism
• How to handle related but varying elements based on element type?
• Polymorphism guides us in deciding which object is responsible for handling those varying elements.
• Benefits: handling new variations will become easy.
64CSE 5324, Summer 2017, Ali Sharifara
Polymorphism - Example
• The getArea() varies by the type of shape, so we assign that responsibility to the subclasses.
• By sending message to the Shape object, a call will be made to the corresponding sub class object –Circle or Triangle.
65CSE 5324, Summer 2017, Ali Sharifara
Pure Fabrication
• Problem: What object should have the responsibility, when you do not want to violate High Cohesion and Low Coupling, or other goals, but solutions offered by Information Expert are not appropriate.
• Solution: Assign a highly cohesive set of responsibilities to an artificial or convenienceclass that doesn't represent any domain object (Ex. Database operations or Logging purposes)
66CSE 5324, Summer 2017, Ali Sharifara
Pure Fabrication - Example #1
• Suppose that we need to save Sale objects in a relational database.
• Should we assign the responsibility to the Sale class?– This task requires a relatively large number of
supporting database-oriented operations.– The Sale class will be coupled to the relational
database interface.– This task is very general and can be duplicated in
many other classes.
67CSE 5324, Summer 2017, Ali Sharifara
Pure Fabrication - Example
68CSE 5324, Summer 2017, Ali Sharifara
Pure Fabrication - Example #2
• Suppose we have Shape class, if we must store the shape data in a database.
• If we put this responsibility in Shape class, there will be many database related operations thus making Shape incohesive.
• So, create a fabricated class DBStore which is responsible to perform all database operations.
• Similarly logInterface which is responsible for logging information is also a good example for Pure Fabrication.
69CSE 5324, Summer 2017, Ali Sharifara
Benefits
• High cohesion is supported as responsibilities are factored into a fine-grained class.
• Reuse potential may increase since the responsibilities of the Pure Fabrication class may be used in other classes.
70CSE 5324, Summer 2017, Ali Sharifara
Indirection
• Problem: Where to assign a responsibility, to avoid direct coupling between two (or more)things?
• Solution: Assign the responsibility to an intermediate object to mediate between other components or services so that they are not directly coupled.
71CSE 5324, Summer 2017, Ali Sharifara
Example
72CSE 5324, Summer 2017, Ali Sharifara
Benefits
• Lower coupling between components.
73CSE 5324, Summer 2017, Ali Sharifara
Protected Variations
• Problem: How to design objects, subsystems, and systems so that the variations or instability in these elements does not have undesirable impact on other elements?
• Solution: Identify points of predicted variation or instability; assign responsibilities to create a stable interface around them.
74CSE 5324, Summer 2017, Ali Sharifara
Example
75CSE 5324, Summer 2017, Ali Sharifara
Benefits
• Extensions required for new variations are easy to add.
• New implementations can be introduced without affecting clients.
• Coupling is lowered.• The impact or cost of changes can be
lowered.
76CSE 5324, Summer 2017, Ali Sharifara
Conclusion
• GRASP provides a map of considerations to provide strong guidance for an OO designer
• But at the same time, GRASP still leaves a lot of room to the designer and creating a good design is still an art!
77CSE 5324, Summer 2017, Ali Sharifara
More Information
• The GoF book– Design Patterns: Elements of Reusable Object-
Oriented Software, Eric Gamma, Richard Helm, Ralph Johnson, John Vlissides, Addison Wesley, 1994.
• CSE 5322: Software Design Patterns taught by Dr. David Kung– A course highly recommended for all CS students
78CSE 5324, Summer 2017, Ali Sharifara