WAYS TO FULFILLDEPENDENCIESCreate the collaborator within a constructor/method.Perform a look-up for a collaborator.Pass the collaborator from outside.using a Constructor.using a Setter.
4INJECT DEPENDENCIESFirst of all, avoid concrete instantiation ofcollaborator objects within a constructor/method ofan object.Avoid making call to ‘new’If you still have to do it, then encapsulate call to ‘new’by usingA static Factory MethodFactory.Builder.
5INJECT DEPENDENCIES/CLOSURESSecond option, do a “look-up” for the collaboratorobjectUse a Service Locator.Third option, inject concrete implementation of acollaborator in to an object at run-time.Use a DI Container.Fourth option, inject code block instead of acollaborator.
6A GENERAL GUIDELINEShort AnswerDependency Elimination is better than DependencyInversionLong AnswerFavor Closure Injection(where its possible and sensible)overDependency InjectionoverLook-upoverConcrete Instantiation.
SETTER OR CONSTRUCTORINJECTION?A tell tale sign of exposing internal implementationmanifests as bunch of getters and setters on theobject.Setters and Getters break the Command/QueryPattern (Tell, Don’t ask principle)Inject collaborators in Constructors.
THE SIDE EFFECT?Too many parameters in the Constructor!
<<STEREOTYPICAL RELATIONS>>OBJECT AND ITSCOLLABORATORSReal DependencyPolicyPartNotiﬁcations
GUIDELINES OF THUMBPass only Real Dependencies through constructors.Without which an object cannot fulﬁll its responsibilities.For Policies and PartsProvide Defaults and allow them to be set through Setters.For NotiﬁcationsProvide NULL/EMPTY Listeners as default and allow new onesto be added/removed using “Adders/Removers”
I STILL HAVE A BIGPARAMETER LIST?Too many things going on orhave more than one concept in that object (SRP violation).Break-up the object.This will collapse the parameter list.
12THE RESULT?Fewer unintended consequences from code changesand more ﬂexibility in your systems.Creates Objects that are isolated from each other.Makes large scale re-structuring of the system possible.
13VALUE OBJECTSMust have value semantics.ImmutabilityValue once set, cannot be changed.Operations on them, returns new value objectsObject’s Identity is its valueEqualityStrive to reuse value objects
REFERENCESAgile Principles, Patterns andPracticesRobert C. Martin and MicahMartinObject DesignRebecca Wirfs-Brock and AlanMcKeanAlec SharpThe Pragmatic ProgrammersMock Roles, not ObjectsPaper by Steve Freeman, NatPryce,Tim Mackinnon, JoeWalnesInfoQ presentation bySteve Freeman and Nat PryceHead-First Design Patterns BookVenkat Subramaniam’s Blog