Posts

Showing posts from April, 2010

A more understandable IComparable

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." - Martin Fowler In the .NET framework the IComparable<T> interface is used to compare values: public interface IComparable<T> { int CompareTo(T other); } The comparison is done with the CompareTo method. It returns zero if the current object is equal to the passed in parameter; a negative number if it's less than the parameter; and a positive number if it's greater than it. That's a very non-intuitive return value, reminiscent of the C strcmp function. I know that this scheme is already ingrained in our brains, but it creates code that's not directly decipherable: static int BinarySearch<T>(IList<T> list, T target) where T : IComparable<T> { if (list == null) throw new ArgumentNullException("list"); int lower = 0; int upper = list.Count - 1; while (lower <= upper) { int midd