DEV Community

Cover image for Code Smell 88 - Lazy Initialization
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

3 2

Code Smell 88 - Lazy Initialization

Yet another premature optimization pattern

TL;DR: Do not use lazy initialization. Use an object provider instead.

Problems

  • Surprising Side Effects

  • Premature Optimization

  • Fail Fast Violation

  • Implementative Coupling

  • The Least Surprise Principle Violation

  • Null Usage

  • Mutability

  • Transactional and Multi-threaded applications problems

  • Debugging Problems

Solutions

  1. Inject Responsibilities with First Class Objects

Sample Code

Wrong

class Employee
  def emails
    @emails ||= []
  end

  def voice_mails
    @voice_mails ||= []
  end
end
Enter fullscreen mode Exit fullscreen mode

Right

class Employee
  attr_reader :emails, :voice_mails

  def initialize
    @emails = []
    @voice_mails = []
  end
end
#We can also inject a design pattern to externally deal
#with voice_mails so we can mock it in our tests
Enter fullscreen mode Exit fullscreen mode

Detection

  • Lazy initialization is a common pattern when used checking for a non-initialized variable. It should be straightforward to detect them.

Tags

  • Premature Optimization

Conclusion

Singletons are another antipattern often combined with lazy initialization.

We must avoid premature optimizations. If we have real performance problems we should use a Proxy, Facade or more independent solution.

Relations

More Info

-Martin Fowler

Credits

Photo by Sam Solomon on Unsplash


We have to stop optimizing for programmers and start optimizing for users.

Jeff Atwood


This article is part of the CodeSmell Series.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Explore this insightful piece, celebrated by the caring DEV Community. Programmers from all walks of life are invited to contribute and expand our shared wisdom.

A simple "thank you" can make someone’s day—leave your kudos in the comments below!

On DEV, spreading knowledge paves the way and fortifies our camaraderie. Found this helpful? A brief note of appreciation to the author truly matters.

Let’s Go!