Parameterized constructors
Factor handbook » The language » Objects » Tuples » Tuple constructors

Prev:C:


A parameterized constructor is a word which directly or indirectly calls new or boa, but instead of passing a literal class symbol, it takes the class symbol as an input from the stack.

Parameterized constructors are useful in many situations, in particular with subclassing. For example, consider the following code:
TUPLE: vehicle max-speed occupants ; : add-occupant ( person vehicle -- ) occupants>> push ; TUPLE: car < vehicle engine ; : <car> ( max-speed engine -- car ) car new V{ } clone >>occupants swap >>engine swap >>max-speed ; TUPLE: aeroplane < vehicle max-altitude ; : <aeroplane> ( max-speed max-altitude -- aeroplane ) aeroplane new V{ } clone >>occupants swap >>max-altitude swap >>max-speed ;

The two constructors depend on the implementation of vehicle because they are responsible for initializing the occupants slot to an empty vector. If this slot is changed to contain a hashtable instead, there will be two places instead of one. A better approach is to use a parameterized constructor for vehicles:
TUPLE: vehicle max-speed occupants ; : add-occupant ( person vehicle -- ) occupants>> push ; : new-vehicle ( class -- vehicle ) new V{ } clone >>occupants ; TUPLE: car < vehicle engine ; : <car> ( max-speed engine -- car ) car new-vehicle swap >>engine swap >>max-speed ; TUPLE: aeroplane < vehicle max-altitude ; : <aeroplane> ( max-speed max-altitude -- aeroplane ) aeroplane new-vehicle swap >>max-altitude swap >>max-speed ;

The naming convention for parameterized constructors is new-class.