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
- log4j logging made easier with Eclipse template
- JUnit testing made easier with Eclipse templates
- Get warnings about unused method arguments from Eclipse to keep code clean
- How to tweak Eclipse templates to suit you
- Extract constants from strings and numbers with Eclipse refactorings