Extrinsic State

Sometimes a part of your program needs state associated with an object, but the rest of the system doesn’t care. For example, information about where an object is stored on disk is useful for the persistence mechanism but not the rest of the code. Putting this data in a field would violate the principle of symmetry. All the rest of the fields are useful for the whole system.

Store special-purpose information associated with an object near where it will be used instead of in the object. In the example above, the persistence mechanism would store an IdentityMap whose keys are the objects stored and whose values are the information about where they are stored.

One weakness of extrinsic state is that it makes copying an object difficult. Replicating an object with extrinsic state isn’t as simple as replicating its fields. Instead, all the extrinisic state must also be copied correctly, which could require different handling depending on how that state is used. Another weakness is the difficulty in debugging objects with extrinsic state. A conventional inspector doesn’t show all the data associated with an object. Because of these difficulties, extrinsic state is rare but useful when necessary.

Implementation Patterns

contents