Question

I have an interface called IEvaluator as a part of library I have created.

public interface IEvaluator<T>
{
    public bool Evaluate<T>(T key, T value);
}

Earlier it used to evaluate whether key is equal to value or not. Now, I want to add support for more operators in it say less than, greater than etc keeping it backward compatible at the same time i.e. only those people who want extended support should update their code and not others. I know that .NET provides an similar interface called IComparer<T> but using that is not an option here.

I tried few approached but non of them seems to work

  • Put operator as default argument.

    public interface IEvaluator<T>
    { 
        public bool Evaluate<T>(T key, T value, string operatorVal = "=");
    }
    
  • Add a new method in the interface and provide its implementation using extension methods.

    public interface IEvaluator<T>
    { 
        public bool Evaluate<T>(T key, T value);
        public bool Evaluate<T>(T key, T value, string operatorVal = "=");
    }
    
    public static class ExtensionMethods
    {
        public static bool Evaluate<T>(this.IEvaluator evaluator, T key, T value, string operatorVal = "=")
        {
            return evaluator.Evaluate(key, values);
        }
    }
    

In both the cases, I'm getting that the function with default argument is not implement. What is the correct way of doing such kind of enhancement?

Was it helpful?

Solution

You can't, basically. If someone has implemented the original interface, their code doesn't expose any way of using other operators... so you can't expose the extra method without breaking their code.

One option would be to create a new interface which extended the old one:

public interface IFlexibleEvaluator<T> : IEvaluator<T>
{ 
    bool Evaluate<T>(T key, T value, string operatorVal);
}

Then implementations could add support at their leisure. They could perform the "default to equality" part themselves.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top