View
333
Download
0
Category
Tags:
Preview:
DESCRIPTION
Talk about Design Patterns for Malaysian JUG (Kuala Lumpur talk) and Jakarta JUG (Gunadarma Univerty talk - Depok)
Citation preview
Agnès CREPET @agnes_crepetCyril LACÔTE @clacote1st November – Gunadarma University
Once upon a -Design- TimeObject Oriented Design principles
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
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»)
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
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 ?
Top–down approach
Approach by decomposition
Break down the problem into subproblems
Apply this same principle to each ones
→ tree decomposition
Divide and conquer
Top–down approach
File opening
File processing
File closingWhile there are records
Invoice processing Asset processing
Amount processing
AccountRead AmountCompute AccountUpdate
Amount processing...
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
Modularity
Code reusability
Function
Module
Sub-Module
Requires a strict separation
Data / Processing
FORTRAN 58, ALGOL 60, PASCAL 70, C 73
Towards Encapsulation
Weak coupling between data and processing structures
Development no longer driven by processing
Unlike COBOL-related methodologies
Consecration: object paradigm!
Objet Paradigm : kind of old !
60s : research at MIT lab
Modula : 1967
SmallTalk : 1972
C++ : 1981
Java : 1995
Objet : motivations
A basic idea :
Close to the real world
start( )accelerate( )
velocity
mark
Car
Abstraction
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!
Objet Oriented design
Design challenges :
Build a system capable of evolving
By maximizing the reuse
To improve both quality and productivity
Easy maintenance !
A good Objet Oriented design?
No absolute solution:
Principles rather than rules
Methodological practices
Acknowledged architectures
Tried and tested recipes: Design Patterns
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
The idea of Design Patterns
Loads of long lists everywhere
tedious, boring : not needed here
Rather try to understand the challenges!
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
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!
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.
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
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
Fundamental features :
Encapsulation
Inheritance
Polymorphism
Elementary frames for good design principles
Object's foundations
Encapsulation
« Black box » objects
Interface :What I know
What I can do
Implementation:None of your
business !
Go !
Brake ! To the left !
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
Encapsulation
Pros :
Ensures data integrity
Enables to change implementation
Reduces side-effects
DEMO!
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()
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
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!
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
Responsibilities assignment
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
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
G.R.A.S.P. : Low coupling (1/2)
Evaluates interdependency between components
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)
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 !
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
So?How to ensure low coupling and high
cohesion?
Dependency managementInversion of control
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
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
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
Dependency injection : example
Example :
Mario has a suit...
Three approaches :
1 - Elementary, without injection
2 - With manual injection
3 - With container injection
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();
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
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();
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)
3 - Injection with a container
Modeling is the same
Only the use changes:
XML configuration or through annotations
Context loading
Suit retrieving
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;
}
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
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
Architectural Patterns2 big families
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)
?
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
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
Conclusion
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 !
Bibliography
Source Code on GitHub
https://github.com/acrepet/JMarioGame
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
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
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
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
Recommended