ObjectOriented Design - PowerPoint PPT Presentation

1 / 50
About This Presentation
Title:

ObjectOriented Design

Description:

Domain, System and Data Models. Use-cases and Test-cases. A ... Favor immutability. Avoid unnecessary use of checked exceptions. Design API signatures carefully ... – PowerPoint PPT presentation

Number of Views:50
Avg rating:3.0/5.0
Slides: 51
Provided by: RQ
Category:

less

Transcript and Presenter's Notes

Title: ObjectOriented Design


1
Object-Oriented Design
  • Lars Degerstedt
  • Linköping university, IDA
  • larde_at_ida.liu.se
  • Basics before Realistics

2
This Lecture
  • 1st hour Basics
  • Domain, System and Data Models
  • Use-cases and Test-cases
  • A Simple Design Theory
  • Classes and Objects
  • Principles of Class Design
  • 2nd hour Advanced Issues

3
Literature
  • Stefan Sigfried, Understanding OO Software
    Engineering, IEEE Press 1996
  • Betrand Meyer, OO Software Construction (2nd Ed).
    Prentice-Hall 1997
  • Martin Fowler, Refactoring, Addison-Wesley 1999
  • Kent Beck, Extreme Programming Explained.
    Addison-Wesley 1999

4
Modeling Reality
Reality/Domain/Problem
Domain model/capture
Perhaps informal Texts only?
Domain/Product Experts Customers/Users
What is the result of domain analysis?
How much domain analysis depends on the character
of the domain.
  • Documents vision and needs
  • (Graphical) concept prototypes
  • Software Artefacts, e.g. data models

5
Modeling The System
System Model
Context of System Design
Problem Description
Architecture Subsystems Strategic Decisions
Legacy and Platform
Software Designers /senior developers
Construction Theory
What is the result of system modeling?
  • Architectural Sketch
  • Subsystem APIs
  • Technical Infrastructure

6
Modeling Data
Data Model
Context of Data Modeling
Domain Concepts
Minimal data models Taxonomy of types Objects and
Attributes
Domain Behaviour
What is the result of data modeling?
Domain Functionality
Knowledge Engineers/ IS experts
  • Database models
  • Document formats
  • Information processing
  • Protocols
  • Data structures

Representation Platform
7
Use-Cases (from RUP)
a sequence of actions the system performs
observable result for an actor
  • Provides a common modeling language
  • Systemcollection of use-cases gives overview
  • - Not a good tool for finding classes
  • - Scenarios are domain-oriented not
    system/data-oriented
  • - use-cases are functional not object-oriented

Alternative XP stories. More liberal, shorter
and with a smaller role in design.
8
Test-Cases (eXtreme Programming View)
  • Tests dont interact
  • Tests are automatic (e.g. Junit) ? ?
  • Only test things that might break
  • In interface and/or implementation
  • Programmers test by method/unit
  • Customers story-by-story/functional
  • Parallel, stress and monkey
  • Finding orthogonal and complete test suites are
    hard issues

9
A Simple Design Theory (Sigfried 96)
Subsystem
-Actor -Agent -Server
System
Interface
Manipulates
Application-part
-Dialog -Connection
Information
Design in the small and in the large!
10
Types of Objects (Design In the Small)
  • Information objects
  • Stable
  • data carriers
  • several instances of classes
  • persistent
  • System objects
  • handlers/controllers
  • Unique instances of classes
  • complex and changing
  • plays roles in the system
  • Interface Objects
  • encapsulates communication, user/module

11
Models and Objects
Domain Model
Interface Objects
Data Model
Information Objects
System Model
System Objects
12
System Objects in Layers
Logical Layer
Movie Information API
Conceptual Devices
Information source
Object Derived from outside entities
Web resource
13
Subsystems of Objects (Design In The Large)
  • micro-world aggregation
  • Independent
  • Useful more than sum of its parts
  • A new large object or mediator to an assembly
  • Methods and attributes of its own
  • Well-defined interface
  • Close to the domain/user natural
  • Subsystem entities (or their APIs) are often
    emergent in the design

14
Controllers and Managers
  • Subsystems can be seen as controllers or
    managers
  • Standardized view on subsystems
  • Each manager manages a micro-world, e.g.
    documents, network, linguistic analysis
  • A controller can be active (threaded) or passive
    (waiting for startup calls)

15
Classes and Objects (Meyer 97)
  • Def A class is an abstract datatype equipped
    with a possibly partial implementation

Class A
x type B
Client
Class B
Supplier
  • Classes are computational models Both type
    (semantic) and module (syntactic)
  • Classes have instances, or objects
  • The OO-object data representation of an everyday
    object.
  • Classes are meta-objects that forms meta-classes

16
Finding Classes (Meyer 97)
  • Many are just for the picking
  • Domain classes abstract reality
  • Try use existing classes (perhaps from third
    party)
  • Implementation classes reuse from libraries!
  • Experience and imitation use existing successes,
    e.g. J2SE and design patterns
  • Design classes reuse from books!
  • Class name a (qualified) noun or adjective
  • Classes normally have several methods
  • Dont use grammatical criteria from domain
    analysis texts!
  • Avoid useless classes and taxomania
  • Avoid relying on metaphors

17
The Shopping List Approach
  • Added features must be
  • relevant
  • compatible
  • unique
  • respect invariant behaviour
  • No absolute limit on API size
  • Negative sides
  • shopping center systems
  • not so easy to find in real life

18
Interface Contracts
  • Modules and/or classes
  • Syntactic (schema) and semantic (names)
  • Smallest contractual units
  • Individual op. lacks individual meaning
  • Context-independent contract
  • Direct part requirements on supplier
  • Indirect part requirements on client

19
Messages/Protocols
Message format
Peer A
Peer B
  • reside on the wire/logical line
  • Similar to interface design
  • Syntax (schema) and semantics (names)
  • Interface or protocol
  • Tradition communication vs computation
  • Emphasis channel or end-points
  • Synchron. or asynchron IF and protocol resp.

20
5 Rules of Modular Class Design
  • Direct Mapping
  • Few Interfaces
  • Small interfaces (weak coupling)
  • Explicit Interfaces
  • Information Hiding

21
Rule 1 Direct Mapping
Keep system design close to domain concepts
  • Continuity easier to maintain when domain
    changes
  • Decomposability reuse modularity of domain
    analysis

22
Rule 2 Few Interfaces
n-16
n(n-1)/2 15
  • Every class should communicate with as few others
    as possible
  • Keeps effects of changes small
  • Reuse through context-independence

23
Rule 3 Small Interfaces
Exchange as little information as possible
Class A
Class B
Bandwidth
  • Save bandwidth
  • Propagation of error Common data can be misused
    by all
  • Propagation of change data structure changes
    affects all

24
Rule 4 Explicit Interfaces
Communication between classes must be obvious
from their texts
  • Avoid indirect coupling
  • Understandability no hidden effects
  • (De)composability all dependencies must be easy
    to spot

Indirectness
Class A
Class B
Data x
25
Rule 5 Information-Hiding
Encapsulation
Information-Hiding
Module
Module
Interface
The Iceberg
Functionality
Simplicity
  • IH is often a gradual process
  • IH means a) coherent abstraction b) focus
  • Drawing the module line at a natural point
  • Simplify without losing functionality
  • Support both beginners and power-usage
  • Powerful interaction vs. independent modules
  • Separate function from implementation

26
This Lecture
  • 1st hour Basics
  • 2nd hour Advanced Issues
  • Simple OO-Architecture
  • Top-down vs Object-Oriented Thinking
  • Reuse
  • Inheritance
  • Effective Design/Java
  • Refactoring

27
Basic OO Architectural Design (Sigfried 96)
Def (1) The process of defining a collection of
hardware and software components/modules and
their interfaces to establish a framework for the
development of a computer system. (2) The result
of the process in (1). IEEE
  • Top-level Grouping of objects top-level
    aggregation/association
  • Divide domain into part-domains
  • Support Parallel development
  • Iterative refined construct

28
Architectural Elements
  • System
  • Functionality (use-cases, XP stories)
  • Platform
  • Subsystem
  • Distributed functional behaviour
  • main functional decomposition
  • System Objects
  • Identification and naming of layers
  • Object conventions for each layer

29
Trad. Top-Down Design (Meyer 97)
Execute Session
A transitional state system, e.g. form- based
booking
State
Initial
Transition
Execute_State
Is_Final
  • Critique
  • why transition function?
  • State arg everywhere
  • Low reuse-factor

Read
Display
Correct
Message
Process
  • Only for Design in the Small (it is simple to
    use!)
  • Functional decomposition/stepwise refinement
  • Changes in domain changes in objects
  • Classes evolve better than functions
  • A large system has no top or top function
  • The system top function is fragile since its
    global
  • External interface should not determine internal
    design
  • Premature emphasis of temporal ordering

30
The Object-Oriented Alternative
Application
AbstractState
Initial, Is_final state
Display() Read()
Execute()
  • Favour objects before properties and functions
  • Introduces polymorphism
  • Find the classes not the function
  • Dont pay too much attention to the real world
  • but Top-down is still valuable for algorithms,
    explanations and first-attempts!

31
OO Quality the Case of Reuse
  • Serving different applications
  • Questions
  • Reuse What is varying?
  • Extendibility (related term) What is changing?
  • Separation of change constancy
  • Reuse-redo dilemma
  • Finding generics deciding what is varying
  • Making API understandable black-box
  • Reusing a part only how?

32
5 Requirements for Reuse
  • Type variation
  • Routine grouping
  • Implementation variation
  • Representation independence
  • Factoring out common behaviours

33
Using Inheritance the ISA-rule
Car
Person
Person
CarOwner
Car
CarOwner
Wrong!
Better!
The ISA Rule one can view every instance of the
subclass as an instance of the superclass.
34
Using Inheritance valid forms
Valid Inheritance
Model Inheritance
Subtype
View
Reflects isa in domain model
Restriction
Extension
Inheritance (simplicity) rule every use of
inheritance should belong to one (preferably just
one) of the accepted categories.
Variation Inheritance
Functional Variation
Description through differences
Type Variation
Software Inheritance
Reification
Structure
Expresses software relations
Implementation
Facility
35
Using inheritance the problems
  • Reuse by subclassing is white-box
  • Defined statically at compile-time
  • Breaks encapsulation propagation of change and
    error
  • Syntactic fragile base class problem
  • Mismatch of Binary releases of super and sub
    class
  • Semantic fragile base class problem
  • Implementation inheritance is fragile

36
Cosmetics matter!
  • Choosing Names
  • Important for public classes and methods
  • Dont compose name from its parts
  • Use standard name(-parts) add, extend,
  • Dont fix the API too soon, put effort on
    (re-)naming!
  • Use constants
  • Avoid anonymous strings/integers in code
  • Search for conceptual domains of immutables
  • Use javadoc comments for public parts
  • Comment the API not the implementation
  • Find a style and follow it
  • API comments done right is your design! Cf. J2SE

37
Effective Java selected items
  • Avoid creating duplicate objects
  • Favor immutability
  • Avoid unnecessary use of checked exceptions
  • Design API signatures carefully
  • Avoid long parameter lists
  • Favor interfaces for parameter types
  • Be selective about convenience methods
  • Be selective about function objects

38
Getter and setters
  • Use with care they often break encapsulation
  • Indirect import and export interfaces
  • Presentation should be hidden in the object
  • no separate GUI-objects
  • No central Swing script
  • Two kinds of safe operations on the object type
    itself, and on primitive values.
  • Make defensive copies of imported/exported
    mutable copies

39
Design Through Refactoring (the XP view)
Design Coverage
Design Quality
Well-designed
Not working
Evolution
Time
Refactor
Refactor
Refactor
Refactor
  • Implement one test-case at a time
  • Extend your design gradually using refactorings
  • Design break-throughs lots of inter-dependent
    refactorings to handle an increment

40
Foundation of Advanced Design
(Gamma et al 95, Meyer 97, etc)
  • Program to an interface, not an implementation
  • Favor object composition over class inheritance
  • Associations needs pattern-support
  • Design for change study what should be variable
    in your design
  • Inherit interfaces only
  • Develop all software for reuse
  • Design only what is needed today refactor
    tomorrow

41
What is Refactoring? (Fowler 2000)
Simple Powerful Design
Refactor
Add Function
MyHack
Bad Design
  • Process of changing existing software such that
  • It does not alter external behaviour
  • Improves internal structure
  • Disciplined way to improve design
  • Order of coding and design unimportant start
    anywhere!
  • Minimal up-front design it emerges during the
    work

42
Ex Remove Middle man
Client class
Client class
Person
getMgr
Person
Department
getMgr
getDep
Department
  • A class is doing too much simple delegation
  • Inverse operation Hide Delegate

43
Ex Introduce Parameter Object
Customer
Customer
Invoice(s, e Date)
Invoice(DateRange)
Recieved(s, e Date)
Recieved(DateRange)
Overdue(s, e Date)
Overdue(DateRange)
  • You have a group of parameters that naturally go
    together
  • Look for behaviour that should go into the new
    class

44
Ex Tease Apart Inheritance
Deal
PresentationStyle
Deal
ActiveDeal
PassiveDeal
ActiveDeal
PassiveDeal
Single
Tabular
TabularActiveDeal
TabularPassiveDeal
  • You have an inheritance hiearchy that is doing
    two jobs at once
  • The most important job stays

45
Three Rules
  • Refactor when you add a function
  • Refactor when you fix a bug
  • Refactor when you do a code review

Dont just read old code refactor it!
46
Bad Smells in Code
  • Duplicated Code
  • Long Method
  • Large Class
  • Long Parameter List
  • Divergent Change
  • Shotgun surgery
  • Feature Envy
  • Data Clumps
  • Primitive Obsession
  • Data Class
  • Refused Bequest
  • Switch Statements
  • Parallel Inheritance
  • Lazy Class
  • Speculative Generality
  • Temporary Field
  • Message Chains
  • Middle man
  • Inappropriate Intimacy
  • Alternative Classes with Different Interfaces
  • Incomplete Library Class

47
Divergent change and Shotgun Surgery
  • You have to change the a class often but for
    different/divergent reasons
  • Split the class
  • Each class should have one type of change
  • For each change you have to change everywhere
  • Restructure so that all that changes goes into
    one class, e.g. move methods and fields
  • Create new classes if needed

48
Data Clumps and Primitive Obsession
  • Data entities moves around in groups in the code
  • Restructure by aggregation
  • Look for data with collective meaning
  • Code is filled with primitive structures, e.g.
    Integers and Dates
  • Introduce small objects
  • Use inheritance polymorphism to minimize
    conditionals

49
Switch Statements
  • Good OO code gt lack of switches
  • A switch often introduce duplication of code
  • Consider polymorphism instead
  • Few case switches replace with separate methods
    in API

50
Summing Up Layers of Design
  • Layer 1 Design for Legacy
  • Industrial investigations
  • De facto situation
  • Existing knowledge and work methods
  • Backwards compatible with top-down etc.
  • Layer 2 Design in the Small
  • Clean simple approach
  • Focus on algorithmic level, e.g. ADTs
  • Specification-driven
  • Layer 3 Design in the Large
  • Code for reuse
  • Yet unknown complexity of systems
  • New territory/products
  • Evolution and third-party-relations
Write a Comment
User Comments (0)
About PowerShow.com