Pure Danger Tech


navigation
home

Dependencies vs state

23 Feb 2005

There was a great question during my dependency injection presentation on the difference between dependencies and the state of an object. In retrospect, I think I didn‘t answer it very well, so I‘d like to take another stab at it.

I quite commonly separate the attributes of a class into three categories:

  1. Dependencies – typically resources required for the class to operate
  2. State – the dynamic state of an object during it‘s lifetime
  3. Derived state – dynamic state derived from the state

When I think about dependency injection, I typically am thinking only about the first category and usually those dependencies represent other resources or components and are defined by an interface. One difference between the dependencies and the state is that I don‘t expect my dependencies to change during the lifetime of the object. The state however, may change in response to what is occurring in the application.

A simple example might be a Person object:

person

In this object, I would characterize the PersistentStore as a dependency (an external resource), the name and birthday as state, and the age as derived state.

One reason to break things up this way is that it tells you how to clone objects (which may or may not really make sense for this kind of an object). Typically resources are just copied into a clone (it uses the same resources, not copies of them), state is cloned deeply, and derived state may not be copied at all, as it can be re-derived as necessary.