5

While reviewing codes, sometimes I see words like lazyLoad, lazyActivation, lazyInit, LazyValue. I am coding Java currently and most of naming conventions in Java are specified in many sources but not lazy. So I wonder if "lazy/lazily" is a convention and what does it mean.

Emre dağıstan
  • 179
  • 1
  • 14

1 Answers1

7

In a nutshell, "lazy" means to defer an action until it becomes necessary, if ever. If the result of the action is never used, the action will never be carried out, saving some work. An arbitrary example that comes to mind in pseudo-real Python is:

import gettext_lazy

class Foo:
    bar = Baz(name=gettext_lazy('Baz label'))

This defines a class and a field in the class which has a name. The name is localised into different languages by gettext. gettext requires loading a translation file, parsing it into memory etc. If this name is never used anywhere (e.g. print(Foo.bar.name)), then all that work of loading the files would be wasted. Also, at the point of this class definition it may not be decided yet what locale we'll be using to output the name later.

For these two reasons, the actual evaluation and localisation is being to deferred to sometime later, until it actually becomes necessary to print that name.

You will often find somewhat more abstract examples in various languages like infinite lists which you can still iterate over since they're never evaluated until their (non-existing) end and such, but this is a rather practical example.

deceze
  • 510,633
  • 85
  • 743
  • 889