By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
World of SoftwareWorld of SoftwareWorld of Software
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Search
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright © All Rights Reserved. World of Software.
Reading: Code Smell 304: Null Pointer Exception – How to Avoid NULL References That Cause Runtime Crashes | HackerNoon
Share
Sign In
Notification Show More
Font ResizerAa
World of SoftwareWorld of Software
Font ResizerAa
  • Software
  • Mobile
  • Computing
  • Gadget
  • Gaming
  • Videos
Search
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Have an existing account? Sign In
Follow US
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright © All Rights Reserved. World of Software.
World of Software > Computing > Code Smell 304: Null Pointer Exception – How to Avoid NULL References That Cause Runtime Crashes | HackerNoon
Computing

Code Smell 304: Null Pointer Exception – How to Avoid NULL References That Cause Runtime Crashes | HackerNoon

News Room
Last updated: 2025/06/20 at 3:43 PM
News Room Published 20 June 2025
Share
SHARE

I keep writing about NULL problems, yet every day the news reminds me: NULL is still alive and kicking.

TL;DR: Avoid NULL references that cause runtime crashes by using proper validation and null-safe patterns

Problems 😔

In Google Cloud case:

  • Poor error handling: The code crashed instead of gracefully handling null data
  • No feature flags: New code wasn’t gradually rolled out with safety controls
  • Instant global replication: Bad data spreads worldwide immediately like in Crowdstrike Incident
  • No randomized backoff: Recovery caused infrastructure overload
  • Inadequate testing: The failure scenario was never tested during deployment

Solutions 😃

  1. Avoid nulls
  2. Use null checks if nulls are beyond your control (for example, an external API)
  3. Initialize default values
  4. Implement guard clauses
  5. Use null objects
  6. Don’t use optionals

Refactorings ⚙️

https://hackernoon.com/code-refactoring-tips-no-015-remove-null

Context 💬

On June 12th, 2025, a major outage happened on Google Cloud Platform.

It affected dozens of Google Cloud and Google Workspace services globally from approximately 10:49 AM to 1:49 PM PDT (3 hours total), with some services taking longer to recover fully.

The outage was caused by a cascading failure in Google’s API management system:

On May 29, 2025, Google deployed new code to “Service Control” (their API management system) that added additional quota policy checks.

This code had a critical flaw. It lacked proper error handling and wasn’t protected by feature flags.

On June 12, a policy change containing blank/NULL fields was pushed to the global database that Service Control uses. When Service Control attempted to process these blank fields, it encountered a null pointer in the unprotected code path, resulting in the binaries crashing in an infinite loop.

Since quota management is global, this corrupted data was replicated worldwide within seconds, causing Service Control to crash in every region.

Null pointer exceptions happen when you try to access methods or properties on objects that don’t exist.

This happens when variables contain null references instead of valid object instances.

The problem becomes particularly dangerous in production environments where these exceptions can crash your application and frustrate users.

Languages like Java, C#, and JavaScript are especially prone to this issue, though modern language features and patterns can help you avoid these crashes entirely.

Nulls have been a significant problem in the software industry for decades, yet software engineers continue to ignore them despite the warnings of their creator.

Sample Code 📖

Wrong ❌

public class ServiceControlPolicy {
  private SpannerDatabase spannerDB;
  private QuotaManager quotaManager;
    
  public void applyPolicyChange(PolicyChange change) {
      // NULL POINTER: change can be null
      Policy policy = spannerDB.getPolicy(change.getPolicyId());
      // NULL POINTER: policy can be null from the database
      String quotaField = policy.getQuotaField();
      // NULL POINTER: quotaField can be null (blank field)
      quotaManager.updateQuota(quotaField, change.getValue());
  }
    
  public void exerciseQuotaChecks(String region) {
      // NULL POINTER: policies list can be null
      List<Policy> policies = spannerDB.getPoliciesForRegion(region);
      for (Policy policy : policies) {
          // NULL POINTER: individual policy can be null
          String quotaValue = policy.getQuotaField();
          // NULL POINTER: quotaValue can be null before trim()
          quotaManager.checkQuota(quotaValue.trim());
      }
  }
    
  public boolean validatePolicyData(Policy policy) {
      // NULL POINTER: policy parameter can be null
      String quotaField = policy.getQuotaField();
      // NULL POINTER: quotaField can be null before length()
      return quotaField.length() > 0 && 
             !quotaField.equals("null");
  }
    
  public void replicateGlobally(PolicyChange change) {
      List<String> regions = getGlobalRegions();
      for (String region : regions) {
          // NULL POINTER: change.getPolicy() can return null
          spannerDB.insertPolicy(region, change.getPolicy());
      }
  }
}

Right 👉

public class ServiceControlPolicy {
  private SpannerDatabase spannerDB;
  private QuotaManager quotaManager;
    
  public void applyPolicyChange(PolicyChange change) {
      if (change == null) {
          // Assuming it comes from an external API
          // Beyond your control
          change = new NullPolicyChange();
      }
      
      Policy policy = findPolicyOrNull(change.policyId());
      String quotaField = policy.quotaField();
      if (!quotaField.isEmpty()) {
          quotaManager.updateQuota(quotaField, change.value());
      }
  }
    
  public void exerciseQuotaChecks(String region) {
      if (region == null || region.isEmpty()) {
          // Assuming it comes from an external API
          // Beyond your control
          return;
      }
      
      List<Policy> policies = policiesOrEmpty(region);
      
      for (Policy policy : policies) {
          String quotaValue = policy.quotaField();
          if (!quotaValue.isEmpty()) {
              quotaManager.checkQuota(quotaValue.trim());
          }
      }
  }
    
  public boolean validatePolicyData(Policy policy) {
      if (policy == null) {
          // Assuming it comes from an external API
          // Beyond your control
          // From now on, you wrap it
          policy = new NullPolicy();
      }
      
      String quotaField = policy.quotaField();
      return quotaField.length() > 0;
  }
    
  public void replicateGlobally(PolicyChange change) {
      if (change == null) {
          // Assuming it comes from an external API
          // Beyond your control
          // From now on, you wrap it
          change = new NullPolicyChange();
      }
        
      Policy policy = change.policy();
      if (policy == null) {
          // Assuming it comes from an external API
          // Beyond your control
          // From now on, you wrap it
          policy = new NullPolicy();
      }
        
      List<String> regions = globalRegions();
      for (String region : regions) {
          spannerDB.insertPolicy(region, policy);
      }
  }
    
  private Policy findPolicyOrNull(String policyId) {
      Policy policy = spannerDB.policy(policyId);
      return policy != null ? policy : new NullPolicy();
  }
    
  private List<Policy> policiesOrEmpty(String region) {
      List<Policy> policies = spannerDB.policiesForRegion(region);
      if (policies == null) {
          // This is a good NullObject
          return Collections.emptyList();
      }
      
      return policies.stream()
              .map(p -> p != null ? p : new NullPolicy())
              .collect(Collectors.toList());
  }
}

class NullPolicy extends Policy {
  @Override
  public String quotaField() { return ""; }
    
  @Override
  public String policyId() { return "unknown-policy"; }
    
  @Override
  public Map<String, String> metadata() { 
      return Collections.emptyMap(); 
  }
}

class NullPolicyChange extends PolicyChange {
  @Override
  public String policyId() { return ""; }
    
  @Override
  public String value() { return ""; }
    
  @Override
  public Policy policy() { return new NullPolicy(); }
}

Detection 🔍

You can detect potential null pointer exceptions by reviewing code for direct method calls on objects without null checks.

Linters can examine return values from methods that might return Null, looking for uninitialized object fields, and using static analysis tools that flag potential null dereferences.

Modern IDEs often highlight these issues with warnings.

Level 🔋

Why the Bijection Is Important 🗺️

In the real world, objects either exist or they don’t.

When you model this correctly in your program, you create a clear one-to-one correspondence between reality and code.

Breaking this bijection by allowing null references creates phantom objects that exist in your code but not in the real world, leading to crashes when you try to interact with these non-existent entities.

If you choose to name your license plate “NULL”, you will get a lot of parking tickets

AI Generation 🤖

AI generators frequently create code with null pointer vulnerabilities because they focus on happy path scenarios.

They often generate method calls without considering edge cases where objects might be NULL, especially in complex object hierarchies or when dealing with external data sources.

AI Detection 🧲

AI tools can detect and fix null pointer issues when you provide clear instructions about defensive programming practices.

Try Them! 🛠

Remember: AI Assistants make lots of mistakes

Suggested Prompt: Remove all Null References

Conclusion 🏁

Null pointer exceptions represent one of the most common runtime errors in programming.

You can remove most of these crashes by implementing proper null checks, using the Null Object design pattern, and adopting defensive programming practices.

The small overhead of validation code pays off significantly in application stability and user experience.

Relations 👩‍❤️‍💋‍👨

https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-iii-t7h3zkv

https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-xliii

https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-xxxix

https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-xxvi

https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-xlii

More Information 📕

Disclaimer 📘

Code Smells are my opinion.


I call it my billion-dollar mistake. It was the invention of the null reference in 1965

Tony Hoare


This article is part of the CodeSmell Series.

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter Email Print
Share
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article World’s first AI government minister to join cabinet in Dubai in 2026
Next Article Cyber Essentials certifications rising slowly but steadily | Computer Weekly
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Stay Connected

248.1k Like
69.1k Follow
134k Pin
54.3k Follow

Latest News

Here’s why ChatGPT needs to know how to make bioweapons
News
Uncertainty looms over next week’s launch of Huawei’s HarmonyOS NEXT system · TechNode
Computing
Amazon under UK investigation over alleged failure to pay suppliers on time
News
Telegram founder planning to leave fortune to his 100+ children
News

You Might also Like

Computing

Uncertainty looms over next week’s launch of Huawei’s HarmonyOS NEXT system · TechNode

1 Min Read
Computing

Everyone’s an AI User Now—But No One Read the Manual | HackerNoon

16 Min Read
Computing

Meituan shifts focus from GMV to order volume amid declining sales · TechNode

1 Min Read
Computing

Stop Prompting, Start Engineering: 15 Principles to Deliver Your AI Agent to Production | HackerNoon

45 Min Read
//

World of Software is your one-stop website for the latest tech news and updates, follow us now to get the news that matters to you.

Quick Link

  • Privacy Policy
  • Terms of use
  • Advertise
  • Contact

Topics

  • Computing
  • Software
  • Press Release
  • Trending

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

World of SoftwareWorld of Software
Follow US
Copyright © All Rights Reserved. World of Software.
Welcome Back!

Sign in to your account

Lost your password?