Explain Codes LogoExplain Codes Logo

Best practice to validate null and empty collection in Java

java
null-checks
collection-validation
best-practices
Anton ShumikhinbyAnton ShumikhinΒ·Sep 21, 2024
⚑TLDR

Bring into play Apache Commons Collections' CollectionUtils for a clear, effective check. The method isEmpty() handles null and emptiness simultaneously.

import org.apache.commons.collections4.CollectionUtils; // Pack your bags, we're going null hunting boolean isValid = CollectionUtils.isNotEmpty(collection);

Choose CollectionUtils.isNotEmpty for direct, expressive validation.

For Maps, we have MapUtils.isEmpty(...):

import org.apache.commons.collections4.MapUtils; // Map isn't empty? High five! πŸ™Œ boolean isMapValid = !MapUtils.isEmpty(map);

These utilities help trim down code bulk and potential snags, simplifying the validation process.

Pros/Cons: To library or not to library?

While external libraries like Apache Commons offer precise solutions, it's crucial to evaluate their need based on your project's complexity.

  • Petite Projects: If you're building a simple app, bringing in a library might be an overkill. Stick to Java's native methods:
// When you don't want external shoulders to lean on if (Objects.nonNull(collection) && !collection.isEmpty()) { // Your collection is in the 'Goldilocks' zoneβ€”not null, not empty }
  • Goliath Projects: For complex systems, Apache Commons can streamline checks across the codebase, enhancing maintainability.

Java's own toolkit: Handling null and empty checks

If you opt for Java's built-in abilities over external libraries, bring the Objects class onboard:

import java.util.Objects; import java.util.Collection; // Null check? Empty check? Yes, we multitask here public static boolean isValidCollection(Collection<?> collection) { return Objects.nonNull(collection) && !collection.isEmpty(); }

This method proves useful when you can't (or won't) add dependencies or want to keep the application light.

Using Spring magic for null and empty durations

If you're a Spring user, make use of Spring's own CollectionUtils.isEmpty():

import org.springframework.util.CollectionUtils; // Spring does have its charm, doesn't it? boolean isValid = !CollectionUtils.isEmpty(collection);

For a wider variety of object types, including arrays, Spring's ObjectUtils.isEmpty() can be your magic wand.

Crafting your own validation toolkit

Creating custom static methods can come handy for non-Spring usage or when you prefer not adding dependencies:

public final class ValidationUtils { private ValidationUtils() { throw new AssertionError("Hey! No instantiation for utility class, please."); } // So you want your own adorable little empty-check? public static boolean isNotEmpty(Collection<?> collection) { return collection != null && !collection.isEmpty(); } }

This encapsulates your null and emptiness checks, providing a neat, reusable solution.

Look out for the sneaky ones: Edge cases

While handling collections, watch out for edge cases like concurrent modifications, immutable collections, or null-by-design elements. These could break your methods if not tackled properly.

Visualization

Here's a metaphor to remember the process of validifying null & empty collections in Java.

Think of a `Collection` as a **Train Station** (πŸš‰). Validating is like checking if there's a train (data) present and ready to board.

Before validation:

πŸš‰? β†’ Is the station even there? (null check) πŸš‰ β†’ Is the train (data) present? (isEmpty check)

After validation:

πŸš‰πŸš‚ - All aboard! (Collection is present and not empty) πŸš«πŸš‰ - No trains here. Station either isn't present or is empty. (Validation fail)

This approach can help avoid boarding an empty train or a train that doesn't exist!

Additional quirks and tricks for effective validation

Here are some best practices and points to remember:

  • Apache Commons' CollectionUtils.isEmpty provides a unified, simple validation method.
  • Java's built-in functions serve as handy tools for smaller, simpler applications.
  • Custom static utility methods centralize validation, promoting consistency and readability.
  • Be aware of how your code handles edge cases and add suitable error handlers.
  • For Spring projects, employ CollectionUtils.isEmpty() and ObjectUtils.isEmpty().
  • To handle non-collections (like arrays or single instances), Spring's ObjectUtils.isEmpty() can be a lifesaver.