Saturday, June 28, 2008

Clean Getters in Java/Struts framework

This blog is about writing clean getter methods in form objects that use Struts framework. In an enterprise application, there are typically web and business object layers seperated and form values submitted by user from view has to be converter into value objects which BO/Service layer can use. A converter utility class is used to perform this action.
For example if an user types first name and last name,phone in his form for creating a profile for him
the following code is written
public class ProfileForm
{
private String firstName;
private string phone;
public setFirstName(String firstName)
{
this.firstName=firstName;
}
public String getFirstName()
{
return firstName;
}
public void setPhone(String phone
{
this.phone=phone;
}
public String getPhone()
{
return phone;
}
}

In the converter class following code has to be written

if(profileForm.getPhone()!=null && !"".equals(profileForm.getPhone().trim()))
{
profileVO.setPhone(profileForm.getPhone());
}
else
{
profileVO.setPhone(null);
}

If there are more number of optional fields then this repeated null, space check and trimming has to be done in an utility method. So instead of doing this if getter method itself does this, then caller need not check all this
public class ProfileForm
{
private String firstName;
private string phone;
public setFirstName(String firstName)
{
this.firstName=firstName;
}
public String getFirstName()
{
return valueOf(firstName);
}
public void setPhone(String phone
{
this.phone=phone;
}
public String getPhone()
{
return valueOf(phone);
}

private String valueOf(String data)
{
if(data = null || "".equals(data.trim()))
{
return null;
}
return data.trim();
}

}
Now the caller has to just write
profileVO.setPhone(profileForm.getPhone());
This way it reduces un-necessary if logic by encapsulation. Sinc it makes getting data from forms/VO easier, it is called as Clean Getter design pattern

1 comment:

Balaji Seshadri said...

Even setter method can do what getters can do. It will be once done when value is set in transfer object.