I am just in the middle of a huge code re-factoring. I am dealing with a huge amount of code which was previously made by someone else. Most of you probably know that working with someone else’s code is most of the time a pain in the ass. It gets even worse when it leaks in documentation.
So, for this really simple reason I decided to start writing quick-tips about coding which will hopefully help keeping your code clean and easy to understand. Here’s the first one.
Use sensible and self-explanatory variable names
Think about how much time you often spend on figuring out what a variable is used for or what it is supposed to be. There are some bad examples:
# a lot of code before... $b = SomeObject::getByID(12); $na = "Cutting Edge"; $nu = 12; $c = array('Audi', 'BMW', 'Mercedes', 'Aston Martin'); # a lot of code after...
Could you explain what those variables are meant to be? You will probably need to find the answer for that some other part of your code. A better way is to indicate the types and use self-explanatory variable names:
# a lot of code before... $oBox = SomeObject::getByID(12); $sName = "Cutting Edge"; $iNumber = 12; $aCars = array('Audi', 'BMW', 'Mercedes', 'Aston Martin'); # a lot of code after...
In this example, the first characters indicate the data types of each variable (”o” means that the variable in subject is an object, “s” stands for strings, “i” indicates integers and so on. Pretty straight-forward.)
You may ask why this is a big deal. I tell you:
- Easier to understand,
- You know what to expect from a variable,
- Others will understand the structure of your code a lot faster,
- Also, it will be even easier for you too to maintain if you need to get back to your own code after a while.
So guys, please remember: Keep your code clean and sensible.
This notation is great. Funny thing, it’s called the “hungarian notation”: http://en.wikipedia.org/wiki/Hungarian_notation