# Initialization templates

Triceps has the common approach for building the complex objects in stages by the chained mehod calls (demonstrated here on a fictional class Object):

    Autoref o = Object::make()->addOption1(arg)->addOption2(arg);

Here

    Object::make()

is a convenience wrapper for

    new Object

, because the operator

    new

has an inconvenient priority. The

    new

or

    make()

returns a pointer to the newly constructed object, and then each method in the chain returns the same pointer (

    this

, from its standpoint) to facilitate the chaining.

While the chain executes, the pointer stays a simple pointer, not a reference. So the methods in the chain can't throw any exceptions, or the memory will leak. Instead they collect the error messages in an Errors object that has to be checked afterwards, like:

    if (o->getErrors()->hasError()) ...

Note that a reference to the object gets created first, so that on an error the object would be properly destroyed.

The convenience template

    checkOrThrow()

allows to do the check along with the chain, and if an error is found, convert it to an Exception:

    Autoref o = checkOrThrow(
    	Object::make()->addOption1(arg)->addOption2(arg)
    );

It does all the right things with the references.

Some objects need to be initialized after all the options have been set, since it's much easier to check things once and get the interaction of the options right rather than check on every option. And since the initialization might create the references to the object, to get it right, it has to be done after the main reference is created.

    Autoref o = Object::make()->addOption1(arg)->addOption2(arg);
    o->initialize();

The template

    initialize()

allows to do it in one expression:

    Autoref o = initialize(
    	Object::make()->addOption1(arg)->addOption2(arg)
    );

For some objects the initialization can't fail (nor any other errors can be created by the options). For the others, the errors needs to be checked afterwards, in the same way as shown above. The template

    initializeOrThrow()

takes care of the whole sequence of the initialization, the check, and Exception throwing on errors:

    Autoref o = initializeOrThrow(
    	Object::make()->addOption1(arg)->addOption2(arg)
    );

That's basically it. All these templates are defined in

    common/Initialize.h

.
error handling in &Cpp;
initialization
Exception