Search code examples
c#language-agnosticdesign-principles

Is it a principle to always have the most abstract parameters and if so does it have a name?


For example, one might have a method max on an integer array.

public static int Max(int[] ints)
{
    var max = ints[0];
    foreach(var i in ints)
    {
        if(i > max)
        {
            max = i;
        }
    }
    return max;
}

But actually we didn't utilize the fact that were were using an array, just that we could iterate over them, and we didn't need ints, we just needed an object that knows how to compare itself. So a more powerful method might be:

public static T MyMax<T>(IEnumerable<T> ts) where T : IComparable<T>
{
    var max = ts.First();
    foreach(var i in ts)
    {
        if(i.CompareTo(max) > 0)
        {
            max = i;
        }
    }
    return max;
}

And I guess the above discounts the fact that the IEnumerable<T> could be infinite which would cause this to hang indefinitely, but then why are you trying to find the Max fo an infinite iterable in the first place.

The point I'm trying to make is that the second method is much more powerful than the former, as it makes the least assumptions about it's parameters as needed. Is there a name for such a principle? Is this even a thing?

Thanks in advance.


Solution

  • I would call this Programming to an Interface.

    The design principle of Programming to an Interface is most commonly mentioned in the context of declaring variables, and that's how the famous Gang of Four book introduced the principle; but it applies equally well to declaring method parameters.

    Don't declare variables to be instances of particular concrete classes. Instead, commit only to an interface defined by an abstract class. You will find this to be a common theme of design patterns...

    The term variables here can be considered in a broad sense that includes method parameters.