Design poo my_jug_en_ppt

63
Agnès CREPET @agnes_crepet Cyril LACÔTE @clacote 1st November – Gunadarma University Once upon a -Design- Time Object Oriented Design principles

description

Talk about Design Patterns for Malaysian JUG (Kuala Lumpur talk) and Jakarta JUG (Gunadarma Univerty talk - Depok)

Transcript of Design poo my_jug_en_ppt

Page 1: Design poo my_jug_en_ppt

Agnès CREPET @agnes_crepetCyril LACÔTE @clacote1st November – Gunadarma University

Once upon a -Design- TimeObject Oriented Design principles

Page 2: Design poo my_jug_en_ppt

Schedule

A bit of history

What's a good object-oriented (OO) design?

The main principles of the OO design

Not an inventory of Design Patterns!

Dependency Management

Inversion of control

Architecture patterns

Page 3: Design poo my_jug_en_ppt

A bit of history

Open («file»)

Read:

read (record)

if (eof)

go to End-File

if (code == «INVOICE»)

go to Invoice

if (code == «CREDIT»)

go to Credit

if (code == «PROFORMAT»)

go to Read

In the beginning : the Go To statement

Invoice: Process invoice go to Computation Credit: Process credit go to ComputationComputation: Read account Compute amount Update account go to Read:End-File: close («file»)

Page 4: Design poo my_jug_en_ppt

Beyond the GOTO

« Go To Statement Considered Harmful »

Edsger W. Dijkstra, 1968

Any program with a single input can be built only with the following structures:

sequence (an ordered execution of statements)

iterative statement : loop

conditional statement : if – else, switch, case

Page 5: Design poo my_jug_en_ppt

Structured Programming

Open («file»)

read (record)

while (eof == false)

if (record.code == «INVOICE»)

ProcessInvoice()

else if (record.code == «CREDIT»)

ProcessCredit()

else

continue

end-if

ReadAccount()

ComputeAmount()

UpdateAccount()

read (record)

end-while

close («file»)

ex : C language

Reusable functions

Control structures

Methodology ?

Page 6: Design poo my_jug_en_ppt

Top–down approach

Approach by decomposition

Break down the problem into subproblems

Apply this same principle to each ones

→ tree decomposition

Divide and conquer

Page 7: Design poo my_jug_en_ppt

Top–down approach

File opening

File processing

File closingWhile there are records

Invoice processing Asset processing

Amount processing

AccountRead AmountCompute AccountUpdate

Amount processing...

Page 8: Design poo my_jug_en_ppt

Top–down approach

Warnier's Method (1974)

Used in loads of huge COBOL programs

Good reliability in the writing of programs

But very low evolutivity :

Does not highlight the code to reuse

Any change requires modification of all programs

Page 9: Design poo my_jug_en_ppt

Modularity

Code reusability

Function

Module

Sub-Module

Requires a strict separation

Data / Processing

FORTRAN 58, ALGOL 60, PASCAL 70, C 73

Page 10: Design poo my_jug_en_ppt

Towards Encapsulation

Weak coupling between data and processing structures

Development no longer driven by processing

Unlike COBOL-related methodologies

Consecration: object paradigm!

Page 11: Design poo my_jug_en_ppt

Objet Paradigm : kind of old !

60s : research at MIT lab

Modula : 1967

SmallTalk : 1972

C++ : 1981

Java : 1995

Page 12: Design poo my_jug_en_ppt

Objet : motivations

A basic idea :

Close to the real world

start( )accelerate( )

velocity

mark

Car

Abstraction

Page 13: Design poo my_jug_en_ppt

Why the object paradigm?

Doc

Design

Test

Code

Other

Maintenance

Source: DP Budget, Vol. 7, Dec 1998.

Maintainable

Flexible

Extensible

Project costs:

15% development

70% maintenance!

Page 14: Design poo my_jug_en_ppt

Objet Oriented design

Design challenges :

Build a system capable of evolving

By maximizing the reuse

To improve both quality and productivity

Easy maintenance !

Page 15: Design poo my_jug_en_ppt

A good Objet Oriented design?

No absolute solution:

Principles rather than rules

Methodological practices

Acknowledged architectures

Tried and tested recipes: Design Patterns

Page 16: Design poo my_jug_en_ppt

Design Patterns

Named pair "problem / solution"

Typical relationships between classes

To Design what Algorithms are to Development

23 historical patterns:

Gang of Four (GoF) : Erich Gamma, Richard Helm, Ralph Johson, John Wlissides, "Design Pattern. Elements of Reusable Object-oriented sofware", 1995

Page 17: Design poo my_jug_en_ppt

The idea of Design Patterns

Loads of long lists everywhere

tedious, boring : not needed here

Rather try to understand the challenges!

Page 18: Design poo my_jug_en_ppt

The challenge of the Design Patterns

"Not Invented Here" syndrome (NIH)

Formalize an expertise

Accessible to a non-expert

Facilitate communication: a common language

Designed for reuse and maintenance

Language-agnostic

Implement general principles

Page 19: Design poo my_jug_en_ppt

A basic principle : OCP (1/2)

Open - Close Principle (OCP)

Each software entities (classes, modules, functions, etc.) should be :

open to extensionsadd new behaviors

→ Adapt to change !

but closed to modificationsExisting code cannot be changed, only additions are

allowed.

→ Do not break what works!

Page 20: Design poo my_jug_en_ppt

A basic principle : OCP (2/2)

Not a foolproof recipe

But a philosophy to reach for maintainable software.

All other principles are just applications of this basic principle.

Page 21: Design poo my_jug_en_ppt

KISS : Keep It Simple, Stupid !

Simplicity is a key factor

Simple code is :Quicker to write

Less buggy

Easier to understand and maintain

Good design principles

Page 22: Design poo my_jug_en_ppt

DRY : Don't Repeat Yourself

“Single source of Truth”

Avoid code repetitions

Single out abstractions

YAGNI : You Ain't Gonna Need It !

Never foresee a future need

Single out pragmatic design

Good Design Principles

Page 23: Design poo my_jug_en_ppt

Fundamental features :

Encapsulation

Inheritance

Polymorphism

Elementary frames for good design principles

Object's foundations

Page 24: Design poo my_jug_en_ppt

Encapsulation

« Black box » objects

Interface :What I know

What I can do

Implementation:None of your

business !

Go !

Brake ! To the left !

Page 25: Design poo my_jug_en_ppt

Encapsulation

Hides implementation details

Encapsulated data :

Private attributes

Outside world can't manipulate it

Public methods :

Service provided to outside

Defined (and only!) access points

Page 26: Design poo my_jug_en_ppt

Encapsulation

Pros :

Ensures data integrity

Enables to change implementation

Reduces side-effects

DEMO!

Page 27: Design poo my_jug_en_ppt

Inheritance

Sharing common characteristics

Both attributes & behaviors

Generalization

Specialization

Person name : String eat()

Person name : String eat()

Employee name : String employer : String eat() work()

Employee name : String employer : String eat() work()

Person name : String eat()

Person name : String eat()

Employee employer : String work()

Employee employer : String work()

Page 28: Design poo my_jug_en_ppt

Polymorphism

A method invocation :

Triggers different behavior according to type

Implementation is chosen by targeted object

Objects have to collaborate :

without knowing their actual type

using one of same type the same way

Page 29: Design poo my_jug_en_ppt

Interface :

a set of public abstract methods

implemented by various classes

Think “service contract”

Polymorphism without inheritance

How polymorphism could be a solution for OCP challenge?

Polymorphism's way to reach OCP

DEMO!

Page 30: Design poo my_jug_en_ppt

Following upper principles

Like a vain wish...

Code can't be fully closed

Choose violation strategically

Estimate change probability

OCP is an utopian goal to reach

a condition for re-usability in an ever-changing context

Page 31: Design poo my_jug_en_ppt

Responsibilities assignment

Page 32: Design poo my_jug_en_ppt

How to assign responsibilities to classes

Who do what?

What is a responsibility?

Knowing (other objects, computation results, ...)

Doing (use, collaborate, coordinate, ...)

→ General Responsibility Assignment Software Patterns

[Graig Larman, "Applying UML and Patterns", 1998]

Responsibilities assignment

Page 33: Design poo my_jug_en_ppt

G.R.A.S.P : Information Expert

Which class should I give a responsibility to ?

→ Give it to the object having enough information to assume it.

"Knowing is doing”

It's the elementary principle

Page 34: Design poo my_jug_en_ppt

G.R.A.S.P. : Low coupling (1/2)

Evaluates interdependency between components

Page 35: Design poo my_jug_en_ppt

High coupling is a disadvantage :

Understandability, maintainability, reusability

Matters when you use an unstable component.

But being strongly coupled to a stable component is not an issue.

G.R.A.S.P. : Low coupling (2/2)

Page 36: Design poo my_jug_en_ppt

G.R.A.S.P. : High cohesion

Responsibilities of a given component should be strongly related.

Cohesion drops when:

Class responsibilities are not focused

A responsibility is dispatched onto several classes

Just do your job !

Page 37: Design poo my_jug_en_ppt

Watch for the fat !

Obesity:

If responsibilities are diluted

Coupling rises for assuming it

A code change will impact other functionalities

Low coupling / High cohesion are intimately linked

Higher cohesion → lower coupling

Page 38: Design poo my_jug_en_ppt

So?How to ensure low coupling and high

cohesion?

Page 39: Design poo my_jug_en_ppt

Dependency managementInversion of control

Page 40: Design poo my_jug_en_ppt

There will be consequences

Dependency A → B

Impossible to

deploy A without B

reuse A without B

A modification on B

has side-effect on A

needs A to be recompiled

A

A

A

uses

is linked to

inherits of

B

B

B

Page 41: Design poo my_jug_en_ppt

Inversion of control : principle

Hollywood principle :

“Don't call us, we'll call you”

Inversion of control is a generic word.

Several usages

The most famous : dependency injection

Objects won't seek their dependencies

They will be provided by a third-party

Page 42: Design poo my_jug_en_ppt

Inversion of control : put into play

A bean container can inject those dependencies, at instantiation time

though constructor parameters,

or through property setters after instantiation

That what “light” containers do :

Spring, Guice, Weld

Page 43: Design poo my_jug_en_ppt

Dependency injection : example

Example :

Mario has a suit...

Three approaches :

1 - Elementary, without injection

2 - With manual injection

3 - With container injection

Page 44: Design poo my_jug_en_ppt

1 - Elementary : without injection

package com.injection.none;

import com.injection.none.BlueSuit;

public class JMario {

private BlueSuit bluesuit = new BlueSuit();

public void onActionButton() {

bluesuit.execute(this);

}

}

Use: JMario jMario = new JMario();

jMario.onActionButton();

Page 45: Design poo my_jug_en_ppt

1 - Without injection : Appraisal

Closed modeling

Mario can only have a suit

High coupling (connection, creation, use)

Dependency to the blue suit

Inability to change without recompiling Mario

Page 46: Design poo my_jug_en_ppt

2 - Manual injection

package com.injection.with;

public class JMario {

private Suit suit;

public void onActionButton(){

suit.execute(this);

}

public void setSuit(Suit suit) {

this.suit = suit;

}

}

Use:

JMario jMario = new JMario();

Suit blueSuit = new BlueSuit();

jMario.setSuit(blueSuit);

jMario.onActionButton();

Page 47: Design poo my_jug_en_ppt

2 - Manual injection : Appraisal

Pros:

Mario exposes its dependency through the setter

No dependency to implementations

It could wear any suit

Cons:

The use is frozen (recompilation required to change the suit)

Page 48: Design poo my_jug_en_ppt

3 - Injection with a container

Modeling is the same

Only the use changes:

XML configuration or through annotations

Context loading

Suit retrieving

Page 49: Design poo my_jug_en_ppt

3 - Injection with a container

XML configuration (example : Spring) : <beans>

<bean id="theBlueSuit" class="com.injection.with.suit.BlueSuit" />

<bean id="mario" class="com.injection.with.JMario">

<property name="suit" ref="theBlueSuit" />

</bean>

</beans>

Configuration by annotations (JEE6): public class JMario {

@Inject

private Suit suit;

}

Page 50: Design poo my_jug_en_ppt

3 - Injection with a container : Appraisal

Same benefits as manual injection

Everything is parameterized

you still have to configure the injection!

Centralized in XML

Type-safe with annotations

It is not even necessary to recompile with XML configuration

Page 51: Design poo my_jug_en_ppt

Inversion of control : conclusion

Low coupling

Easy to replace components

Simplified maintenance

Implementations are independent of use context

Reusable components

Modular and incremental development

Simplified tests:

Dependencies already isolated

Mock-objects

Page 52: Design poo my_jug_en_ppt

Architectural Patterns2 big families

Page 53: Design poo my_jug_en_ppt

Application Architecture : Example

Java web Application

Application layers (presentation,

service, business…

HTML/ JavaScript

HTTP

… and persistence)

RDBMS

JDBC

Browser

Application Server (ex : JBoss)

DataBase Server (Ex: Oracle)

ApplicationOutside

(CompanyInformation

system)

?

Page 54: Design poo my_jug_en_ppt

Lean Service Oriented Architecture (SOA)

Control (Business services / repositories) is the main component

Anemic Object Model

No Business logic

Strict image of DB (POJO)

Mainly procedural programming

J2EE leaded to forget about OO programming!

Facades

BusinessServices

Repository

RDBMS

Do

ma

in O

bje

cts

Page 55: Design poo my_jug_en_ppt

Domain Driven Architecture

Domain Entities are the corner stone of the application

manage their state

and their state's persistence

and implement business logic

→ PDO (Persistent Domain Object)

Services (Control) lose application logic

Perhaps not needed anymore!

Repository

SGBDR

Domain Object

Page 56: Design poo my_jug_en_ppt

Conclusion

Page 57: Design poo my_jug_en_ppt

Conclusion

Answers?

No miracle recipes..

Familiarize with those principles to raise the good questions

Design patterns are not mandatory

Tackle to user needs first

then with an added value (maintainability always !)

Lead to a design-driven approach

New development cycles

Agile methodologiesStay humble,But think big !

Page 58: Design poo my_jug_en_ppt

Bibliography

Page 59: Design poo my_jug_en_ppt

Source Code on GitHub

https://github.com/acrepet/JMarioGame

Page 60: Design poo my_jug_en_ppt

Bibliography

Design Patterns - Catalogue des modèles de conceptions réutilisables [GOF], Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides ; Vuibert; Juillet 1997 ; ISBN: 2-7117-8644-7

Design Patterns CD - Elements of Reusable Object-Oriented Software De Erich Gamma, Richard Helm, Ralph Johnson et John Vlissides - Addison Wesley Mai 1998 -

Refactoring to patterns, J. Kerievsky ; Addison Wesley; Septembre 2004 ; ISBN: 2-7117-8644-7

Page 61: Design poo my_jug_en_ppt

Bibliography

Patterns of Enterprise Application Architecture [PEAA] de Martin Fowler – 2002 – Hardcover

Refactoring : Improving the Design of Existing Code de Martin. Fowler - 1999 [PEAA] - Addison-Wesley

Page 62: Design poo my_jug_en_ppt

Bibliography

"Real World Java EE Night Hacks - Dissecting the Business Tier"Adam Bien – 2009 - Press Adam Biem

"Real World Java EE Patterns - Rethinking Best Practices "Adam Bien – 2011- Press Adam Bien

Page 63: Design poo my_jug_en_ppt

Bibliography : websites

Jon Pearce website about patterns: http://www.cs.sjsu.edu/~pearce/modules/patterns/

index.htm

Martin Fowler website:

http://martinfowler.com

Adam Bien website:

http://www.adam-bien.com

About "Domain-Driven Design" approach :

http://domaindrivendesign.org