Sunteți pe pagina 1din 52

‫‪Object-‬‬

‫‪Object-Oriented Design‬‬

‫לאוניד ברנבוים וגרא וייס‬


‫המחלקה למדעי המחשב‬
‫אוניברסיטת בן‪-‬גוריון‬
22

Why Start with Design?

 Object-oriented thinking begins with object-


oriented design

 It is the easiest way to see the problems of


realistic modern software development

 Without understanding
programming in the large, one cannot
appreciate the importance of OOP
33

Working with object oriented language is neither


necessary nor sufficient condition for
doing object oriented programming
44 http://rebeccawbblog.blogspot.com/

Responsibility Driven Design


Simply using an object-oriented programming
language does not, in itself, guarantee
miraculous results.
Like any human endeavor, software design
requires discipline, hard work, inspiration and
sound technique.
Some people have touted object-oriented
design as the next great revolution in software
simply because it allows a designer to capture
‘real world objects’ and, with just a little bit of
REBECCA WIRFS-
WIRFS-BROCK transformation, create a working program.
It isn’t that easy.
There’s a lot of judgment, abstraction skills,
and lessons learned from previous experiences
that go into creating an object-oriented model.
And the approach taken to define and describe
objects will have profound impacts on the
resulting design.
55

Goals for the Design Process


 Develop first the ‘big picture’ of how key objects interact,
before filling out precise details of individual classes

 It is far, far easier to consider, refine, and even discard ideas


up front before major investments of time and money have
been made

 Decisions made about the internal structure and algorithmic


details of an object before there is a clear understanding of its
role and purpose are often flawed

 Design, by nature, is an incremental journey of discovery and


refinement

 With each new refinement comes further insights and changes

 It is important, however, to not force design decisions before


there is a knowledge to make intelligent tradeoffs
66

Goals for the Design Process

 We wanted designers to initially focus on building


a model of interacting objects

 Each object’s role or purpose as well as its


interactions with other objects is important to
understand

 Finally we wanted to present modeling techniques


and guidelines that were language-independent
77
Responsibility Implies
Noninterference

re
fe
no ior

er
nt
v
ha

ti
Responsibility

be
in

o
,d
nd rta
ce
ce
en
de t a
c
pe
pe
Ex
in
e
A two-way
iv
G

sword
88
Programming in the Small and
Programming in the Large

Programming in the small

One programmer
understands everything from top to bottom.

Main problem is the


development of algorithms

Programming in the large

System is developed by a
large teams of programmers

Main problems are management of details and


communication between software subsystems
99

Object Oriented Design


 Object-oriented design typically is quite exploratory and
iterative

 Unless designers are building (or rebuilding) an


application with which they are intimately familiar,
a clear vision of the key classes does not exist

 Creating a model requires understanding system


requirements as well as skill in identifying and creating
objects

 Building consensus and developing a common


vocabulary among team members is important

 Initially, designers look for classes of key objects, trying


out a variety of schemes to discover the most natural and
reasonable way to abstract the system into objects
10
10 Responsibilities and
Collaborations

 Responsibility-driven design focuses


on what actions must get accomplished, and
which objects will accomplish them

 How each action is accomplished is deferred

 Details of internal structure and specific


algorithms can be worked out once roles and
responsibilities are better understood
11
11
Basis for Design
Consider for the moment what aspects of a
problem are known first:

Data Structures ?
Functions ?
A Formal Specification ?
Behavior ?

A design technique based on behavior can be applied from the


very beginning of a problem

Whereas techniques based on more structural properties necessarily


require more preliminary analysis
12
12

Directed Evolution

Let us take specifications as they occur in nature

Imprecise

Ambiguous

Unclear

and rather than attempt to change human nature,


let us direct the evolution of the specification in
concert with the design of the software system
13
13

Evolution of Specifications

How the project leader How the business Consultant


How the customer explained it How the Analyst designed it How the Programmer wrote it
understood it Described it

How the project was What the customer really


What operations installed How the customer was billed How it was supported
documented needed
14
14

An Example, the IIKH


 Imagine you are the chief software architect in a
major computing firm

 The president of the firm rushes into your


office with a specification for the next
PC-based product

 It is drawn on the back of a dinner napkin

 Briefly, the
Interactive Intelligent Kitchen Helper
will replace the box of index cards of recipes in the
average kitchen
15
15

Your Job
Your job is to develop the software that will
implement the IIKH:
16
16

Abilities of the IIKH


Here are some of the things a user can do with the IIKH:

 Browse a database of recipes

 Add a new recipe to the database

 Edit or annotate an existing recipe

 Plan a meal consisting of several courses

 Scale a recipe for some number of users

 Plan a longer period, say a week

 Generate a grocery list that includes all the items in all the
menus for a period
17
17

Characterization by Behavior
Just as an Abstract Data Type (ADT) is characterized
more by behavior than by representation

The goal in using Responsibility Driven Design will be


to first characterize the application by behavior:

 First capture the behavior of the entire application

 Refine this into behavioral descriptions of subsystems


refinement

 Refine behavior descriptions into code

 This emphasis on behavior is a hallmark of


Object-Oriented programming
18
18

Working Through Scenarios


Because of the ambiguity in the specification, the major tool we will
use to uncover the desired behavior is to
walk through application scenarios:

 Pretend we had already a working application

 Walk through the various uses of the system

 Establish the “look and feel” of the system

 Make sure we have uncovered all the intended uses

 Develop descriptive documentation

 Create the high level software design

Some people use the term “use-cases” for this


process of developing scenarios
19
19
 Given an initial set of key objects, the designer can elaborate
object responsibilities and collaborations by testing how the
model responds to a variety of requests

 Scenarios that the application must handle can be described,


and requests or events can be fed into the model

 Running through a number of typical scenarios rapidly points out


gaps in understanding

 It is not uncommon to find new key objects and discard ill-


conceived ones, to elaborate and reassign responsibilities, or to
fabricate new mechanisms as part of this process

 It is also a time when missing or conflicting system requirements


surface and require clarification before completing the initial
model
20
20
Example Scenario: Simple Browsing
1. Alice Smith sits down at her computer and starts the IIKH
2. When the program begins, it displays a graphical image of a recipe box, and
identifies itself as the IIKH. Alice presses the return button to begin. In response to
the key press, Alice is given a choice of a number of options
3. She elects to browse the recipe index, looking for a recipe for Salmon that she
wishes to prepare for dinner the next day
4. She enters the keyword Salmon, and is shown in response a list of various recipes
5. She remembers seeing an interesting recipe that used dill-weed as a seasoning
6. She refines the search, entering the words Salmon and dill-weed
7. This narrows the search to two recipes. She selects the first
8. This brings up a new window in which an attractive picture of the finished dish is
displayed, along with the list of ingredients, preparation steps, and expected
preparation time
9. After examining the recipe, Alice decides it is not the recipe she had in mind
10. She returns to the search result page, and selects the second alternative

11. Examining this dish, Alice decides this is the one she had in mind. She requests a
printing of the recipe, and the output is spooled to her printer
12. Alice selects “quit" from a program menu, and the application quits
21
21

Software Components
A software component is an abstract design entity with
which we can associate responsibilities for different tasks

May eventually be turned into a class, a function, a module,


or something else

A component must have a small well defined set of responsibilities

A component should interact with other components to the minimal


extent possible
22
22

CRC Cards
Components are most easily described using CRC cards. A CRC
card records the name of a candidate component, its
responsibilities, and collaborators :

Component Name
Collaborators

Description of the List of other

responsibilities assigned components

to this component
23
23

First component: The Greeter


 The first component your team defines is the Greeter
 When the application is started, the Greeter puts an
informative and friendly welcome window (the greeting) on
the screen

 Offer the user the choice of several different actions:


 Casually browse the database of recipes

 Add a new recipe

 Edit or annotate a recipe

 Review a plan for several meals

 Create a plan of meals

 Many of the details concerning exactly how this is to be


done should be ignored for the moment
24
24

The Recipe Database Component

Ignoring the planning of meals for the moment, your


team elects to next explore the recipe database
component:

 Must maintain the database of recipes

 Must allow the user to browse the database

 Must permit the user to edit or annotate an existing recipe

 Must permit the user to add a new recipe


25
25

The Who/What Cycle

As we walk through scenarios, we go through cycles of


identifying a what, followed by a who

 What action needs to be performed at this moment,

 Who is the component charged with performing the action

Every what must have a who, otherwise it simply will not


happen

Sometimes the who might not be obvious at first, i.e., who


should be in charge of editing a recipe?
26
26

Postponing Decisions
Many decisions, such as the method of browsing, can be
ignored for the moment,

as they are entirely encapsulated within the recipe database


component, and do not effect other components

 Scroll bars and windows?

 A virtual “book” with thumb-holes and flipping pages?

 Keywords and phrases?

Only need to note that somehow the user can manipulate the
database to select a specific recipe
27
27

Responsibilities of a Recipe
We can make the recipe itself into an active data structure

It maintains information, but also performs tasks

 Maintains the list of ingredients and transformation algorithm

 Must know how to edit these data values

 Must know how to interactively display itself on the output device

 Must know how to print itself

We will add other actions later (ability to scale itself, produce


integrate ingredients into a grocery list, and so on)
28
28

The Planner Component

Returning to the Greeter, we start a different


scenario

This leads to the description of the Planner:

 Permits the user to select a sequence of dates for


planning

 Permits the user to edit an existing plan

 Associates with Date object


29
29

The Date Component

The Date component holds a sequence of meals


for an individual date:

 User can edit specific meals.

 User can annotate information about dates (“Bob's


Birthday”, “Hanukkah Dinner”, and so on)

 Can print out grocery list for entire set of meals


30
30

The Meal Component


The Meal component holds information about a
single meal:

 Allows user to interact with the recipe database to


select individual recipes for meals

 User sets number of people to be present at meal,


recipes are automatically scaled

 Can produce grocery list for entire meal, by


combining grocery lists from individual scaled
recipes
31
31

The Six Components


Having walked through the various scenarios, your team
eventually decides everything can be accomplished using
only six software components.

Greeter

Recipe
Plan Database
Manager

Date Meal Recipe

You can at this point assign the different components to


different programmers for development
32
32

Interaction Diagrams
The picture on the previous slide captures static relationships, but
not the dynamic flow of messages in a scenario.

That information can be recorded by an interaction diagram:

Greeter Database Recipe Planner


browse()
display()

return from display

return from browse

makePkan()
33
33

Characteristics of Components
Let us return to the idea of a software component

There are many different aspects to this simple


idea, we will consider just a few:

Behavior and State

Instances and Classes

Coupling and Cohesion

Interface and Implementation


34
34

Behavior and State


All components can be characterized by two aspects:

 The behavior of a component is the set of actions a


component can perform. The complete set of behavior
for a component is sometimes called the protocol.

 The state of a component represents all the


information (data values) held within a component.

Notice that it is common for behavior to change state.


For example, the edit behavior of a recipe may change
the preparation instructions, which is part of the state.
35
35

Instances and Classes


We can now clarify a point we earlier ignored.

There are likely many instances of recipe, but they will all behave
in the same way.

We say the behavior is common to the class Recipe:

Recipe Behavior:
Recipe class: Edit
Display

Strawberry Vegetables Cheese


Recipe instances:
short cake soup enchilada

Since earlier our goal was to identify behavior, we ignored this


distinction and concentrated on prototypical objects
36
36

Coupling and Cohesion

The separation of tasks into the domains of different components


should be guided by the concepts of coupling and cohesion:

 Cohesion is the degree to which the tasks assigned to a


component seem to form a meaningful unit.
Want to maximize cohesion

 Coupling is the degree to which the ability to fulfill a certain


responsibility depends upon the actions of another component.
Want to minimize coupling
37
37

Interface and Implementation


 We have characterized software components by
what they can do

 The user of a software component need only know


what it does, not how it does it.

“Ask not what you can do to a data structure,


ask instead
what your data structures can do for you”
38
38

Two views of a Software System


This naturally leads to two views of a software
system:

Edit a recipe Text buffer

Create a new recipe Window pointer

Display on terminal Ingredients list

The term information hiding is used to describe


the purposeful hiding of implementation details
39
39

Parnas' Principles

These ideas were captured by computer scientist


David Parnas in a pair of principles:

 The developer of a software component must provide the


intended user with all the information needed to make
effective use of the services provided by the component, and
should provide no other information

 The implementer of a software component must be provided


with all the information necessary to carry out the given
responsibilities assigned to the component, and should be
provided with no other information.
40
40

Public and Private View


In C++ and Java, Parnas's Principles lead to the
ideas of a public and private view:

 Public view - those features (data or behavior) that


other components can see and use

 Private view - those features (data or behavior)


that are used only within the component
41
41 Next Step –
Formalize the Interface
The next step is to formalize the channels of communication
between the components:

 The general structure of each component is identified.

 Components with only one behavior may be made into functions

 Components with many behaviors are probably more easily


implemented as classes

 Names are given to each of the responsibilities - these will


eventually be mapped on to message names

 Information is assigned to each component and accounted for

 Scenarios are replayed in order to ensure all data is available


42
42

A Rose by any other Name


Government bureaucrats have long shown us that
obscure and idiomatic names can make even the
simplest operation sound intimidating

 The selection of names is an important task

 Names should be evocative in the context of the problem

 Names should be short

 Names should be pronounceable (read them out load)

 Names should be consistent within the project


43
43

Documentation

 Besides CRC cards, it is important that the


development of other documentation be
performed almost from the beginning

 The two most important documents are the


user manual and the design documentation of
the software system
44
44

User Manual

The user manual describes the application as


seen by the user

 Does not depend upon the implementation, so can


be developed before the implementation

 Can naturally flow from the process of walking


through scenarios.

 Can be carried back to the clients to make sure


the users and the implementers have the same
ideas
45
45

Quality
 You should always remember that the primary
measure of quality is the degree to which
your customers (clients) are satisfied with your
product

 Since often customers do not know exactly what


it is they want, it is important to work with the
client early in the design phase to make sure the
system your are developing is the desired
product

 One very important way to do this is to create


the user manual before the software is written
46
46

System Design Documentation


Record the decisions made during the process of
system design:

 Record the arguments for and against any major


decision, and the factors influencing the final choice

 Record CRC cards for the major components

 Maintain a log or diary of the process schedule

 Important to produce this while the ideas are fresh, not in


hindsight when many details will have been forgotten

 Note the code only records the outcome of decisions, not


factors that lead up to decisions being made
47
47

Preparing for Change


Your design team should also keep in mind that change is inevitable

Users requirements change with experience, hardware changes,


government regulations change

 Try to predict the most likely sources of change, and isolate the effect

 Common changes include interfaces, file formats, communication


protocols

 Isolate interfaces to hardware that is likely to change

 Reduce dependency of one software component on another

 Keep accurate record of the reasoning behind every major decision in


the design documentation
48
48 Next Step - Select
Representations for Subsystems

 Next the internal representation of the software


subsystem corresponding to each component is
selected

 Knowledge of the classic data structures of


Computer Science is important here

 Often once data structures have been selected,


the code is almost self-evident
49
49 Step - Implement and Test
Subsystems
Classic techniques, such as stepwise refinement, are
used to implement each of the subsystems

Subsystems are validated in isolation:

 Informal and formal proofs of correctness for the


subsystem are developed

 Identify necessary conditions for correct functioning.


Try to minimize conditions, and test input values
whenever possible

 Software testing is used as a confidence building


measure
50
50

Step - Integration and Testing


 Components are slowly integrated into completed
system

 Stubs can be used to perform testing all during


integration

 Errors discovered during integration to cause


reinvestigation of validation techniques performed
at the subsystem level
51
51

Maintainence and Evolution


Software does not remain fixed after the first working version is
released:

 Errors or bugs can be discovered. Must be corrected.

 Requirements may change. Say as a result of government


regulations, or standardization among similar products.

 Hardware may change.

 Users expectations may change. Greater functionality, more


features. Often as a result of competition from similar products.

 Better documentation may be required.

A good design recognizes the inevitability of change, and plans


an accommodation for these activities from the very beginning
52
52
Common Design Flaws
 Direct modification: Components that make direct modification of data values
in other components are a direct violation of encapsulation.
 Such coupling makes for inflexible designs.

 Too Much Responsibility: Components with too much responsibility are difficult
to understand and to use.
 Responsibility should be broken into smaller meaningful packages and distributed.

 No Responsibility: Components with no responsibility serve no purpose.

 Often arise when designers equate physical existence with logical design existence.

 “Money is no object”

 Components with unused responsibility:

 Usually the result of designing software components without thinking about how they
will be used.

 Misleading Names:

 Names should be short and unambiguously indicate what the responsibilities of the
component involve.

S-ar putea să vă placă și