Since 2009, I have had the opportunity to review code written by
different people who utilize different coding styles. Some programmers
try to keep a high level of consistency and follow logical standards,
others write code as if it were a series of cryptograms that nobody else
is supposed to understand, and others simply don't care. I have come to
realize that I can be significantly more efficient by writing source
code in a way that allows me to go back to it months after having
written it and still be able to quickly understand how it works and what
it does. In order to achieve this, I have had to pick up good coding
habits from other developers.
The following list is my attempt at summarizing the coding guidelines
that have helped me learn how to write more maintanable source code.
1. Use logical, material and descriptive names:
Trying to determine what a variable
contains, or what a method does should be as straightforward as
possible. It is an all too common practice to use abbreviations, single
letters or seemingly random names for variables, functions and class
names. Using abbreviated names doesn't make sense in almost any
practical programming language (and there are usually minifiers for those where it does).
For example:
foreach( $usrs as $usr ) {
$u_ph = $usr->PhNum();
$u_ad = $usr->Addr();
$u = $usr->Name();
echo "User: {$u} - {$u_ph} - {$u_ad}\n";
}
Sure, sounds like fun. But the big
problem here is that it becomes hard to keep track of these variables
and over time it becomes very time consuming to back-track where they're
being set, what they mean, etc. The same applies to method names. Even
though your IDE does half of the work by giving you a nice list of all
methods available for an object, it makes sense to use full sentences
that are meaningful and tell you right away what to expect from the
method. Having to check a method's documentation on a regular basis to
even know what it does is a sign that it needs to be renamed.
The advantages of using real names in
code are more subtle in some cases than in others, but considering how
little additional work is actually required to name things sensibly it
is an overall winning strategy. Notice how the above code can become a
self-documenting code-block by making some minor changes to element
names.
foreach( $users as $user ) {
$user_phone_number = $user->getPhoneNumber();
$user_mailing_address = $user->getMailingAddress();
$user_full_name = $user->getFullName();
echo "User: {$user_full_name} - {$user_phone_number} - {$user_mailing_address}\n";
}
The extra effort is minimal, and anybody reading the code will be able to easily know what's happening.
Overall strategy:
- Establish a naming convention based on real names that mean something.
- Avoid any abbreviations unless they are part of your target industry's every-day lingo.
- Try to be obvious.
- In method names, try to use a name that describes what the method really does.
- Follow a naming standard such as consistent combination of Camel Case and under_scored names.
- If using a development framework, it often makes sense to use the naming conventions set by the developers of the framework.
2. Keep your indentation consistent:
Indentation of code, in most programming
languages, plays a big role in readability. Try to maintain your code
indentation consistent throughout the entire application. I personally
like to use 4 spaces per tab because it gives each block enough
definition for me to easily spot where a construct starts and where it
ends.
I recentrly picked up the habit of
indenting code after a comment that describes a process containing one
or more steps (lines of code), which I think allows you to follow
comments more quickly as you know right away what code is involved.
For example:
if( $this->getRequestParameter( 'document_style', null ) == null ){
// Load default Style and apply it to the Document.
$default_system_style = DocumentStylePeer::getDefaultSystemStyle();
$document->setStyle($default_system_style );
$document->save();
// Send a message to the User notifying them of the style change
$style_change_message = "The style of document {$document->getName()} has been changed to the system default.";
}
Overall strategy:
- Stick to your indentation prefference. Make sure all members of the team use the same.
- Consider grouping related lines of code under a comment that describes what they do
3. Maintain a consistent spacing style:
Spacing is not as important as
indentation, but the code can be easier to read if the spaces left
between parentheses and text, brackets, etc. I, for example, like to
leave a space between parentheses and text inside language constructs:
if( $application->getName() == 'control_panel' ){
foreach( $application->getAliases() as $application_alias ){
$output_text->addLine(�"Application alias: {$application_alias}" );
}
}
Overall strategy:
- Keep your spacing consistent.
- Add spaces where needed to increase readability of the code.
4. Add meaningful comments:
Sometimes it is impossible to write self-explanatory code. Some
scenarios require complex procedures and so comments become necessary.
Additionally, your thought process is very different when you are
writting a piece of code and when you're going back to read it or change
it after a few months or even a few days. For that reason, comments
should serve as a guide in the code allowing you to quickly split the
code in logical parts and understand how everything fits together.
When writing comments, avoid assumptions
and try to write everything that you think you may forget later on.
Writing the requirement that you are trying to fulfill usually helps as
well as it is easier for you to figure out how the code works by knowing
beforehand what it is trying to accomplish.
Overall strategy:
- Think of your comments as a guide for you or others to understand your code.
- Avoid assumptions.
- Anotate the conditions you are trying to meet.
- Write down things you may forget later.
5. Add annotations for To-Do items to aid refactoring:
In some circumstances you are forced to write minimalistic code that
you know will serve its purpose, but it is not the ultimate solution you
had in mind. Fixing the code so that it is more robust may be an
important thing to do later in the project when you are refactoring.
However, it is usually impossible to remember exact changes that need to
be made to the code when you finally get the time to do it. Comments
are a quick and easy way to keep track of those so that you don't have
to distract yourself logging into the bug tracker to create a new case
or keeping a separate document outlining these changes.
Even if you keep a separate document with
this changes, in-code comments are contextual and can very effectively
remind you of the changes you had in mind for specific sections of code.
// TODO: change the following code so that it uses the Request object istead of $_REQUEST
if( $_REQUEST['appointment_id'] ){
$appointment = AppointmentPeer::retrieveByPrimaryKey( $_REQUEST['appointment_id'] ); $appointmet->delete();
}
Overall strategy:
- Write down references to what you need to fix or improve in the code later.
- Try to be as specific as possible.
- Try to use the same format for ToDo comments so that you can find them later easily.
6. Follow a design pattern:
Design patterns are fundamental to maintainable code. Patterns such as Model-View-Controller (MVC)
dictate well-established solutions to common organizational problems in
programming. It is important not to re-invent the wheel unless you're
really trying to do so. In other words leverage the work that has
already been proven to be efficient by building your code following the
guidelines set by whatever development patter that makes sense for your
project.
Code written with a development pattern
usually yelds well-organized modules, clear data-flows and easy to
understand procedures. It makes it easier to group your code logically
and enables you to find specific parts of your code more quickly.
Overall strategy:
- Stick to the guidelines of a design patter that makes sense for your project.
- Learn as much as you can about the pattern you are using.
- If using a development framework, it often makes sense to use the coding guidelines set by the developers of the framework.
7. Store your code in meaningful folder structures:
The naming conventions should also apply to your folders. Split up
your code in logical groups and store it in folders that describe what
they contain. This will make it much easier to keep your code-tree
organized and scale it to thousands of files without hindering your
ability to get to specific files quickly.
If you are doing web application
development and you are using a framework, you will usually have to only
organize newly added code. For example, the Symfony framework
provides a very comprehensive folder structure that you can quickly add
to. In Symfony, I create folders as I add source files as I see fit in
order to keep them organized.
Overall strategy:
- Group your source files in logical groups
- Keep your folder names consistent throughout the project.
- use your naming convention recursively inside of your sub-folders.