A variable should have one purpose.

Don’t overload variables into multiple meanings.

A variable should represent only one concept. It should be used for only one purpose. This seems obvious, but there three ways people go wrong with this.

First, some people will stuff multiple attributes into one variable. For example, imagine an object code of “DAL-4234-W”, where “DAL” represents location (Dallas?), “4234” is an object id, and “W” means the white model. That’s three separate pieces of information in one variable. Please don’t do this. Instead, create an object with three attributes.

myThing = new BusinessThing();
myThing.location = "Dallas";
myThing.id = 4234;
myThing.color = "white";

Not only is this a ton easier to read, it’s also immediately obvious what the component pieces represent.

The second problem people have is by adding hidden meanings. For example, say a variable normally has values between 1 and 200, representing something like length. But in this weird case, a -1 means an error code (couldn’t calculate length) and -2 means a different error (invalid permissions). Furthermore, a special code of 999 means this is a test object.

Magic numbers like these are really not obvious and can lead to trouble later if the attribute is used as input to a later process. Instead, put error codes elsewhere, or throw exceptions.

The third problem is that sometimes a variable will get re-used for a different purpose. This commonly happens with “temporary” variables. For example, maybe “i” means the count of packages at the top of the routine, but later in the routine “i” is used as a counter of shipping stations. Initially, it works, but when the code is altered later by someone else, the new developer is unaware of the re-use, and the scope of the variable changes enough to introduce bugs.

So avoid these problems by forcing variables to do only one thing. You can always make more variables; there’s plenty of room.

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 )

Connecting to %s

%d bloggers like this: