This article is more than 1 year old

First among equals

The contract metaphor is an effective way of approaching API design

This is about the simplest, contract-satisfying implementation you can imagine. A contract overspecified to require the result to -1, 0 or +1 would not be a great benefit to the caller but it would be a burden to the implementer:

public final class Date implements Comparable
{
    ...
    public int compareTo(Object other)
    {
        return sgn(day - ((Date) other).day);
    }
    private static int sgn(int value)
    {
        return value < 0 ? -1 :
               value > 0 ? +1 : 0;
    }
    private int day;
}

Alternatively, the implementer could write out the logic longhand and inline within the compareTo method.

The same justification of the less strict contract also applies to field-based representations [7]. Instead of comparing field by field, treat the date as an ordered but discontinuous number range and subtract the right-hand side from the left-hand side. For example, the dates 6th April 2002 and 21st February 1998 can be treated as decimal numbers, 20020406 and 19980221, which are easily obtained by multiplying up and adding the respective year, month and day fields. To discover the relative ordering of 6th April 2002 and 21st February 1998 one simply has to subtract the second figure from the first, which yields a positive number and, therefore, the conclusion that 6th April 2002 naturally orders after 21st February 1998.

Most programmers attempting this task get caught up in a logic and control flow thicket that, as a by-product, happens to return precisely -1, 0 or +1. Neither the code expressing the logic nor the precision of the result is necessary. Part of the art of decision making is knowing which decisions need not be taken: letting arithmetic take the place of control flow sometimes offers such a route; having a contract that is no stricter than is necessary makes that path an easier one to follow. ®

This article originally appeared in Application Development Advisor.

References / bibliography

  1. Kevlin Henney, "Sorted", Application Development Advisor, July 2003
  2. Bertrand Meyer, Object-Oriented Software Construction, 2nd edition, Prentice Hall, 1997
  3. Kevlin Henney, No Memory for Contracts, Application Development Advisor, September 2004
  4. Kevlin Henney, "Objects of Value", Application Development Advisor, November 2003
  5. Kevlin Henney, Conventional and Reasonable, Application Development Advisor, May 2004
  6. Barbara Liskov, Data Abstraction and Hierarchy, OOPSLA '87 Addendum to the Proceedings, October 1987
  7. Kevlin Henney, The Taxation of Representation, artima.com, July 2003

Kevlin Henney is an independent software development consultant and trainer. He can be reached at http://www.curbralan.com

More about

TIP US OFF

Send us news


Other stories you might like