lundi 30 novembre 2015

Dependency Injection and IoC practices in a inherently tight coupling design

What's the best practice when dealing with a situation like the following (simplified symbolic analogous case, not asking for a particular implementation solution):

Imagine I want to create a custom class that represents my physical Calendar at my office desktop. It can be translated in Java as a GregorianCalendar(myCustomZone).

So, I create a class such as:

 class MyOfficeCalendar extends GregorianCalendar{
   public MyOfficeCalendar(){
        super(new SimpleTimeZone(...));
   }
 }

In these cases, code reviewers would say that instantiation in the constructor is a bad idea. But if I inject the SimpleTimeZone dependency into the constructor this seems to me like error prone, since my dependency only be instantiated in a desired way. I want the control at that scope, not exposing the possibility of erroneous injection. I mean, that certain instantiation is part of my caller class behaviour or paradigm. The definition of MYOfficeCalendar is precisely a GregorianCalendar working with this particular custom TimeZone instance.

So what is the best design usually in those cases?

  • Force MyCalendar to be flexible enough to be incoherent and rely on a correct IoC container xml or user

  • Instantiate in the constructor the absolute desired dependence

  • Manage the Whole thing without my convenient OOP class (I lie to adhere to the SingleResponsabilityPrinciple as muc as I can)

  • Change the whole architecture ?

Aucun commentaire:

Enregistrer un commentaire