Java Best Practices : Part I

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:-

@Override
public String toString() {
return ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE);
}
view raw Apache toString hosted with ❤ by GitHub

Apache library gives you more control, like excluding certain attributes like password, can use

@Override
public String toString() {
final ReflectionToStringBuilder reflectionToStringBuilder = new ReflectionToStringBuilder(this);
reflectionToStringBuilder.setAppendStatics(true);
reflectionToStringBuilder.setAppendTransients(true);
reflectionToStringBuilder.setExcludeFieldNames(
new String[] {"contentStreamLength", "password"});
return reflectionToStringBuilder.toString();
}

 

2. Have you manipulated Strings, like comparing String for not null and not empty?

 

if (str == null || "".equals(str)){
//..
//..
}
view raw String Checking hosted with ❤ by GitHub

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:-
org.apache.commons.lang.StringUtils

Some usage examples:-

 

// Usage 1
if (StringUtils.isEmpty(firstName)) {
//…
}
// Usage 2
if (StringUtils.equalsIgnoreCase(field1, someObject.getField1())
&& StringUtils.equalsIgnoreCase(field2, someObject.getField2())
&& StringUtils.equalsIgnoreCase(field3, someObject.getField3())){
//…
}
// Usage 3
String emptyString = StringUtils.EMPTY;
// Usage 4
StringUtils.substringAfter(url, "/some/random/url/");

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….

 

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class Emp {
private String name;
private int sal;
private List<Emp> subordinates;
@Override
public int hashCode(){
return new HashCodeBuilder()
.append(name)
.append(sal)
.append(subordinates)
.toHashCode();
}
@Override
public boolean equals(final Object obj){
if(obj instanceof Emp){
final Emp other = (Emp) obj;
return new EqualsBuilder().append(name, other.name)
.append(sal, other.sal)
.append(subordinates, other. subordinates)
.isEquals();
} else{
return false;
}
}
}

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… 🙂

http://code.google.com/p/cloning/wiki/Usage

Tagged with: , , , ,
Posted in Best Practices
9 comments on “Java Best Practices : Part I
  1. Javin says:

    I agree with point that these are core method to understand and for Domain object it should be overridden but not with every class i.e. some classes are just utility classes e.g. java.lang.Math. I have also shared my tips on overriding equals and hascode and overriding toString in Java. let me know how do you find it.

  2. Javin says:

    I agree with point that these are core method to understand and for Domain object it should be overridden but not with every class i.e. some classes are just utility classes e.g. java.lang.Math. I have also shared my tips on overriding equals and hascode. let me know how do you find it.

    • ekramalikazi says:

      Thanks Javin for the response. I do agree with your comment. Your tips are very helpful.

      The purpose of this article is to promote usage of already written strong libraries.
      I have re-framed some of the stuff above to make more sense.. Sorry for the confusion.

      Hope this helps.

      Thanks,
      Ekram Ali

  3. lkubaski says:

    You should use the wordpress tag anytime you want to post source code (this way you’ll get indenting and syntax highlighting for free). Also, it would be great to see the actual output of ReflectionToStringBuilder.toString()

  4. lkubaski says:

    And speaking of Apache Commons, shameless plug for my latest project: http://code.google.com/p/apache-commons-javadoc-chm/

  5. […] Java Best Practices to use apache common library. To promote code reuse which means less unit testing, less bugs….  […]

  6. whitenoise says:

    Reblogged this on fucking the white bunny rabbit and commented:
    Three interesting best practice on basic java development. To be archived for future use.

  7. i was looking for such easy task from a long time it will help me in increasing my knowledge. thanks a lot.

Leave a reply to Java Best Practices - Part I - toString(), equals(), hashcode(), clone() | DevOps in the Enterprise | Scoop.it Cancel reply