Naked Objects
By Richard Pawson and Robert Matthews

Enriching object behaviours

Initializing persistent objects

When certain types of logical object are first created you will need to give their value fields specific initial values or associate other specific objects with them. In Java this would be done in the constructor as it is only ever called once during the object's lifetime. In the Naked Objects framework, however, every time a logical object is retrieved from the object store it is re-instantiated using the class's constructor. This means that the constructor will be called more than once during the 'lifetime' of the naked object. You could find yourself inadvertently resetting all the fields each time an object was retrieved from storage, overwriting any other changes.

Initialising the logical object, therefore, should not be done in the constructor, but in the created method instead. This method is only called by the framework when an object is created using the factory methods we saw in the last section. This is what actually happens when the user selects the New Instance... menu option.

The following code extract sets up the value held by the quantity field when the logical object is instantiated. The value object should already exist at this point as it should have been initialized during the variable's declaration or within the containing object's constructor:

public void created() {

This does not mean that the constructor should never be used. The value objects and internal collections still need to be created before they can be accessed, including every time an object is recreated from persistent storage, and can, therefore, be done safely within the constructor.