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.