|
I believe if an object has a lifecycle that has this pre-initialized stage, then you are better off making sure that the object in that stage is accessible only within a limited scope. The idea is that you have some library code that initializes the object completely, sets the flag and then passes the reference. Noone but the library should have access to the object before initialization is complete. This pattern can used e.g. in a factory method.
Of course the library code can still do the wrong thing, but that's your fault, then ;-)
If the initialization has to be done in client side code, you can go the other path and use mutable companion classes, such as StringBuffer/StringBuilder -- another aspect that didn't fit into the article. That pattern is very safe, but it has the drawback of requiring two classes and two objects for each creation. But in my opinion that is a reasonable price for the safety you can get this way and the optimizations you can do later on the immutable objects can easily make up for it (on a side note: some optimizations are possible only on completely immutable objects, such as copying it across a wire instead of using remote callbacks). |