Find What Is Varying and Encapsulate It

http://www.informit.com/articles/article.aspx?p=167890&seqNum=4

Containing variation in data versus containing variation in behavior

Suppose I am working on a project that models different characteristics of animals. My requirements are the following:

Each type of animal can have a different number of legs.

Animal objects must be able to remember and retrieve this information.

Each type of animal can have a different type of movement.

Animal objects must be able to return how long it will take to move from one place to another given a specified type of terrain.

A typical approach of handling the variation in the number of legs would be to have a data member containing this value and having methods to set and get it. However, one typically takes a different approach to handling variation in behavior.

Suppose there are two different methods for moving: walking and flying. These requirements need two different pieces of code: one to handle walking and one to handle flying; a simple variable won’t work. Given that I have two different methods, I seem to be faced with a choice of approach:

Having a data member that tells me what type of movement my object has.

Having two different types of Animals (both derived from the base Animal class)—one for walking and one for flying.

Unfortunately, both of these approaches have problems:

Tight coupling—The first approach (using a flag with presumably a switch based on it) may lead to tight coupling if the flag starts implying other differences. In any event, the code will likely be rather messy.

Too many details—The second approach requires that I also manage the subtype of Animal. And I cannot handle Animals that can both walk and fly.

Handling variation in behavior with objects

A third possibility exists: have the Animal class contain an object that has the appropriate movement behavior.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s