As a developer, more of your time will be spent reading and understanding code than actually writing it.
In fact, Peter Hallam says he actually spends 78% of his day simply understanding code while spending only 22% of his day writing new code and modifying existing code. When you stop to think about your average day, my bet is that you’ll notice results that are of similar proportion. While some of this time is unavoidable and necessary, you should be driving your team to write code that holds a certain standard of both readability and maintainability. Inevitably, these standards will lead you and your team to greater profitability and more time spent doing what you love—writing code.
The coding specifics we talk about today will all center around answering “yes” to a common question that should enter your mind whenever you’re writing new code:
If we added a new team member today, would they be able to change this code and be confident that it wouldn’t break this or something else?
I realize that, in most cases, you wouldn’t throw a new team member onto your biggest client’s production storefront all by their lonesome without any direction or back history, but if you strive to write your code in a way that will be easily read and understood by a new team member, you’ll accomplish the task I’m trying to lay out in that hyperbole of a situation.
Keep Your Object Methods Short
We’ve all seen the methods that contain about 500 lines of code. In all but maybe 0.000001% of those occurrences, the object methods shoudl've been broken out into smaller, more changeable chunks within that or some other object. The fact is that, if your methods contain long, seemingly never-ending code chains, you’re probably violating one, two, or several other things talked about later in this post. In general, your object methods should only actually do one bit of work. The more work your methods do, the harder they are to reuse and eventually change.
This is simple: don’t repeat yourself. Every time you unnecessarily copy and paste a block of code, a small puppy dies. So save a puppy and break that block of code out into its own method. It costs you 30 seconds of writing new code for 30 minutes of refactoring it later when you’ve built the rest of your application.
It’s important that when developing you keep boundaries between things that have little or nothing to do with each other. The Law of Demeter says that method M of object O should only be able to access:
- O’s methods
- M’s parameters
- Objects instantiated by M
- Direct component objects of O
- Global variables accessible by O and in the scope of M
Adhering to the Law of Demeter will make your code easier to change because your objects will be loosely coupled together. A good example of this would be a database abstraction layer. What if you coded your entire application and then wanted to change database providers? You shouldn’t have to re-code all of your models. You for sure shouldn’t have to change your controllers or views.
Don’t Abuse Shorthand
In most programming languages, shorthand syntaxes are available to make your code a bit more concise. Some developers will combine shorthand syntaxes and/or use them too often, making the code illegible to the glancing eye.
form_dropdown('num-results', array('10' => '10', '25' => '25', '50' => '50', 'view_all' => 'View all'), (isset($_POST['num-results']) ? $_POST['num-results'] : '25'), $attr);
There are several things wrong with this line of code. We’re only going to point out the formatting. For one, it’s too much on one line. If you still wanted to cram all of this into one statement, you should make use of good indenting and formatting to make it a bit more readable:
form_dropdown( 'num_results', array('10' => '10', '25' => '25', '50' => '50', 'view_all' => 'View all'), (isset($_POST['num_results'])) ? $_POST['num_results'] : '25', $attr);
This helps a lot, but there is a case to be made about even breaking it out further:
$dropdown_options = array( '10' => '10', '25' => '25', '50' => '50', 'view_all' => 'View all' ); $number_of_results = (isset($_POST['
num_results'])) ? $_POST['
num_results'] : 10; form_dropdown('
num_results', $dropdown_options, $number_of_results, $attributes);
The benefit here is that you get the context of well-named variables which not only make the code more meaningful, but also provide a bit of self-documentation for the
Use Consistent, Meaningful Naming Conventions
// These are vague and provide no type hinting $results $i var results var i // This is better, we know now what we're working with $results_array $result_index var results_array var result_index // Same as above, but with camelCased conventions var resultsArray var resultIndex // Condensed version without losing meaning $results_arr var arrResults
Use Consistent Formatting
Again, you should stick to the conventions of your chosen programming language, but whatever formatting style you choose should be employed throughout the entire application. Don’t use tabs to indent in one file and use spaces in another. If you copy in someone else’s code and it doesn’t match your chosen formatting style, you must modify the code to be uniform. If you are leading a team of developers, you should be implementing a code standards guideline that will set these rules. This will help your team more efficiently work together, which will make them more profitable and your organization’s code will have a polished, uniform look.
Going back to the newbie team member, he/she will have much less context of the file they’re working on than you do. It is also possible that this person will be less familiar with the programming language or module than you. It’s important that you don’t make assumptions about what is known by the person who is reading your code. How verbose you make your comments depends entirely on the situation. There are times when I’ll write a paragraph above a particular code block to explain a complex situation that would be confusing to someone just jumping on the project. I’ll thank myself when I re-visit that block of code a year later, wondering what I was thinking.
I’ve heard the rant about how you shouldn’t have to comment your code if you’ve written it well. There is some truth to this, but most of it is crap. The people who say this are misunderstanding the usefulness of commenting by assuming that comments only describe the function of a particular piece of code. The truth is, most of the time the comments you make will not be detailing what you’re doing; rather, the comments you make will be detailing why you’re doing it. Since the developer’s thought process is not checked into Git at the end of the day, commenting is a necessary piece of making your code easier to change.
Commit Logically; Write Meaningful Commit Messages
Since we’re all using version control now (as we should be), it’s important that people understand how to commit and write commit messages. I remember the day that I made Josh Miller a believer in using Git for our ExpressionEngine web sites. We had just rolled out some big changes to a client’s web site and were testing throughout the day. Come to find out, I had written some code that broke a very small, but important part of the site. Yeah, I screw up too. The problem is that it wasn’t noticed until about 6PM local time—at which point I was in an airplane flying over the Cumberland River in Nashville and was unreachable. Luckily, Josh looked at the commit history, found the changes I made and was able to rollback the deployment until I had a chance to look at it.
I tell that story to say this: what if I had changed multiple features in one commit? What if in one commit, a feature was only halfway finished? It’s possible that Josh could’ve broken the site even more if he had not reverted every commit I made. It’s important that you separate your commits into small, logical components. In general, I like to make my commits when I’ve written enough code to make a new feature stable, or if it’s a large feature, when I finish a logical section of that feature. I need to ask myself, "If I had to undo this commit, would things be stable?" If another team member or I has to revert my code, I don't want a whole bunch of unrelated code to be changed. Lastly, your commit messages should detail exactly what you changed. Instead of, “Adding Images” you might write, “Add images for the top navigation bar”.
Write Comprehensive Unit Tests
Unit testing is awesome. Whenever I work on a project that employs well-written unit testing, I don’t have to be familiar with the entire code base, nor do I feel any animosity when changing someone else’s code. I know that if I make a change and all the unit tests pass, there is little chance that my changes broke something else.
Unit testing web sites can be difficult. In fact, it’s almost impossible to unit test CMS templates. Unit testing works well for large product type applications and requires you to write code that is easy to test. That topic will have to wait for another day, but you get the picture.Share Article