O'Reilly logo

Functional Programming in Java by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Delayed Initialization

In object-oriented programming we ensure that objects are well constructed before any method calls. We encapsulate, ensure proper state transitions, and preserve the object’s invariants. This works well most of the time, but when parts of an object’s internals are heavyweight resources, we’ll benefit if we postpone creating them. This can speed up object creation, and the program doesn’t expend any effort creating things that may not be used.

The design decision to postpone creating part of an object should not burden the object’s users—it should be seamless. Let’s explore some ways to design lazy initialization.

A Familiar Approach

In the following example, we will craft a way to delay the creation of a heavyweight instance. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required