Staged constuction: a missing pattern?

August 7, 2012

Mr HostileFork argues that initialising an object after it has been constructed is against good object-orentiated design as exmplified by C++;. Contrary as ever, I will argue that C++ is anti good design.

The idea of once-and-for-all
construction is not a good match for processing that builds up complex data
structures in a number of stages. All the required data might not be initially
available to do the processing upfront, and it might be undesirableto do all the  
construction at once on timing grounds.
On the other hand, naively implemented “get” functions might try to return
data that isn;t ready yet. On way of solving that is for the “get..” for stage
N to check that the data from stage N-1 is ready, and if not, call the get of the previous
stage. N gets can therefore chain back. The user does not have to worry about
callign a series of methods in the right order. The check will prevent unnecessary
duplication of effort, since no processing is performed unconditionally (methods that engage
in staged construction can be made private). (Necessary re-performing of stages
where data has changed requires more complexity…blanking out all the data
belonging to the upstream stages to force them to be reperformed), The downside
is a small amount of extra runtime to perform the check. This technique resembles
the way SQL interfaces typically do not perform the query till the first fetch.(Lazy Initialisation
Alternatively, the stages could be turned into
a hierarchy. The class representing the Nth stage embeds an object of stage
N-1, or calls the constructor of its parent (and so on). However,
the C++/Java style of OO is not much more accomodating to the nesting/wrapping than
it is to staged construction.


Staged construction and destruction are needed for resource allocation and deallocation. Objects could be seen as a special case of two-state state machines, which leap from unconstrusted to constructed in a single bound. This idea is followed through in the incipient language Plaid. State machines are considered limited as languages, but there is a difference between a language entirely bassd on SMs, and a language that allows them to be constructed in conjunction with general purpose facilities.

The best things to do with state are to hide it as much as possible, or put it under as much explicit control as possible. Therefore, an ideal language would have a functional language embedded in a state machine language.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: