views:

72

answers:

3

Hello,

We have lot of object with this kind of design : Interface and several implementations, and use of several object by composition. Exemple : Foo implements IFoo and have a Bar object who implements IBar Foo also have a setBar(IBar bar) method for injection of dependancie.

My question is : the setter sould't be in the interface ? ( For Testing, Mocking... i'm stuck ! )

A: 

If you are using polymorphism, i.e., calling the setter on the interface type, then obviously you need it in the interface.

Glenn
Yes, but the formal developper dont do it. And i think it's wise to understand why. ( before just adding the setter )
Antoine Claval
A: 

Either inject Bar to Foo using setter Injection. In a context where Foo cannot exist without Bar it would more appropriate to inject Bar with a constructor.

Further Read: Types of dependency injection

AB Kolan
+1  A: 

To have a setter in the interface just for mocking and testing is not good. Thus you permit the users of that interface to arbitrary set components, even though the properties of that object probably shouldn't be modifiable after construction. The interface shouldn't reveal how to construct object.

egaga