Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Better code

DZone's Guide to

A Better code

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

Problem

While we are implementing a method, we need to assert about various conditions and path flows of code. For instance, we would like to ensure the given parameters are all valid in our preconditions then the operation will be executed.

Impacts

Handling this scenario by classic if-else statements will cause:

Options

There are few options that have been considered which are:

  • Assert from spring core. This one is rejected because in its javadoc has been mentioned it is a class for internal framework usage.
  • Preconditions from google guava. This one is rejected because of immaturity compare to Apache Common's Lang.
  • Validate from commons-lang. This is the to go way.

Solution

Imagine there is a code like below:

This is a code BEFORE using assertion concept

public static void createUser(final String username, final String password) {
       if(username == null) throw new IllegalArgumentException();
       if(username == "") throw new IllegalArgumentException();
       if(password == null) throw new IllegalArgumentException();
       if(password == "") throw new IllegalArgumentException();

            //and etc .....

}

And after:

This is a code AFTER using assertion concept

public static void createUser(final String username, final String password) {
      Validate.notEmpty(username); 
      Validate.notEmpty(password);
      //and etc .....

}

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}