Class invariants

I’m a constructor-based dependency injection kinda guy but with everyone always talking about setter-based dependency injection I started to question my approach. When Dave Thomas reminded me about class invariants I knew that my constructor-based approach was the right one.

From Wikipedia:

…a class does not allow use of all possible values for the state of the object, only those that are well-defined by the semantics of the intended use…

and

The main purpose of a constructor is to establish the invariant of the class, failing if the invariant isn’t valid.

You know that you should use constructor-based dependency injection when the dependency answers the question is this a class invariant.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s