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.
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?