The OO Design Principles

Post on 06-May-2015

10.735 views 2 download

description

This presentation describe the basic OO design princples, copied from Uncle Bob's S.O.L.I.D princiles and Pragmatic Programmer's DRY, broken window, DBC, LoD.

Transcript of The OO Design Principles

The OO Design Principles

Steve Zhang

Introduction Software design definition Software nature - entropy Discuss Symptoms of poor software design Discuss 5 OO software design principles Law of Demeter Don’t Repeat yourself principle Design By Contract

The presentation comes from two books

Author: Robert C. MartinNick Name: Uncle Bob

Agile Software Development, principles, patterns and practices

The pragmatic Programmer – from journeyman to master

Andy Hunt Dave Thomas

What is Software Design?

The source code is the design UML diagram represents part of a design, but

it is not the design. Because the design can only be verified

through source code The software design process includes coding,

testing, refactoring… The programmer is real software designer

Software nature – Software entropy Software tends to degrade / decay Software rot – like a piece of bad meat

The cost of change curve

Developers productivity vs. time

Question: does our project manager consider this curve when doing estimations?

Design Smells – The Odors of Rotting Software Rigidity – The design is hard to change Fragility – The design is easy to break Immobility – The design is hard to reuse Viscosity – It is hard to do the right thing Needless complexity – Overdesign Needless Repetition – Mouse abuse Opacity – Disorganized expression

Rigidity

The tendency for software to be difficult to change

Single change causes cascade of subsequent changes in dependent modules

The more modules must be changed, the more rigid the design

Fragility

The tendency for a program to break in many places when a single changes is made

The new problems in area that have no conceptual relationship with the area that was changed

As the fragility of a module increases, the likelihood that a change will introduce unexpected problems approaches certainty.

Immobility

Difficult to reuse A design is immobile when it contains parts

that could be useful in other systems, but the effort and risk involved with separating those parts from the original system are too great.

This is an unfortunate but very common occurrence.

Viscosity

It is easy to do the wrong thing, but hard to do the right thing.

When the design-preserving methods are more difficult to use than the hacks, the viscosity of the design is high

When development environment is slow and inefficient, developers will be tempted to do wrong things

Needless complexity

Overdesign A design smells of needless complexity when

it contains elements that aren't currently useful

The design becomes littered with constructs that are never used

Makes the software complex and difficult to understand.

Needless Repetition The design contains repeating structures that

could be unified under a single abstraction The problem is due to developer’s abuse of

cut and paste. It is really hard to maintain and understand

the system with duplicated code.

Duplication is Evil!

DRY – DON’T REPEAT YOURSELF

Opacity

Opacity is the tendency of a module to be difficult to read and understand

The code does not express its intent well The code is written in an opaque and

convoluted manner

What Stimulates the Software to Rot? Requirements keep change – design

degradation People change – violate the original design Tight schedule pressure

Traditional waterfall process can not prevent software from rotting

• Lack of Feedback• Lack of Communication

The psychology reason – Broken Window Theory

Came from city crime researcher

A broken window will trigger a building into a smashed and abandoned derelict

So does the software Don’t live with the Broken

window

From the book Pragmatic Programmer – From Journeyman to Master

How can we prevent software from rotting? Applies OO design principles

Bad design usually violates design principles Uses design patterns Follows agile practices

Refactoring will reduce the software entropy

S.O.L.I.D Design Principles

SRP – The Single Responsibility Principle OCP – The Open-Closed Principle LSP – The Liskov Substitution Principle ISP – The Interface Segregation Principle DIP – The Dependency Inversion Principle

SRP: The Single-Responsibility Principle A class should have only one reason to

change. If a class has more than one responsibility,

then the responsibilities becomes coupled. SRP is one of the simplest of the principles,

and the one of the hardest to get right.

OCP: The Open-Closed Principle Software entities( classes, modules,

functions, etc.) should be open for extension, but closed for modification

“Open for extension”

The behavior of the module can be extended “Closed for modification”

Extending the behavior of a module does not resulting changes to the source code or binary code of the module.

OCP – Abstraction is the key

Example: Strategy pattern Client is both open and closed

OCP Summary

The Open/Closed Principle is at the heart of object-oriented design

Conformance to OCP is what yields the greatest benefits claimed for object-oriented technology: flexibility, reusability, and maintainability.

Further thinking of OCP Does J2ME preprocess violate OCP or not? My answer: Yes• preprocess itself is anti-OO, give the developer a ba

ckdoor to violate OO brutally• Every time we add a new feature, we have to modify

the existing source code• It is difficult to refactor• Difficult to reuse, maintain and understand• So we should be very careful to use preprocess, use

it as the last choice instead of the first choice• > 90% our preprocess code can be removed!

LSP: Liskov Substitution Principle Subtypes must be substitutable for their base

types. LSP defines the OO inheritance principle. If a client uses a base class, then it should

not differentiate the base class from derived class, which means the derived class can substitute the base class

LSP violation example: A violation of LSP causing a violation of OCPpublic enum ShapeType {square, circle};

public class Shape{ public static void DrawShape(Shape s) { if(s.type == ShapeType.square) (s as Square).Draw(); else if(s.type == ShapeType.circle) (s as Circle).Draw(); }}public class Circle : Shape { public void Draw() {/* draws the circle */}}

public class Square : Shape{ public void Draw() {/* draws the square */}}

Violate OCP

Not substitutable

Another LSP violation example: Rectangle and Square

void g(Rectangle r)

{

r.setWidth(5);

r.setHeight(4);

if(r.getArea() != 20)

throw new Exception("Bad area!");

}

Square’s behavior is changed, so it is not

substitutable to Rectangle

IS-A Relationship

Square is not Rectangle!

LSP is closely related to Design By Contract methodology A routine re-declaration [in a derivative] may

only replace the original precondition by one equal or weaker, and the original post-condition by one equal or stronger.

Derived classes must accept anything that the base class could accept

derived classes must conform to all the post-conditions of the base

DIP: The Dependency Inversion Principlea. High-level modules should not depend on

low-level modules. Both should depend on abstractions.

b. Abstractions should not depend on details. Details should depend on abstractions.

DIP is at the very heart of framework design.

A DIP example

DIP violation

DIP

DIP: an inversion of ownership Inversion is not just one of dependencies,

also one of interface ownership. Clients own the abstraction interfaces. Hollywood principle: “Don’t call us, we’ll call

you”.

DIP: Depend on Abstractions

No variable should hold a reference to a concrete class.

No class should derive from a concrete class. No method should override an implemented

method of any of its base classes.

DIP is also regarded as Dependency Injection & Inversion of Control Dependency injection is the core of the

famous Spring framework.

DIP Summary

Inversion of dependencies is the hallmark of good object-oriented design.

If its dependencies are inverted, it has an OO design; if its dependencies are not inverted, it has a procedural design.

DIP makes abstractions and details isolated from each other, the code is much easier to maintain.

ISP: The Interface Segregation Principle Clients should not be forced to depend on

methods they do not use. ISP deals with designing cohesive interfaces

and avoiding "fat" interfaces. The dependency of one class to another one

should depend on the smallest possible interface.

The interfaces of the class can be broken up into groups of methods.

Each group serves a different set of clients.

An violation of ISP example

ISP violation

An ISP Violation example: solution Segregated

interface

LoD - Law of Demeter Principle of Least Knowledge Only talk to your immediate friends Don’t talk to strangers Write “shy” codes Minimize coupling

LoD formal definition

A method M of an object O may only invoke the methods of the following kinds of objects

1. O itself

2. M's parameters

3. any objects created/instantiated within M

4. O's direct component objects

LoD

LoD violation example

final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();

a.getB().getC().doSomething()

- Transitive Navigation

From book Clean Code – A handbook of Agile Software Craftsman

ship ( Robert C. Martin)

DRY – Don’t Repeat Yourself

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

Following DRY will make software developments easier to understand and maintain

Duplication is Evil

Originated from the book – The pragmatic programmer

How can we prevent duplication? Code duplication – Refactoring code, make it easier

to reuse Defect duplication – communication, code review,

internal forum, internal wiki, and document. System design duplication (spec, configuration,

deployment, database schema) – keep improving the system design

Build duplication – build automation Use meta programming and code generator

technology. Duplication is a waste in software development, we

need to eliminate the waste

DBC - Design By Contract

A contract defines rights and responsibilities between method caller and a routine

Preconditions – the routine’s requirements, it is the caller’s responsibility to pass the good data

Postconditions – What the routine is guaranteed to do

Class invariants – A class ensures that this condition is always true from perspective of a caller

Design By Contract Definition The contract between a routine and any pote

ntial caller can thus be read as

If all the routine’s preconditions are met by the caller, the routine shall guarantee that all posconditions and invariants will be true when it completes.

DBC

DBC concept is developed by Betrand Meyer for the language Eiffel.

We can use assertive programming to implement DBC

assert(string != null); We also use the DBC concept in JUnit test. DBC give us a good concept to write a robust

software, even java does not support it.

Summary

The OO design principles help us: As guidelines when designing flexible,

maintainable and reusable software As standards when identifying the bad design As laws to argue when doing code review

References Book - Agile Software Development, Principles,

Patterns, and Practices, Robert C. Martin Book - Agile Principles, Patterns, and Practices

in C# (Robert C. Martin Series) Book- The Pragmatic Programmer, Article- What is software design?

http://www.bleading-edge.com/Publications/C++Journal/Cpjour2.htm

Resources from Object Mentor website: http://objectmentor.com/resources/omi_reports_index.html

http://mmiika.wordpress.com/oo-design-principles/

Your feedback is very important!

Thank You!