XNSIO
  About   Slides   Home  

 
Managed Chaos
Naresh Jain's Random Thoughts on Software Development and Adventure Sports
     
`
 
RSS Feed
Recent Thoughts
Tags
Recent Comments

toString(), equals() and hashCode(): To Override or Not to?

During a pairing session with Michael Feathers, he told me why he does not like to override toString(), equals() and hashCode() methods in Java.
If you look around, different people use toString() method to return random pieces of text. The guidelines says that the toString() method should
Returns a string representation of the object. In general, the 

1
toString

 method returns a string that “textually represents” this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

What does string representation of the object really mean? Does it mean all the values of all the instance variables? Does it mean just a selected values? Usually developers decide on some selected value which uniquely identifies the object. But there is no clear guideline. 
Similarly when we talk about the equals() method, different developers look at object equality differently. Depending on the state of the object and the context, one might have to think about equality differently. So instead of overriding equals() method, Michael prefers to create methods like matchesId() or matchesName() which are very explicit in terms of what they are matching to. 
So the next time you override one of these methods think about them.

    Licensed under
Creative Commons License