object design-part-2
DESCRIPTION
TRANSCRIPT
Dhaval Dalal software-artisan.com
Part II: Moving Towards a Simple Design
OBJECT DESIGN
OBJECTCREATION
A E
D
C
B
WAYS TO FULFILL DEPENDENCIES
Create the collaborator within a constructor/method.
Perform a look-up for a collaborator.
Pass the collaborator from outside.
using a Constructor.
using a Setter.
4
INJECT DEPENDENCIES
First of all, avoid concrete instantiation of collaborator objects within a constructor/method of an object.
Avoid making call to ‘new’
If you still have to do it, then encapsulate call to ‘new’ by using
A static Factory Method
Factory.
Builder.
5
INJECT DEPENDENCIES/CLOSURES
Second option, do a “look-up” for the collaborator object
Use a Service Locator.
Third option, inject concrete implementation of a collaborator in to an object at run-time.
Use a DI Container.
Fourth option, inject code block instead of a collaborator.
6
A GENERAL GUIDELINEShort Answer
Dependency Elimination is better than Dependency Inversion
Long AnswerFavor Closure Injection
(where its possible and sensible) over
Dependency Injection over
Look-up over
Concrete Instantiation.
SETTER OR CONSTRUCTOR INJECTION?
A tell tale sign of exposing internal implementation manifests as bunch of getters and setters on the object.
Setters and Getters break the Command/Query Pattern (Tell, Don’t ask principle)
Inject collaborators in Constructors.
THE SIDE EFFECT?
Too many parameters in the Constructor!
<<STEREOTYPICAL RELATIONS>> OBJECT AND ITS
COLLABORATORSReal Dependency
Policy
Part
Notifications
GUIDELINES OF THUMB
Pass only Real Dependencies through constructors.
Without which an object cannot fulfill its responsibilities.
For Policies and Parts
Provide Defaults and allow them to be set through Setters.
For Notifications
Provide NULL/EMPTY Listeners as default and allow new ones to be added/removed using “Adders/Removers”
I STILL HAVE A BIG PARAMETER LIST?
Too many things going on or have more than one concept in that object (SRP violation).
Break-up the object.
This will collapse the parameter list.
12
THE RESULT?
Fewer unintended consequences from code changes and more flexibility in your systems.
Creates Objects that are isolated from each other.
Makes large scale re-structuring of the system possible.
13
VALUE OBJECTS
Must have value semantics.
Immutability
Value once set, cannot be changed.
Operations on them, returns new value objects
Object’s Identity is its value
Equality
Strive to reuse value objects
REFERENCES
Agile Principles, Patterns and Practices
Robert C. Martin and Micah Martin
Object Design
Rebecca Wirfs-Brock and Alan McKean
Alec Sharp
The Pragmatic Programmers
Mock Roles, not Objects
Paper by Steve Freeman, Nat Pryce, Tim Mackinnon, Joe Walnes
InfoQ presentation by
Steve Freeman and Nat Pryce
Head-First Design Patterns Book
Venkat Subramaniam’s Blog