Home Java javaTutorial Simplify Null Checks in Java: Writing Clean Code with Apache Commons Lang 3

Simplify Null Checks in Java: Writing Clean Code with Apache Commons Lang 3

Oct 19, 2024 am 06:07 AM

Simplify Null Checks in Java: Writing Clean Code with Apache Commons Lang 3
In Java, null checks are generally done using == or !=. In addition, if we want to do an empty check, our condition will look like the following.

if (myString != null || myString != ""){
  // Not null or empty
}

if(myList != null || myList.size() != 0){
  // Not null or empty
}

if (myObject != null) {
  // Not Null
}
Copy after login

Such controls make your code repetitive and difficult to manage as it grows.

This is where the Apache Commons Lang 3 library comes in. We will examine 3 classes to make null or empty checks in objects and lists more reliable and more readable. First, let’s see how to add this library to our project.

How to Add Apache Commons Lang3 to Your Project

If you are using Maven, you can add the following dependency to your pom.xml file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version> <!-- Check the version -->
</dependency>
Copy after login

If you are using Gradle, you can add the following dependency to your build.gradle file:

implementation 'org.apache.commons:commons-lang3:3.17.0'  // Check the version

Copy after login

ObjectUtils for General Null Checks

ObjectUtils has several useful methods that you can use to check objects and assign default values. Two of them are the isEmpty and isNotEmpty methods. These methods check whether the object is null or empty.

if (ObjectUtils.isEmpty(myObject)) {
  // Null or empty
}

if (ObjectUtils.isNotEmpty(myObject)) {
  // Not null or empty
}
Copy after login

You can also use Java Util.

if (Objects.isNull(myObject)) {
  // Null or empty
}

if (Objects.nonNull(myObject)) {
  // Not null or empty
}
Copy after login

If you want to assign a default value to an object in case it is null, you can use the defaultIfNull method of the ObjectUtils class.

Integer age = ObjectUtils.defaultIfNull(inputAge, 18);

Copy after login

Checking Strings for Null or Empty with StringUtils

Especially when working with String values, we need to do a lot of null or empty checking. In this case, we can easily do this with the StringUtils class.

if (StringUtils.isBlank(myString)) {
  // String is null, empty or contains only spaces
}

if (StringUtils.isNotBlank(myString)) {
  // String contains a valid value
}
Copy after login

If you only want to check for null or empty;

if (StringUtils.isEmpty(myString)) {
  // String null or empty
}

if (StringUtils.isNotEmpty(myString)) {
  // String contains a valid value (Can contain only spaces)
}
Copy after login

If the string is null or empty and you want to assign a default value to it;

String name = StringUtils.defaultIfBlank(inputName, "John Doe");

Copy after login

This allows us to assign a safe default value if the Strings are null, empty or space.

Collection Checks with CollectionUtils

When working with collections, it is essential to check for lists that are empty. With the CollectionUtils class you can make such checks quite simple.

To check if a collection is empty;

if (CollectionUtils.isEmpty(myList)) {
    // List is empty
}

if (CollectionUtils.isNotEmpty(myList)) {
    // List is valid
}
Copy after login

In this way, we can do both checks at once and make the code cleaner.

With Apache Commons Lang 3, you can make your code cleaner, reliable and maintainable by performing null checks in Java more easily. With this library, which is very easy to include in the project, you can reduce code complexity in your Java projects and create a better quality software development process by minimizing errors.

...

Thank you for reading my article! If you have any questions, feedback or thoughts you would like to share, I would love to hear them in the comments.

Thank you! ?‍??

To follow me on LinkedIn: https://www.linkedin.com/in/tamerardal/
Medium: Simplify Null Checks in Java: Writing Clean Code with Apache Commons Lang 3

Resources:

  1. Educative IO, What is ObjectsNonNull in Java
  2. Apache Commons, StringUtils
  3. Apache Commons, Dependency Info
  4. Baeldung, Java Commons Lang 3

The above is the detailed content of Simplify Null Checks in Java: Writing Clean Code with Apache Commons Lang 3. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles