Introducing Lazy Evaluation and Proxy Objects
Learn how lazy evaluation differs from eager evaluation and how to use proxy objects.
We'll cover the following
First and foremost, the techniques used in this chapter are used to hide optimizations in a library from the user of that library. This is useful because exposing every single optimization technique as a separate function requires a lot of attention and education from the library user. It also bloats the code base with many specific functions, making it hard to read and understand. By using proxy objects, we can achieve optimizations under the hood; the resultant code is both optimized and readable.
Lazy vs. eager evaluation
Lazy evaluation is a technique used to postpone an operation until its result is really needed. The opposite, where operations are performed right away, is called eager evaluation. In some situations, eager evaluation is undesirable as we might construct a value that is never used.
To demonstrate the difference between eager and lazy evaluation, let’s assume we are writing some sort of game with multiple levels. Whenever a level has been completed, we need to display the current score. Here we will focus on a few components of our game:
-
A
ScoreView
class responsible for displaying the user’s score with an optional bonus image if a bonus was achieved -
An
Image
class that represents an image loaded into memory -
A
load()
function that loads images from the disk
The implementation of the classes and functions is not important in this example, but the declarations look like this:
Get hands-on with 1400+ tech skills courses.