JavaAntiPatterns

Collection of bad coding practices

‘equals()’ and ‘hashCode()’ are context-sensitive

with 3 comments

equals() and hashCode() implementations should rely only on an internal object state. Making them dependent on other objects, context of use and other external conditions conflicts with the general contracts of consistency:

“For any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false” [*]

“Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer” [*]

Violating those contracts may cause all kinds of weird and unpredictable behavior.

A known example of this antipattern is equals() and hashCode() in java.net.URL implementation where they are depending on information returned by a domain name server, rather than on actual stored URL data.

See also:

About these ads

Written by Alex

November 24, 2007 at 6:20 am

Posted in Objects

Tagged with , ,

3 Responses

Subscribe to comments with RSS.

  1. […] It is incostistent […]

  2. Please give due credit to Joshua Baloch before copy/pasting.

    Zahid

    March 7, 2012 at 4:37 pm

    • Do you mean Bloch? So, could you point me to a sentence which has actually been copypasted from any of his work?

      Alex

      March 7, 2012 at 5:28 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: