Template method in constructors: a special pattern

It’s common to hear against the use of a virtual method in a constructor of a base class. That’s because the child class isn’t properly initialized when the virtual method runs. The following link explains the case:


The order of execution usually involves this order: base.constructor -> child.virtualmethodoverrided -> child.constructor. Any code that is supposed to initialize/construct the child is running after the overridden method. The usual recommendation is to avoid using the virtual method and to use an appropriate initialize method independently of the constructor. That results in two initializing operations: constructors and initialize methods. The solution isn’t at all satisfactory because implies an artificial division of the construction operations.

The most common use of a virtual method in a constructor is the special case when a constructor as a template method. In many cases the virtual method body is empty or the hook method is an abstract. When using a template method pattern in a constructor of a base class, the parent class imposes an algorithm of initialization to children that override the hook method. The hook method in this kind of template method should function as an initialize method that must replace the constructor of children. The child can’t ignore the base intentions, because it’s the child which overrides the virtual/abstract hook method. In any case, the constructor in the child method can’t surpass the imposition of its parent ignoring the execution order defined in the template method.

As a result, a constructor that is also a template method isn’t just another template method, but a special one. A constructor like a template is a pattern that profiles the algorithm of initialization, replacing in some instances, the constructor operation of children classes.

Anuncio publicitario

Deja una respuesta

Por favor, inicia sesión con uno de estos métodos para publicar tu comentario:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Salir /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Salir /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Salir /  Cambiar )

Conectando a %s