TDD rule and Java contract conflict - java

Rule one of TDD is this:
Write production code only to pass a failing unit test
Effective Java Item 11(third edition), that is the same contract of java Object.hashCode():
Always override hashCode when you override equals
Now which is correct to do if we need to override only equals to pass a failed test and we need not to use object in a collection in the current failed test and it may be happened in future?

Always override hashCode when you override equals
Try this spelling: if you have to override equals, then your work is not done until you've also overridden hashCode.
So don't merge/share/publish the work until all of the required elements of the contract are complete.
But you can do the work in whatever order you like.

Related

Effective Java: should I override equals() and hashCode() if the objects I'm creating are never compared with each other?

If the objects I create are not used for comparisons such as list.contains(new Employee("MM")), and also if those objects will only be stored in Lists returned from a database such as List<Employee>employeeList = employeeService.getEmployeeList(); then do I need to override equals() and hashCode() in Employee class?
No, you do not need to override .equals() and .hashCode() if you don't need a custom definition of equality. As long as you intend to treat every instance of your class as un-equal to other instances the defaults will work fine. You can store such objects in Lists and even in hash-based collections such as HashMaps and HashSets - both classes have no problems with the default Object notion of equivalence.
Furthermore for many classes you shouldn't override these methods. Many common design patterns will include classes that aren't intended to ever be equivalent, such as factories, singletons, and state machines. Defining a custom notion of equality for such classes can introduce strange bugs, or at a minimum simply be unnecessary boilerplate.
On the other hand value types, or classes intended specifically to be a structured representation of some sort of data should almost always override .equals() and .hashCode() (and possibly implement Comparable as well), because it's what users of these sort of classes are likely to expect. The Auto/Value project makes creating such value types really painless; if that's the type of class you're constructing I'd strongly encourage you to use it.
If you know you will never be using the object as a key in a HashMap or will never be putting it in any sort of Set, or never doing anything with it where you will do any object comparison other than "are these references referring to literally same instance or not", then you do not have to override equals() and hashCode().
And if that's not the case and you do have to override them, then do consider letting your IDE generate the overrides rather than doing it manually -- especially for hashCode(). And be aware that when having the IDE generate these, you can tell the IDE which fields to include and which fields not to include, which even further reduces any need to write the overrides manually.
As QuantumMechanic had said above, you do not need to override equals() and hashcode().
However, if the Employee class is going to be shared with other people, it's a good idea to add equal and hashcode so that it is easier for other people to use.
Also, Eclipse can generate these functions by right clicking -> Source -> Generate hashCode() and equals()
Good luck!
Why overriding Equals Method:
If you object needs to be stored on Collection i.e List, you should override equals method since when you will use indexOf, lastIndexOf etc API method as those api methods internally uses equals method. If you dont override equal method, then you might get those object back from collections since identity checking is not the right way to get the object back from Collections.
Why overriding hashCode Method:
If your object needs to be stored in a set or as key object in a map collection, you must override HashCode and Equals both becuase both methods are used to get the object back from those collections.

Overriding broken equals

I have some third party code that has a lot of classes with broken equals() and hash-code implementations. I cannot change the third-party code but need the equals method badly. To overcome this I came up with the the following approaches:
1) Create an EqualsUtility which has a bunch of overloaded static equals() methods.
Problem: the class will become very large as the third-party code grows.
2) Create adapter classes for all the third party classes and write an equals method.
Problem: Too many new classes are created.
Is there a third, more clean way to do this.
You may try to check the object equality with some 3rd party lib, for example with the ApacheCommoms EqualsBuilder. But that could be not a very good solution, since it uses reflection for comparison. Furthermore, it doesn't help with hash code implementation.
IMO, extending base classes and overriding equals and hashcode methods are prefferable. Any other solution, including aspects, 3rd party libs for deep object comparison, some proxy objects, are not good for performance and in some cases for understanding of your code.
Check out AspectJ. It's an Aspect Oriented programming library for Java that let's you do exactly what you want to do. You describe an entity called a pointcut that corresponds roughly to in this case a method invocation of the equals() method on the library's objects.
You then write code that gets executed when that pointcut is hit. You can write different types of pointcuts. So for instance you can have your code execute before the equals() method, after the equals() method, or around the equals() method. If you write an around() type you can choose to handle the call your self or do some work then call the original method.
You could do an around() and rewrite the equals method so it is correct for your situation.
Very powerful stuff.

Extend JUnit assertEquals

I want to create a new assertEquals which takes in as input a custom pojo for expected and actual.
How would I go about extending assertEquals of the JUnit library?
What I could do is implement a compare method which returns a boolean and have this as the input to the assertEquals or even assertTrue but creating my own assertEquals seems more elegant.
Would it simply be the case of returning true if equal or raising a AssertionError?
As #Makoto commented, you could use a custom Hamcrest Matcher.
The disadvantage of the other common answer here (just change the definition of Object#equals for your class), is that you would have one and only one way of comparing your objects, and it would have to match exactly what is needed by the test rather than what would be needed by users of the class. The two needs may or may not be identical. Often in testing, I only need to assert one or two values, sometimes several, but usually not what gets tested by the "natural" #equals method of my class. Furthermore, I work with a lot of classes that don't even have an explicit override of #equals. In these cases you would have to define one that works simply for the case of your test, whereas it semantically might not represent the domain very well.
There is an overload of assertEquals that takes objects. It (eventually) calls the equals method on both objects. So, the "compare" method you need to write is an override of Object's equals method.
Once you have that written, then you can call assertEquals("Failure message", yourObject1, yourObject2). There is no need to extend JUnit for this case.
As an aside, if you override equals, then you should override hashCode also, in a consistent way.
Asserts are static methods, defined in Assert class. TestCase derives from that class, hence all asserts are available there too.
java.lang.Object
|
+--junit.framework.Assert
|
+--junit.framework.TestCase
Creating another derived class, such as class MyTestCase extends TestCase and define your customized asserts there the same way they are defined in Assert.
Use MyTestCase instead of TestCase
Profit!
Another approach is to define proper equals() method and use standard assertEquals(). You can use EqualsBuilder to get a reasonable implementation automagically using reflection.
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html
If you don't like Apache Commons, you can find similar tool in Guava.

Java hashCode() method override is not needed if we don't use hashmap or hashset

My co-worker was overriding the equals() method. My response was, have you also overridden the hashCode() method? His response was because we won't use hash map or hash set, it shouldn't really matter if we override hashCode(). Is that correct?
Yes he is factually right - however, if you need to put your objects in a hash-based collection one day, you will have to add hashcodes everywhere, which can be annoying + on that day you might implement your hashcode incorrectly (i.e. not consistent with equals) because you miss some subtlety in the equals method...
Considering that most IDEs provide an auto equals/hashcode generation feature, I see little reason not to create both.
Another way to look at it is: when you override a method from a parent class, you should follow the contract defined by that parent class. In the case of Object, the javadoc of equals is pretty clear:
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
So unless you have a real design reason not to override hashcode, the default decision should be to follow the parent class contract and override neither or both.
If you override equals(), do override hashCode() as well. Even if you don't use hashCode() now, you or somebody else might use it.
For more on this topic, check the excellent SO answer
It's a code smell. Findbugs for example will warn you if you override either hashCode or equals without overriding the other. You should override both so that they are consistent with one another (that is, a.equals(b) => a.hashCode() == b.hashCode()).
A little effort now may save a lot of headaches later.
You must override hashCode in every class that overrides equals. Failure to do so will result in a violation of the general contract for Object.hashCode, which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.
Effective Java Item 9: Always override hashCode when you override equals.
If your class is a public class then you can not control how your classes will be used in future development. Without looking into source code (or through reflection) there is no way to know whether this class has overriden the hasCode method or not and the user will be surprised by the result if they use it in any hash based collections.
Actually assume that you create two different objects without overriding equals and hashCode methods. And then if you call equals method java calls hashCode method implicitly then checks the equality of hashcodes.
Overriding hashCode method is enough for checking equality of two objects. And it will be useful for future. You can use this class on collections.
Otherwise if you implement just equal method, it will solve just equality of two objects not more.
General:
only override those methods which you want to use in your own way and also those methods which are affected by this overriding.
Specific to your Ques:
From java docs,
Note that it is generally necessary to override the hashCode method
whenever equals() method is overridden, so as to maintain the general
contract for the hashCode method, which states that equal objects must
have equal hash codes.
Equals

Java equals and hashCode methods - technical constraints

I've got question about java's equals(Object o) and hashCode() methods. What are the technical constraints of implementation this both methods? Is there something that I can't do during implement this methods?
None. It's just two methods in Object class. You could even change an object's state within this methods and this will freak out every developer and system but it's still valid from technical point of view.
You can technically anything inside them you can do in any other methods.
Instead what you concern yourself with are the practical and contractual obligations of the methods.
Good rules of thumb:
If you override one, override the other.
Variables used in one should be used in the other.
a given object must consistently report the same hash value
two objects which equals() says are equal must report the same hash value - so no timestamps in the hashcode :).
Two unequal objects can also have the same hashcode, though it is better to make the hashcode difficult to repoduce.
All you need to remember, is:
those constrains are very important
all are very well documented in javadoc for Object.hashCode() and Object.equals()
Make sure you understand it every time you override any of those methods.
Is there something that I can't do during implement this methods?
Well, as a rule of thumb (and as already #RHT mentioned above and #Antti Sykäri explains here) do your future self a favor and always use EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. Because, quite frankly, at least in my case I never get to remember all the nitty-gritty details that a correct implementation would require. ;-)

Categories

Resources