Posts Tagged ‘Jakarta Commons’
On Commons Lang
One of my favorite open source libraries is the Jakarta commons. I find myself using some methods and classes all the time. The top few, based on how often they appear in my code, are:
-
StringUtils (org.apache.commons.lang)StringUtils.isNotEmpty(str): Sure beats having to do the following:if(str!= null && str.length() >0) { ---- }This can be expressed simply as:
if(StringUtils.isNotEmpty(str)){ ---- }StringUtils.isEmpty(str),StringUtils.isBlank(str),StringUtils.isNotBlank (str)have similar semantics, with intuitive handling of “null” variables.
Check out the API docs for more time-savers. -
ToStringBuilder (org.apache.commons.lang.builder)Like most others, I find it invaluable to have a well defined toString method in every class I write. This is especially true of stateful classes(domain objects, DTOs etc).
It is painful to write code like:public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("Last Name=").append(lastName); buffer.append("First Name=").append(firstName); }The quick and easy:
return ToStringBuilder.reflectionToString(this);
If you want to customize which fields are included/excluded, it’s still simpler than using StringBuffer:
return new ToStringBuilder(this). append("firstName",this.firstName). append("lastName",this.lastName).toString();Note: There are many options available like changing the default output format, including the superclass etc. Check out the API for more details.
-
EqualsBuilder and HashCodeBuilder (org.apache.commons.lang.builder)Again, a really simple way to write good
equalsandhashCodemethods:public boolean equals(Object other) { return EqualsBuilder.reflectionEquals(this, other); } public int hashCode() { return HashCodeBuilder.reflectionHashCode(17,37,this); }See Also:
CompareToBuilder -
Validate (org.apache.commons.lang)A good practice is to always ensure that arguments to a method call are correct. For example,
public void doSomething(Long aLong, Collection aCollection){ if(aLong == null) { throw new IllegalArgumentException("aLong is null"); } if(aCollection == null || aCollection.isEmpty()) { throw new IllegalArgumentException( "aCollection is null or empty"); } --- }This can be expressed more concisely:
public void doSomething(Long aLong, Collection aCollection){ Validate.notNull(aLong, "aLong is null"); Validate.notEmpty(aCollection, "aCollection is null or empty"); ----- }
The above mentioned are but a few of the useful and elegant methods on the commons lang API. The web site is http://jakarta.apache.org/commons/lang/