Sviatoslav Iakovlev
Sviatoslav Iakovlev

Reputation: 36

Is using generic interface justifies using another marker interfaces?

Let's assume I have an interface that has some method parametherized with another interface:

interface IFeature<T> where T : IFeatureParameters
{
    CustomObject Apply(CustomObject obj, T featureParameters);
}

But features are so much different that there is nothing common in their parameters so IFeatureParameters interface is in fact marker interface. It just forces developers in future to create Feature and FeatureParameters implementations in pairs.

As far as I googled, marker interfaces are considered to have no reasons to exist in custom code.

Is it suitable to use marker interfaces in my case? If not, what may substitute it?

Upvotes: 0

Views: 659

Answers (1)

Ruud Helderman
Ruud Helderman

Reputation: 11028

An interface IFeatureParameters has no added value here. Whether or not a class (or whatever type you like) is a valid type to pass parameters to a feature, is entirely determined by the feature implementation. Every time a developer makes a new implementation of interface IFeature, they will specify explicitly what is the correct parameter type, by filling in the type variable T. That is enough to ensure no 'alien' types will be passed into an implementation of method Apply.

Here is a simple example.

public class FeatureParametersA
{
    public string SomeText;
}

public class FeatureParametersB
{
    public int SomeNumber;
}

I could have made these classes implement an interface IFeatureParameters, but that is not required.

public interface IFeature<T>
{
    CustomObject Apply(CustomObject obj, T par);
}

public class FeatureA : IFeature<FeatureParametersA>
{
    public CustomObject Apply(CustomObject obj, FeatureParametersA par);
    {
        obj.Add(par.SomeText);
        return obj;
    }
}

public class FeatureB : IFeature<FeatureParametersB>
{
    public CustomObject Apply(CustomObject obj, FeatureParametersB par);
    {
        obj.Add(par.SomeNumber.ToString());
        return obj;
    }
}

Notice how each class has its own dedicated implementation of Apply, specific for the related 'parameters' type. Everything is strongly typed, so the compiler will prevent anyone from trying to pass the wrong type into Apply.

For completeness:

public class CustomObject
{
    public void Add(string s) { _sb.AppendLine(s); }
    private StringBuilder _sb = new StringBuilder();
}

Upvotes: 1

Related Questions