Content-Length: 332940 | pFad | http://hackernoon.com/refactoring-029-how-to-replace-null-with-collection

Refactoring 029 - How to Replace NULL With Collection | HackerNoon

Refactoring 029 - How to Replace NULL With Collection

by Maximiliano ContieriJune 2nd, 2025
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

Replace nullable optional attributes with empty collections to eliminate null checks and leverage polymorphism.

People Mentioned

Mention Thumbnail
featured image - Refactoring 029 - How to Replace NULL With Collection
Maximiliano Contieri HackerNoon profile picture

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 😔

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;
    }
}
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();
    }
}

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();
  }
}

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 the 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 the 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 a 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

Without Proper Instructions

With Specific Instructions

ChatGPT

ChatGPT

Claude

Claude

Perplexity

Perplexity

Copilot

Copilot

Gemini

Gemini

DeepSeek

DeepSeek

Meta AI

Meta AI

Grok

Grok

Qwen

Qwen

Tags 🏷️

  • Null

Level 🔋

  • [x]Intermediate

See also 📚

Credits 🙏

Image by Eak K. on Pixabay


This article is part of the Refactoring Series.


Trending Topics

blockchaincryptocurrencyhackernoon-top-storyprogrammingsoftware-developmenttechnologystartuphackernoon-booksBitcoinbooks








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://hackernoon.com/refactoring-029-how-to-replace-null-with-collection

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy