Note: This question is related to an advice rather than an issue.
I would like to know when I should use an interface and when I should not.
In order to make it clear about my question, I am going to write my current implementation with and without interface:
WITH INTERFACE
interface IObjectBuilder
{
string Build();
}
class ObjectABuilder: IObjectBuilder
{
ObjectABuilder(Object A){}
public string Build();
}
class ObjectBBuilder: IObjectBuilder
{
ObjectBBuilder(Object B){}
public string Build(){}
}
WITHOUT INTERFACE 1:
class ObjectABuilder
{
ObjectABuilder(Object A){}
public string Build(){}
}
class ObjectBBuilder
{
ObjectBBuilder(Object B){}
public string Build(){}
}
WITHOUT INTERFACE 2:
class ObjectABuilder
{
public string Build(Object A){}
}
class ObjectBBuilder
{
public string Build(Object B){}
}
So, I would like to know, in this case:
-
Should I use with and without interface and why?
-
For the case of using without interface, what do you think of constructing the class with objectA (b) is better or just pass it directly in the method?
Thanks in advance.
You don’t always need an
interface. They’ll reach a point where you do, perhaps you want to share with another module, and you’d rather it only took a dependency on aninterfacerather than a concrete implementation? Perhaps you want to test implementation of an interface for a unit test? I’d say start without an interface until you can demonstrate you need it.For your second question, do other methods in the class need that
Object? If yes, then I’d pass it in the constructor so that those methods can share thatObject. If not then I’d keep it passed in.The common theme is to DTSTTCPW