12
OCT
2007
Foreword
My primary programming language is PHP. I am going to try to keep these rules as general as possible, for they should apply in any programming situation. The one exception to that theory is in my readability section, some of the syntax may differ. I will draw my examples using PHP.
Grab your keyboard and the nearest shuriken. There will be blood shed by the end of this article!
1. Readability
There are a few simple techniques that you can employ to make your code more readable. Readability is important if you’re working on your own, or if you’re working with people. Readability is literally how your code reads and nothing more. There are other players in the overall ability to follow your code, and I will allude back to this section when we get there.
Key Factors in Readability
Whitespace
Whitespace is free, use it. I know some people may disagree with me here, and I’ve seen their atrocious code, but spacing out your code is very important. Think of your code as a book, you need to allow the eye to find breaks and segways easily so that you can scan your code and find the break point you’re looking for.
Figure 1 (Poor Formatting)

Since this is a small amount of code, one could discern it’s intentions pretty easily. But, Figure 2 will show you the difference. It should make you feel like you’ve just showered off the poor formatting and inhaled a fresh breeze of readability.
Figure 2 (Clean Formatting)

With the right amount of line breaks, indentation, and spacing, you can produce readable code. Obviously, too much of any of these will start to look bad as well. Find a good median and stick to it throughout the rest of your code.
Alignment
When you have many similar lines of code, ask yourself if they can be aligned or grouped in such a way that express similartiy and also make it easy to extract information from.
Figure 3 (Messy variable declaration)

Again, in the small scheme of things, this is readable. But, you need to picture this in the grand scheme of things. If all of your code is not written in a careful manner, when you come back to read it, or if someone else has to read it, it will become a nightmare as it grows. In Figure 4, you will see that it’s almost the same except the variable names and values are aligned and the variables of similar types are grouped.
Figure 4 (Organized variable declaration)

Variable Naming
If you want your code to be readable, you should use descriptive variable names. As Alisto said below:
The difference between amateur and professional (and maintainable) code is the amount of semantic load you are required to carry around with you as you navigate through the code. Less semantic load = more brain power available for understanding what the code does.
With modern IDEs and editors there is no excuse for using shortened names for classes, procedures, etc., this increases the semantic load as each time you come across one, you have to expand it to understand it.
For example, a variable called ‘cnt’ does this stand for ‘current’, ‘count’ or what? It gets even worse if ‘cnt’ is expanded to different things in different modules of the code (possibly written by different people).
I agree completely. You should not need to stop and figure out what a variable stands for. If it’s impossible to express the variable’s contents simply by it’s name, then you should comment it and give a description.
2. Conformity
Conformity is very important in solo or group projects. It is all about keeping your coding style consistent throughout your entire application.
Solo
This can be harder to maintain on a solo level. As you begin to grow as a programmer, your techniques evolve. You can’t be expected to always go back and change all of your old code to reflect your new findings. Sometimes you will, but you can’t always do it.
Over time you will most likely begin to create your own library. A library, as you may know, is a set of code that you bring to every job. It’s basically your self-made toolbox. You begin to understand the need for functions and object orientation in order to make your life easier and reduce repetitive tasks. It is very important to keep your library fresh and take the time to tend to old wounds. Your library is your toolbox and you should make sure your tools are always cutting edge and sharp. If one of your tools grows dull, either sharpen it, or replace it.
Example
At one point in my career I had a set group of functions that I always included in my projects. One of them was called make_dropdown() which would take in an array of ids and their text equivalent and generate the HTML for the dropdown. I did this because it was getting old to always have to write a loop to populate dropdown menus.
Group
In college I had a professor Vic Berry, who made a great point that has stuck with me and should stick with everyone. When you’re joining a project, you shouldn’t push your own coding style. Make it easy for everyone and stick to the style of the project. If you’re making a plugin for wordpress, for instance, you should stick to the way the rest of the code looks in wordpress. Even if it’s atrocious. Why? Conformity in the grand scheme of things is very important.
If you’re reading through an entire project of code, you don’t want to see different coding styles all over the place. This prevents your brain from recognizing patterns. Even if the coding style isn’t to your liking, consistency is important and should be maintained to provide overall project readability.
3. Be Organized
This section plays into both Conformity and Readability. You should organize your files and code the same way throughout your entire project. If you have your includes at the top of the file, they should be at the top of the file in the same place in every file. Again, we’re building on the brain’s expectations and the way it handles patterns.
Code
If you don’t already know, in the software engineering world there is an architectural pattern called MVC (Model-view-controller). MVC separates the Model (database), View (Presentation, UI) and the Controller (what modifies the Model). I won’t go to deep into it here, because it’s an elaborate topic. It’s a great way to organize your code, though, and you should read up on it if you haven’t yet.
File Structure
This should also apply to your directory structure. If you’re naming a directory ‘lib’ in one place that contains specific files, it should be named ‘lib’ in another place that contains those similar specific files that pertain to that section.
Group similar files together. Javascript files go in js, CSS files go in css. Keep anything that doesn’t need to be accessed by the web outside of the web’s reach. Something like:
/home/website/website.com/public_html - Web accessible code (html, javascript, the “view”)
/home/website/website.com/system - System Code (functions, classes, dependencies, ajax functions)
4. Scalability
The ability for your code to scale is vital if you want to sell yourself as a programmer. It’s also vital if you’re supporting your own code and trying to expand it’s ability. The best way to approach scalability is to abstract things when possible. Even if you think you’ll never need to expand something, it’s good practice, and you can never be sure.
If you’re working on a larger project, try to avoid saying “We’ll cross that bridge when we get there”. Sure, cross the bridge, but make sure it’s built by the time you get there. It’s easy to cut corners and not take the extra steps in the early stages of a project. But, it’s very important not to rush and to think things through. The best example of a site that has had horrible scalability issues is Myspace which you can read about in this great article by David F. Carr titled Inside Myspace.
Example
Recently, one of my clients asked me to take their contacts database, which was only one table, and change it so they could have user-definable regions and contact groups within that region. When I had created the original contacts table, the region field was an enum(’US,’UK’,'Other). So, this is an example of how having some foresight could save you some trouble. I had to create the region table, then, update the contact table to have a region_id that corresponds to the contact’s and then update all of my code to reflect these changes.
5. Supportability
Sections 1-4 of this article all amount to this word: Supportability.
By making your code easy to read, organized, conformed, and scalable, you create supportable code. What is supportable code? Supportable code is something that is easily enhanced or modified or easily fixed. After you leave a project, if someone is given the task to fix a bug that falls in your region of code, the more supportable your code, the faster it gets fixed. People like you.
Comments
By now, many of you are probably foaming at the mouth waiting to point out that I haven’t mentioned comments. I’ve left it until the end intentionally. Comments are the most integral part of creating supportable code. While most of your code should tell a story on it’s own, there are times where comments will save you hours of work in the future.
When to use comments
- Functions. Comments are essential in describing the expected input, output, and purpose of a function.
- Complex logic. Use comments to give a human description of what is going on in the next several lines.
- Declaring variables. Indicate what the purpose of a variable is within its scope.
- Non-intuitive approach. When you are approach any situation with a non-intuitive approach, it is essential to comment.
When to avoid using comments
If you use comments all the time, they become less meaningful and defeat the purpose of having comments. Your comments will become diluted. Comments should be annotation, not narration.
- Don’t announce you’re going to // loop through vars
- Don’t comment if the code is redundant to your comment. // Checking if var is equal to 8
Conclusion
Every one of these techniques should become a habit. Each one of the sections in this article applies to each other, it’s almost incestuous. Organization requires conformity, conformity requires organizations, readability requires conformity, supportability requires everything, etc. It’s a vicious ninja star. Use it to tear through your enemies.

Buy me a beer if you liked this post or found it helpful









October 12th, 2007 at 3:42 pm
Dude, vicious code ninjas don’t care about readability, organisation, and all that tame gobbledygoo. Vicious code ninjas care about using awesomely clever tricks to compress their whole application into seven lines of code, and using their mean nerd-fu to decapitate anybody who dares criticise them for it. Also, they don’t write PHP, they write assembly — or Haskell.
October 12th, 2007 at 3:54 pm
@Reggie: lol. You must praise the ninja elders, the wise men. They let the boys be boys
October 14th, 2007 at 9:22 am
Nice post! I agree with most of your points, except:
Readability - alignment
===
I think there is a general idea that lining up equals signs (and a similar pattern — pretty banner boxes) is an anti-pattern in code formatting, because it increases the code-maintenance burden.
Comments
===
Comments are good when they are necessary, but too many comments is a code smell.
Particularly:
Declaring variables
The variable names should denote their purpose
Non-intuitive approach
A good hint that you need an intuitive approach
One situation where a non-intuitive approach should be commented, though:
When you fix a bug, and it might not be obvious why the fix is needed (to keep future maintainers/you from changing back the fix)
October 14th, 2007 at 11:54 am
@Ryan: I find that lining up equal signs in certain cases is easy if you have an IDE that supports it. When I hit tab twice for instance, in most IDEs, it ‘lines up’. If you hit tab twice on the next line, instead of passing the other equal sign, it stops at the same column.
Textmate has a nice feature where if you highlight text and hit apple + option + ], it lines everything up for you.
Thanks for the comment
October 14th, 2007 at 2:22 pm
Following on from some of the points thecookie and Ryan made.
The difference between amateur and professional (and maintainable) code is the amount of semantic load you are required to carry around with you as you navigate through the code. Less semantic load = more brain power available for understanding what the code does.
With modern IDEs and editors there is no excuse for using shortened names for classes, procedures, etc., this increases the semantic load as each time you come across one, you have to expand it to understand it.
For example, a variable called ‘cnt’ does this stand for ‘current’, ‘count’ or what? It gets even worse if ‘cnt’ is expanded to different things in different modules of the code (possibly written by different people).
October 14th, 2007 at 6:17 pm
@Alisto: Damn it I knew I forgot something important. Variable names should always be clear, no matter how long or annoying they are to type. I’m going to amend the post to reflect that. Thanks!
October 16th, 2007 at 3:34 pm
echo ($looksgood ? “Damn, you are stunning!” : “Ew, mashed codatos”)
October 16th, 2007 at 3:36 pm
@Greg:
I’d go with…
echo $looksgood ? “Damn, you are stunning!” : “Ew, mashed codatos”;
October 16th, 2007 at 6:50 pm
While LOC isn’t everything, I’d have to say this is a substantially cleaner and more readable way to format your specific example (short then clauses, and simple logic):
if ($looksgood) echo “Damn, you are stunning”;
elseif (!$looksgood) echo “Ew, mashed codatos”;
else echo “Start coding buddy”;
The ternary operator is cool, but excludes the third clause of the example statement in the two comments above.
October 16th, 2007 at 8:24 pm
@max:
In that case, I’d use braces. Always use braces.
if ($looksgood)
{
echo …
}
elseif ($looksbad)
{
echo …
}
else
{
….
}
October 17th, 2007 at 11:52 am
@max:
Re: third clause. I don’t know PHP, but does it really deny the law of the excluded middle? For what value of $looksgood will the third block be entered?
October 17th, 2007 at 11:34 pm
[…] 5 Elements of Writing More Professional Code The 5 Elements of Writing More Professional Code (aclevercookie.com) A good short article about elements of writing that are appropriate for any language. I agree will […]
October 19th, 2007 at 7:14 am
[…] auf http://www.aclevercookie.com/the-5-elements-of-being-a-vicious-code-ninja Bookmark to: (No Ratings Yet) Loading […]
October 21st, 2007 at 11:00 pm
[…] 5 Elements of writing more professional code […]
November 10th, 2007 at 11:30 am
I basically agree with what you are saying here; all of these are good practices with the possible exception of the code formatting suggestions in (1). In the day and age of IDEs like Eclipse and PHP-Designer, programmers can format source code to their own preferences with a single key stroke. So, maybe it isn’t necessary to be too rigid about this. (2) Standards conformity is extremely useful, but unfortunately PHP is not exactly famous for it. Let’s be honest. The inconsistencies of its own APIs and extensions and the name space pollution unfortunately don’t set a good example. In (4) I am not quite sure what you are saying about scalability, but it seems that you mean extensibility. Yes, extensibility belongs into the “good design” category, whereas scalability is an architecture goal/decision which is often desirable but not always required. When talking about golden rules one should probably also mention the three kings: DRY, KISS, and DRTW (sort of the eternal principles and mentioned in litertaure since the 60s…)
Cheers, Thomas
November 10th, 2007 at 3:26 pm
@Thomas: Thanks for the insight. Perhaps I have blended extensibility and scalability into the same category, but yes, both are important. Scalability is not always required, only in specific cases.