"Lazy evaluation" principle consists in doing a calculation as late as possible. Is is a form of "procrastination" (= postponing everything).
Let's take as an example a game where the player triggers abilities via buttons. These buttons all have a UI updating method. Let's call this method OnCapacityChanged()
here. This method updated graphical widgets depending on values (box is checked or unchecked, button is grayed out or not, selectable or not, etc.).
Now, let's imagine we call the update method for each value change:
void SetGameCapacity(GameCapacity gc) {
gameCapacity = gc;
OnCapacityChanged();
}
void SetHidden() { hide = true; OnCapacityChanged(); }
// etc.
Obvious main advantage: every change will update the UI immediately. Drawback: if we change multiple values at a time, there will be multiple updates, when only one is actually needed. For instance:
box.SetGameCapacity(myCapacity);
box.SetHidden(false);
The trick is to replace the content of OnCapacityChanged()
to indeed perform a lazy evaluation. This would look like:
void OnCapacityChanged() { dirty = true; }
void Update() {
if (dirty) { // If OnCapacityChanged() was called at least once in a single frame...
OnCapacityChanged_DoUpdateUI(); // then perform the "real" UI update...
dirty = false; // and revert the flag to its normal state.
}
}