Variables

Choosing Names

There are quite a few schools of thought on this issue ranging from what is called Polish notation to long variable names. While all of the different approaches are attempting to devise a fool-proof method of variable naming that any idiot can understand, often the result is that the naming scheme gets in the way of understanding the code. You may clearly understand what this variable is, but have trouble understanding what is being done to it.

Pick Variable Names That Describe Them

I frown on the use of prefixes to identify variable type such as using $Icounter or $Bisobject to signify the first is an integer and the second is a boolean. That's what type declarations are for. If we take this to an extreme we might get $AoOstuff which might refer to an array of objects called stuff. Instead, let's be practical (can you imagine that?).

Consider the following case: We have an array of person objects that we want to create.

$people = array();
$people[] = $person;

So, people is a collection of multiple person objects, as in life. Is this hard to understand? I don't think so. The solution is to pick names that describe the contents, not the format of the data. We are trying to explain to people what we are dealing with. When we tell someone our phone number, do we need to explain to them that it is a sequence of numerals or is that understood already by the fact that it is a phone number?

Use Descriptive Names

OK, so what about long variable names? We could have $city_for_home_address_within_the_United_States and $city_for_work_address_within_the_United_States. The meaning of each variable name is clear, but since they are so long, it is hard to distinguish the two apart since the unique piece is somewhere in the middle.

Instead let's simplify this a bit and improve readability without sacrificing meaning. How about $home_city_US and $work_city_US? The unique part is at the front so its more obvious as to which is which and it's shorter so the use within the code is not obscured. Now let's eliminate extra characters so we get $homeCityUS and $workCityUS. Better? Of course it is.

Pick names that make sense in the context of what you are doing. It is understood by most programmers that variables like $i, $j, $k all are used as indexes so it isn't necessary to resort to names like $role_index when $r is clear in common use.