The OO Design Principles

53
The OO Design Principles Steve Zhang

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

Page 1: The OO Design Principles

The OO Design Principles

Steve Zhang

Page 2: The OO Design Principles

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

Page 3: The OO Design Principles

The presentation comes from two books

Author: Robert C. MartinNick Name: Uncle Bob

Agile Software Development, principles, patterns and practices

Page 4: The OO Design Principles

The pragmatic Programmer – from journeyman to master

Andy Hunt Dave Thomas

Page 5: The OO Design Principles

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

Page 6: The OO Design Principles

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

Page 7: The OO Design Principles

The cost of change curve

Page 8: The OO Design Principles

Developers productivity vs. time

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

Page 9: The OO Design Principles

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

Page 10: The OO Design Principles

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

Page 11: The OO Design Principles

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.

Page 12: The OO Design Principles

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.

Page 13: The OO Design Principles

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

Page 14: The OO Design Principles

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.

Page 15: The OO Design Principles

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

Page 16: The OO Design Principles

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

Page 17: The OO Design Principles

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

Page 18: The OO Design Principles

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

Page 19: The OO Design Principles

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

Page 20: The OO Design Principles
Page 21: The OO Design Principles
Page 22: The OO Design Principles

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

Page 23: The OO Design Principles

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.

Page 24: The OO Design Principles

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.

Page 25: The OO Design Principles

OCP – Abstraction is the key

Example: Strategy pattern Client is both open and closed

Page 26: The OO Design Principles

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.

Page 27: The OO Design Principles

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!

Page 28: The OO Design Principles

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

Page 29: The OO Design Principles

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

Page 30: The OO Design Principles

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!

Page 31: The OO Design Principles

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

Page 32: The OO Design Principles

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.

Page 33: The OO Design Principles

A DIP example

DIP violation

DIP

Page 34: The OO Design Principles

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”.

Page 35: The OO Design Principles

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.

Page 36: The OO Design Principles

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

famous Spring framework.

Page 37: The OO Design Principles

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.

Page 38: The OO Design Principles

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.

Page 39: The OO Design Principles

An violation of ISP example

ISP violation

Page 40: The OO Design Principles

An ISP Violation example: solution Segregated

interface

Page 41: The OO Design Principles

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

Page 42: The OO Design Principles

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

Page 43: The OO Design Principles

LoD

Page 44: The OO Design Principles

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)

Page 45: The OO Design Principles

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

Page 46: The OO Design Principles

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

Page 47: The OO Design Principles

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

Page 48: The OO Design Principles

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.

Page 49: The OO Design Principles

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.

Page 50: The OO Design Principles

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

Page 51: The OO Design Principles

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/

Page 52: The OO Design Principles

Your feedback is very important!

Page 53: The OO Design Principles

Thank You!