Feeds

First among equals

The contract metaphor is an effective way of approaching API design

Security and trust: The backbone of doing business over the internet

Kevlin HenneyColumn Whether formal or informal, a contract defines an (in principle) enforceable agreement between two or more parties with respect to a specific undertaking. The same is also true in code. The contract metaphor is an effective way of approaching API design and use [1]: "A contract is effectively an agreement on the requirements fulfilled by a component between the user of the component and its supplier".

One way of capturing a functional contract is through the use of pre- and postconditions that state what must be true before an operation is to be called, for it to be called correctly, and what must be true after an operation has returned, for it to be considered correct [2]. To consider contracts only with respect to pre- and postconditions, however, offers a slightly limiting and incomplete — albeit common — view of the contract metaphor, although it clearly offers a great deal of coverage, utility and insight [3].

Comparing two objects for some kind of equality offers fertile ground for exploring different conventions and contracts [4, 5].

Beyond pre- and postconditions

The contract for the equals method in Java can be phrased most easily and clearly in terms of named constraints, each one stated as a simple truth:

reflexive:
a.equals(a)
symmetric:
a.equals(b) if and only if b.equals(a)
transitive:
a.equals(b) && b.equals(c) implies a.equals(c)
consistent:
a.equals(b) returns the same as long as a and b are unmodified
null inequality:
!a.equals(null)
hashCode equality:
a.equals(b) implies a.hashCode() == b.hashCode()

This contract is binding on any override of the Object.equals method. If you try to state this in terms of preconditions — what must be true before a successful call to equals — and postconditions — what must be true after a successful call to equals — from a strictly object-centric viewpoint you will find a loss of clarity as well as a loss of part of the contract. Assuming that the argument to equals is named other:

postcondition where other == null:
The result is false
postcondition where other == other:
The result is true
postcondition otherwise:
The result is the same as the result of other.equals(this), and where true then hashCode() == other.hashCode().

As you can see, there is no useful precondition and the postcondition is in part partitioned by the named constraints we had before, but not as clearly. More reading between the lines is needed to get the full sense of the contract. The consistency constraint is a difficult one to express at the best of times, but its temporal nature means that it cannot be properly expressed as the postcondition of an operation, which describes only what is true at the point of completion of the method call, and nothing beyond.

There is also a subtle loop here: if the result of calling equals is required to be the same as the result of making the same call but with the argument and receiving object switched round, what is the requirement on that second call? It would be the first call. Any literal implementation of this would find itself caught in infinite recursion.

Although the contract for overriding Object.equals in Java cannot be as well stated in terms of pre- and postconditions, the truths it uses are assertible from a testing perspective. For a given a, b and c that are supposed to compare equal we can assert the following, using the Java 1.4 assertion mechanism:

assert a.equals(a)                  : "reflexive";
assert !a.equals(null)              : "null inequality";
assert a.hashCode() == b.hashCode() : "hashCode equality";
assert a.equals(b) && b.equals(a)   : "symmetric";
assert b.equals(c) && a.equals(c)   : "transitive";
assert a.equals(b)                  : "consistent";

Of course, the consistency constraint check cannot be a thorough one, but it simply reinforces that in the simple test suite shown yet another equality comparison between a and b will yield true.

It is worth noting that contrary to the way that it is often presented — including in Sun's own documentation — the relationship between equals and hashCode is more properly a part of the equality contract, which deals with relations between objects, than it is of the hashing contract, which deals with individual objects.

Providing a secure and efficient Helpdesk

More from The Register

next story
New 'Cosmos' browser surfs the net by TXT alone
No data plan? No WiFi? No worries ... except sluggish download speed
'Windows 9' LEAK: Microsoft's playing catchup with Linux
Multiple desktops and live tiles in restored Start button star in new vids
iOS 8 release: WebGL now runs everywhere. Hurrah for 3D graphics!
HTML 5's pretty neat ... when your browser supports it
'People have forgotten just how late the first iPhone arrived ...'
Plus: 'Google's IDEALISM is an injudicious justification for inappropriate biz practices'
Mathematica hits the Web
Wolfram embraces the cloud, promies private cloud cut of its number-cruncher
Mozilla shutters Labs, tells nobody it's been dead for five months
Staffer's blog reveals all as projects languish on GitHub
SUSE Linux owner Attachmate gobbled by Micro Focus for $2.3bn
Merger will lead to mainframe and COBOL powerhouse
iOS 8 Healthkit gets a bug SO Apple KILLS it. That's real healthcare!
Not fit for purpose on day of launch, says Cupertino
prev story

Whitepapers

Secure remote control for conventional and virtual desktops
Balancing user privacy and privileged access, in accordance with compliance frameworks and legislation. Evaluating any potential remote control choice.
WIN a very cool portable ZX Spectrum
Win a one-off portable Spectrum built by legendary hardware hacker Ben Heck
Storage capacity and performance optimization at Mizuno USA
Mizuno USA turn to Tegile storage technology to solve both their SAN and backup issues.
High Performance for All
While HPC is not new, it has traditionally been seen as a specialist area – is it now geared up to meet more mainstream requirements?
The next step in data security
With recent increased privacy concerns and computers becoming more powerful, the chance of hackers being able to crack smaller-sized RSA keys increases.