Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Follow publication

Code Smell 88 — Lazy Initialization

Photo by Sam Solomon on Unsplash

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

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

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.

More Info

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

Jeff Atwood

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Written by Maximiliano Contieri

I’m a senior software engineer specialized in declarative designs. S.O.L.I.D. and agile methodologies fan. Maximilianocontieri.com

Responses (1)

Write a response