Many a times we override default behavior of Object class. we need to take utmost care while overriding those methods by ourselves about their contracts. Moreover, we need to write unit tests for our implementation. Consider using Apache and other libraries. They are here to rescue us and save our development time….
1. Do you wish to override toString() method? Don’t do it yourself….
toString() method returns a string representation of the object. In general, the 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.
Instead of writing one on your own, try using apache commons class as:-
Apache library gives you more control, like excluding certain attributes like password, can use
2. Have you manipulated Strings, like comparing String for not null and not empty?
Imagine you want to compare 2 strings with equals, checking both should not be null, and its undoubtedly big statement.
We have StringUtils from apache to help us with all such string manipulations:-
Some usage examples:-
These are only few benefits of using StringUtils. Explore more on this, when you need to manipulate Strings.
3. Do you wish to override equals and hashcode methods? Don’t do it yourself….
4. Do you wish to override clone method for your POJO? Don’t do it yourself….
Writing correct clone method is a challenging task and that performing all sort of unit testing is much time consuming. Also if we modify our POJO, the clone method needs to modified and tested accordingly. The most important thing is about deep cloning.
Cloning can be potentially dangerous. Cloning files, streams can make the JVM crash. Also cloning proxies (i.e. objects returned by ORM libraries) means a big graph of objects might be cloned which can lead to performance issues and potential crashes.
Here, is a quick solution for cloning and no need to implement and override any method. No coding means no testing… 🙂