Give Meaning To Your Code – naming of variables and types

The rule
This probably sounds obvious, but apparently it isn’t. What’s more, if you think about it, it even isn’t that easy to make the difference.

Your variables have a Behaviour and a Role
Behaviour maps to the type of your variable, and the role maps to the name of your variable.

The problem
We’ve had a round of code review today and while looking into the code I saw some classes which where really a packing of the same members into several classes. Those classes where then given different names.

An simple example will make clear what I mean (These are my own samples and not the real code):
(code is C++)

class Person
{
public:
   int GetAge();
   void SetAge(int age);

private:
   int m_age;
}

class Husband
{
public:
   int GetAge();
   void SetAge(int age);

private:
   int m_age;
}

class Wife
{
public:
   int GetAge();
   void SetAge(int age);

private:
   int m_age;
}

The Solution
In the above sample code, the classes Husband and Wife shouldn’t really exist. You should use variables with names husband and wife and with type Person. The role is husband and wife and they have the behaviour of Person.

This requires knowledge of the domain your application is written for because the distinction isn’t always that easy, as you will see in the following caveat’s.

Caveat
You probably think that this is obvious and in the above classes it is. But what if you have a class Person and you want to model “Male” and “Female”. Do you create new classes representing those or do you add a member “Sex” to the above class in which you make the difference between males and females?

Or maby you will have started with a class named Male, and then later you want to model females too. Will you make a class Female, or will you rename your class Male to Person and add the Sex member? The last solution will require you to adapt your code everywhere you use Male to set it’s Sex member.

You may also have two classes which are very common but differ slightly. Should you pack them into one class, or should they stay different. Maybe they must inherit from a common baseclass.

Updates
11 November 2006: original version

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