Generate validation code for required variables using templates

You may find yourself having to write the following code once too often, especially at the start of a method to validate arguments:

if (account == null) {
    throw new IllegalArgumentException("Account is required");
}

//Or for strings
if (name == null || name.length() == 0) {   //Or even StringUtils.isBlank() of Apache Commons
    throw new IllegalArgumentException("Name is required");
}

Well, here  are templates that makes it easy to validate an object or string and throw an IllegalArgumentException if it isn’t.

Import the templates (recommended)

Download the relevant template below then import it into Eclipse.

  • errifnull – Checks if an object is null and throws IllegalArgumentException if it is.
  • errifblank – Checks if a String is null or of length zero and throws IllegalArgumentException if it is. Add trim if you want to take it further.
  • errifblank (StringUtils) – Same as above, but uses Apache Commons StringUtils.isBlank() and automatically adds a static import.

Create the templates manually

Alternatively, create the templates with the following settings.

Name errifnull
Context Java statements
Pattern
if (${var} == null) {
    throw new IllegalArgumentException("${message}");
}
Name errifblank
Context Java statements
Pattern
if (${string:var(java.lang.String)} == null || ${string}.length() == 0) {
	throw new IllegalArgumentException("${message}");
}
Name errifblank (StringUtils)
Context Java statements
Pattern
if (isBlank(${string:var(java.lang.String)})) {
	throw new IllegalArgumentException("${message}");
}${:importStatic('org.apache.commons.lang.StringUtils.*')}

Related Tips

Support Eclipse On E

Comments are closed.