mardi 29 septembre 2015

Lazy and cheap initialization pattern

When one decides to use lazy initialization, he usually has to pay for it.

class Loafer
{
    private VeryExpensiveField field;
    private VeryExpensiveField LazyInitField()
    {
        field = new VeryExpensiveField();
        // I wanna then remove null check from accessor, but how?
        return field;
    }
    property Field { get { return field ?? LazyInitField(); } }
}

Basically, he has to check every time if his backing field has null/nil value. What if he could escape from this practice? When you successfully initialize the field, you can rid of this check, right?

Unfortunately, majority of production languages can not allow you to modify their functions in runtime, especially add or remove single instructions from the function body though it would be helpful if used carefully. However, in C#, you can use events mechanism to imitate such behavior with consequent lack of performance, because null-checks just move onto lower level, but do not disappear completely. Some languages, e.g. LISP and Prolog, allow you to modify their code easily, but they are hardly can be treated as production languages.

In native languages like Delphi and C/C++ it would be better to write two functions, safe and rapid version, and switch to rapid after initialization. You can even allow compiler or IDE to do this for you automatically.

And what common approaches are exist to develop such functionality?

Aucun commentaire:

Enregistrer un commentaire