Refactoring 029 - Replace NULL With Collection
Maxi Contieri

Maxi Contieri @mcsee

About: Learn something new every day. - I am a senior software engineer working in industry, teaching and writing on software design, SOLID principles, DDD and TDD.

Location:
Buenos Aires
Joined:
Apr 13, 2020

Refactoring 029 - Replace NULL With Collection

Publish Date: Jun 2
7 2

Transform optional attributes into empty collections for cleaner, safer, and polymorphic code, banishing the billion-dollar mistake

TL;DR: Replace nullable optional attributes with empty collections to eliminate null checks and leverage polymorphism.

Problems Addressed 😔

Related Code Smells 💨

Steps 👣

  1. Identify nullable optional attributes that could be collections
  2. Replace single nullable objects with empty collections
  3. Remove all null checks related to these optional attributes
  4. Update methods to work with collections instead of single objects

Sample Code 💻

Before 🚨

public class ShoppingCart {
    private List<Item> items = new ArrayList<>();
    private Coupon coupon = null;

    public void addItem(Item item) {
        this.items.add(item);
    }

    public void redeemCoupon(Coupon coupon) {
        this.coupon = coupon;
    }

    public double total() {
        double total = 0;

        for (Item item : this.items) {
            total += item.getPrice();
        }

        // This a polluted IF and null check
        if (this.coupon != null) {
            total -= this.coupon.getDiscount();
        }

        return total;
    }

    public boolean hasUnsavedChanges() {
        // Explicit null check
        return !this.items.isEmpty() || this.coupon != null;
    }

    public boolean hasCoupon() {        
        return this.coupon != null;
    }
}
Enter fullscreen mode Exit fullscreen mode
public class ShoppingCart {
    private final List<Item> items = new ArrayList<>();

    // This version uses Optionals
    // Not all programming languages support this feature
    private Optional<Coupon> coupon = Optional.empty();

    public void addItem(Item item) {
        items.add(item);
    }

    public void redeemCoupon(Coupon coupon) {
        // You need to understand how optionals work
        this.coupon = Optional.ofNullable(coupon);
    }

    public boolean hasUnsavedChanges() {
        return !items.isEmpty() || coupon.isPresent();
    }

    public boolean hasCoupon() {
        return coupon.isPresent();
    }
}
Enter fullscreen mode Exit fullscreen mode

After 👉

public class ShoppingCart {
  private List<Item> items = new ArrayList<>();

  // 1. Identify nullable optional attributes
  // that could be collections
  // 2. Replace single nullable objects with empty collections
  private List<Coupon> coupons = new ArrayList<>();

  public void addItem(Item item) {
      this.items.add(item);
  }

  // Step 4: Work with collection
  // instead of single nullable object
  public void redeemCoupon(Coupon coupon) {
      this.coupons.add(coupon);
  }

  // Step 4: Simplified logic without null checks
  public double total() {
    double total = 0;

    for (Item item : this.items) {
        total += item.getPrice();
    }

    // 3. Remove all null checks 
    // related to these optional attributes        
    for (Coupon coupon : this.coupons) {
        total -= coupon.getDiscount();
    }

    return total;
  }

  // Consistent behavior with empty collections
  public boolean hasUnsavedChanges() {
    // 4. Update methods to work with collections
    // instead of single objects 
    return !this.items.isEmpty() || !this.coupons.isEmpty();
  }

  // 3. Remove all null checks 
  // related to these optional attributes
  // Collection-based check instead of null check
  public boolean hasCoupon() {
    return !this.coupons.isEmpty();
  }
}
Enter fullscreen mode Exit fullscreen mode

Type 📝

[X] Semi-Automatic

Safety 🛡️

This refactoring is generally safe when you control all access points to the collection attributes.

You need to ensure that no external code expects null values and deal with inside APIs.

The refactoring maintains the same external behavior while simplifying internal logic.

You should verify that all constructors and factory methods initialize collections properly.

Why is the Code Better? ✨

The refactored code eliminates null pointer exceptions and reduces conditional complexity.

Empty collections and non-empty collections behave polymorphically, allowing you to treat them uniformly.

The code becomes more predictable since collections always exist (at least empty) and respond to the same operations.

Method implementations become shorter and more focused on business logic rather than null handling.

The approach aligns with the principle of making illegal states unrepresentable in your domain model, leading to more robust and maintainable code.

Empty collections and non-empty collections are polymorphic.

How Does it Improve the Bijection? 🗺️

In the real world, containers exist even when empty.

By representing optional collections as empty collections rather than null, you create a more accurate model of reality.

Null does not exist in real world and it always breaks the bijection.

This maintains the one-to-one correspondence between real-world concepts and your computational model, creating a good MAPPER.

When you return a collection instead of nulls, you also reduce the coupling.

Limitations ⚠️

This refactoring may not be suitable when null has semantic meaning different from "empty". Some legacy APIs might expect null values, requiring adaptation layers.

You need to ensure all code paths initialize collections consistently to avoid mixed null and empty states.

Refactor with AI 🤖

Suggested Prompt: 1. Identify nullable optional attributes that could be collections 2. Replace single nullable objects with empty collections 3. Remove all null checks related to these optional attributes 4. Update methods to work with collections instead of single objects 5. Test that empty and non-empty collections behave consistently

Tags 🏷️

  • Null

Level 🔋

[X] Intermediate

Related Refactorings 🔄

See also 📚

Credits 🙏

Image by Eak K. on Pixabay


This article is part of the Refactoring Series.

Comments 2 total

  • Ava Nichols
    Ava NicholsJun 4, 2025

    I love how clear and organized your writing is! The logical step-by-step breakdown and concise explanations make the refactoring process easy to follow. Great use of formatting and code examples too!

  • Dotallio
    DotallioJun 5, 2025

    Love this - switching to empty collections has saved me so much time on defensive code and bugs. Have you ever run into any weird edge cases where null actually made more sense than empty?

Add comment