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);
 }

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)){

 //..
 //..
 }

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

if (StringUtils.isEmpty(toPhone)) {
//…
}

 

if (StringUtils.equalsIgnoreCase(userAnswer1, userObj.getSecurityAnswer1())
&& StringUtils.equalsIgnoreCase(userAnswer2, userObj.getSecurityAnswer2())
&& StringUtils.equalsIgnoreCase(userAnswer3, userObj.getSecurityAnswer3())){
//…
}

 


String emptyString = StringUtils.EMPTY;

StringUtils.substringAfter(url, "/account/user/reset/");

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

9 thoughts on “Java Best Practices : Part I

    • 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

  1. 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()

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