Reputation: 105029
I would like to extract an interface of a class that needs initilization.
public class Example<T>
{
public Example(SomeData data)
{
// initialize self with data
}
public IEnumerable<T> GetObjects(SomeData data)
{
// extract data
}
}
The problem is that we can't write an interface that would enforce non-default type constructors. I could of course change my class to:
public interface IExample<T>
{
void Initilize(SomeData data);
IEnumerable<T> GetObjects(SomeData data);
}
public class Example<T> : IExample<T>
{
public void Initilize(SomeData data)
{
// initialize self with data
}
public IEnumerable<T> GetObjects(SomeData data)
{
// extract data
}
}
But this is not the same, because when one would instantiate this type could directly call into GetObjects
which would then result in an exception that instance is not initilized.
Upvotes: 1
Views: 112
Reputation: 74909
As this is just an interface, you shouldn't care about the constructor. The interface defines what the implementations can do but not specifically how they do it or what order methods are called in.
How can you realistically say that in the future there won't be some implementation of the interface that works differently and doesn't require the constructor?
Upvotes: 3
Reputation: 51329
You don't. The constructor arguments are an implementation detail of the class- they are irrelevant to the interface unless you decide to make GetObjects
a read/write property.
Somewhere you are constructing a concrete instance, and you already know about the class itself there, so you know that you need to pass certain constructor arguments.
If you really want to enforce this idea that "All IExamples must be constructed with some arguments" externally, use a Factory pattern:
public static class ExampleFactory {
public static IExample<T> MakeAnExample(SomeData data) {
// return some concrete implementation...
}
}
Upvotes: 1