# 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](https://martinfowler.com/bliki/LazyInitialization.html)

# Solutions

1. Inject Responsibilities with First Class Objects

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/0d762f54e37352ed72eee7e77d0ae5e0)
```ruby
class Employee
  def emails
    @emails ||= []
  end
  
  def voice_mails
    @voice_mails ||= []
  end
end
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/dbd08513d5005325e63954515052555d)
```ruby
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](https://maximilianocontieri.com/singleton-the-root-of-all-evil) 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

%[https://maximilianocontieri.com/code-smell-32-singletons]

# More Info

- [Wikipedia](https://en.wikipedia.org/wiki/Lazy_initialization)

-[Martin Fowler](https://martinfowler.com/bliki/LazyInitialization.html)

# Credits

Photo by <a href="https://unsplash.com/@samsolomon">Sam Solomon</a> on <a href="https://unsplash.com/s/photos/lazy">Unsplash</a>  

* * *

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

_Jeff Atwood_
 
%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
