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

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

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 .....

}

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}