First among equals

The contract metaphor is an effective way of approaching API design

Security for virtualized datacentres

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:

a.equals(b) if and only if b.equals(a)
a.equals(b) && b.equals(c) implies a.equals(c)
a.equals(b) returns the same as long as a and b are unmodified
null inequality:
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.

Intelligent flash storage arrays

More from The Register

next story
PEAK APPLE: iOS 8 is least popular Cupertino mobile OS in all of HUMAN HISTORY
'Nerd release' finally staggers past 50 per cent adoption
Microsoft to bake Skype into IE, without plugins
Redmond thinks the Object Real-Time Communications API for WebRTC is ready to roll
Microsoft promises Windows 10 will mean two-factor auth for all
Sneak peek at security features Redmond's baking into new OS
Mozilla: Spidermonkey ATE Apple's JavaScriptCore, THRASHED Google V8
Moz man claims the win on rivals' own benchmarks
FTDI yanks chip-bricking driver from Windows Update, vows to fight on
Next driver to battle fake chips with 'non-invasive' methods
DEATH by PowerPoint: Microsoft warns of 0-day attack hidden in slides
Might put out patch in update, might chuck it out sooner
Ubuntu 14.10 tries pulling a Steve Ballmer on cloudy offerings
Oi, Windows, centOS and openSUSE – behave, we're all friends here
Was ist das? Eine neue Suse Linux Enterprise? Ausgezeichnet!
Version 12 first major-number Suse release since 2009
prev story


Why cloud backup?
Combining the latest advancements in disk-based backup with secure, integrated, cloud technologies offer organizations fast and assured recovery of their critical enterprise data.
Forging a new future with identity relationship management
Learn about ForgeRock's next generation IRM platform and how it is designed to empower CEOS's and enterprises to engage with consumers.
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?
New hybrid storage solutions
Tackling data challenges through emerging hybrid storage solutions that enable optimum database performance whilst managing costs and increasingly large data stores.
Getting ahead of the compliance curve
Learn about new services that make it easy to discover and manage certificates across the enterprise and how to get ahead of the compliance curve.