Depending on Functions Instead of Interfaces: Why and How

See the original posting on DZone Python

Here’s a simple, contrived example of a class that depends on an interface, IDoesMath, followed by the same class modified to depend on a function instead. As you’ll quickly see, there is no immediate benefit. The change doesn’t make this a better class. So are there any benefits to depending on functions rather than interfaces? I think that at least in some cases, depending on functions has potential to improve the long-term maintainability of our code (Can I be any more careful to qualify that statement?).

Depends on an Interface

public class ClassThatDependsOnMath  
{ 
    private readonly IDoesMath _math; // interface

    public ClassThatDependsOnMath(IDoesMath math) 
    {
        _math = math; 
    }

    public Single Calculate(Single value1, Single value2)
    {
        return _math.DoMath(value1, value2);
    }
}

Depends on a Function

public class ClassThatDependsOnMath
{
    private readonly Func<Single, Single, Single> _doMath; // function

    public ClassThatDependsOnMath(Func<Single, Single, Single> doMath)
    {
        _doMath = doMath;
    }

    public int Calculate(Single value1, Single value2)
    {
        return _doMath(value1, value2);
    }
}

Again, I don’t see a compelling difference. The interface actually makes it a little bit easier to see what the dependency does (more on that later.) So why would we ever consider the second approach?