Before we jump to the article, would you like to share your opinion
if the poll does not load for you, please cast your vote here.
Sometime around May 2012 I was interviewing for an internship at Microsoft when I was asked a question during the telephonic interview. The lady asked “What is good code to you?”. I said “I believe that the person who is going to manage your code is a serial-killer and he knows your address. Any code written with that knowledge is good code.”. This one liner that I read somewhere on the inter webs highlights how much writing manageable code mattered to me. She laughed and did not ask me to go deeper on that. However, often times I see code snippets online on Github and other places that makes me cringe.
The code is usually not bad in totality, but the shortcuts and concessions made by programmers at the time of coding made it harder to understand the code. Here is my take on small things that one could do to make their code better. Some of these are instant fixes while some might take some time to implement. Some are more of a habit while others are one-time jobs that can be performed before you work on someone else’s code.
Readability
Good code is effortlessly readable. You need to keep track of your code’s cyclomatic complexity in order to maintain readability. Don’t write a code where every other line can change the execution path. Try to end your decision making statements as early as possible.
For instance, look at the following code sample:
$level = $_POST['level']; if ($level > 2){ echo 'You are an admin'; doAdminStuff(); } else { echo 'You do not have permission to access this page'; }
This code could be rewritten for better readability by changing how you test conditions:
$level = $_POST['level']; if ($level <= 2){ echo 'You do not have permission to access this page'; exit; } echo 'You are an admin'; doAdminStuff();
This is a simple piece of code, but if I had a penny every time…you know the drill.
Murphy’s law prevails. Always remember that bugs stay hidden in complex code to show their colors at the worst possible time. If you write complex methods that require others to jump up and down trying to dry run the code, you will have a hell of a time explaining your code to the next person if you score a promotion. Even you yourself won’t want to touch a complex piece of code you wrote yourself.
This is where you get the inspiration to say “oh, we should not touch that code”. Saying that is totally unacceptable as a software development practice. Person who says this is too lazy to be working on that code in the first place. Think of a doctor refusing to treat a wound because it looks messy. Alternatively, think of the serial killer.
Part of readability is indenting your code. Using a good IDE takes care of this problem, but sometimes you might have to click a button or press a shortcut to auto-format your code. If your IDE is decent, please use the auto formatting that comes with it. If you are working in a team and collaborate using git, mercurial or subversion, it will make sure you don’t see false changes only due to formatting. Before experienced “gitters” email me with the option that allows you to ignore formatting changes, let me tell you formatting is still a better way to go.
Make sure you use those curly braces the same way (either in a separate line or at the end of the line before where the block starts) everywhere. Again, use what your IDE suggests as that will help you with consistency of your formatting.
Code with consistency
Programmers tend to like a particular way of writing code. Unfortunately, not all programmers use the “standard” standards while typing code out. I am not against any standard, be it PEAR Coding Standards or GNU Coding Standards by RS or anything else. Make sure you are consistent with your code.
You may like camel case (myFunction) or snake case (myfunction), but it is necessary to be consistent with your choice. Good naming with consistency makes it easy to understand and manage code. For instance, constants should always be all uppercase (SITE_PATH) etc.
Make your code secure
Security is not optional. Write code with security in mind. Keep yourself updated with latest hacks your counterparts on the dark side are advancing themselves to and secure your code against those tricks.
At the very least you should be doing the following consistently:
- Use prepared statements
- Filter input to avoid injection
- Validate input (it has more benefits than just security)
- Escape output
- Regenerate session when changing permission levels
- Use CSRF tokens on forms
You can conduct periodic penetration testing of your code to ensure that it doesn’t have any vulnerabilities that can lead to any security issues.
note: above suggestions are specific to PHP but most of them apply to a larger class of languages.
Keep your code organized
Your code must be organized. Even a readable code could become a nightmare if it is not organized properly. Think of how readable a stylesheet is, but if it continues to grow as a single file you need Morgan Freeman himself to organize it.
If you are using a framework (such as MVC) to write your code, respect the organization of the framework. If not using a framework make sure you are not adding files in the same folder for every new thing. There is no reason for your config file to sit next to your business logic.
Separation of concerns
You should decouple your code into as many files as you can without having meaningless partitions. Don’t mix different languages such as HTML in PHP, CSS in HTML/PHP etc. Don’t use jQuery to print a Javascript tag or setting up a CSS variable inside a PHP code file.
Divide your code into separate files such that PHP files don’t have excessive HTML and vice versa. Use templates for presentation of information and that is where most of your HTML belongs. Use PHP for your business logic and use no more than presentation decorator HTML in there. Keep javascript in separate files that can be included where needed.
Common sense for efficient code
I understand if you can’t implement the most efficient algorithm for every logical step of your application, but never turn a blind eye to common efficiency considerations.
Most common efficiency issues are in loop statements that use SQL queries inside.
<?php $stmt = $db->prepare("SELECT user_id FROM USERS where country = ?"); $stmt->bind_param('s', $_GET['country']); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($user_id); while ($stmt->fetch()) { $match = $db->prepare("SELECT * FROM MATCH where user_id = ?"); $match->bind_param('i', $user_id); $match->execute(); $match->store_result(); $match->->bind_result($match_id, $match_name); if($match->fetch()){ echo '$match_id - $match_name'; } } ?>
In the loop above, an SQL statement will be executed for every user in the USERS table from a given country.
Following is a better way to accomplish the same thing without excessive SQL execution
<?php $stmt = $db->prepare("SELECT match_id, match_name FROM USERS, MATCH where USERS.user_id = MATCH.user_id and country = ?"); $stmt->bind_param('s', $_GET['country']); $stmt->execute(); $stmt->store_result(); $stmt->->bind_result($match_id, $match_name); while ($stmt->fetch()) { echo '$match_id - $match_name'; } ?>
See how the new code requires way less resources than the previous ones. If you were running this code on a website with large number of users this will save a lot of expenses including your power bill. This will also have lower carbon footprints. Go Green Nerds!
Comment properly
It is a good practice to comment your code. Code without comment has a short lifespan. However, don’t waste your time commenting obvious things. Comments are only necessary when your code is complex. If you write simple clean statements inside a simple function or method, you will be fine commenting above the entire function to explain what that function does.
If the code is getting complex, make sure you comment for the block of code to explain what it does. If the statements are too complex to understand, write a simpler version of those statements.
Always comment if you are doing something tricky. Wait, don’t do anything tricky. Tricks are shortcuts taken by programmers to avoid a lengthy code. These shortcuts will make your code’s life short.
Clean up obsolete code
This should be part of organizing your code, but I believe it deserves a section on its own. As we move through iterations of a project, there are always code snippets that are no longer needed. Make sure you remove these as soon as you are sure they are not needed. Trust me you will not need the old ones.
This code is sometimes commented out in sections of newer code or left in functions that never get called.
No error left behind
I can’t highlight the benefit of Try-Catch statements enough. Even if you know a statement cannot produce error inside certain function, if it demands Try-Catch statements in some scenarios, use Try-Catch in all scenarios.
For instance, you may think that a SELECT query does not need error handling while an INSERT query does. This is wrong. You don’t know what external factor can change the state of your database server. Therefore, always catch all possible exceptions and log them properly so that you can monitor your code’s behavior and fix any bugs that might have still hide in there.
WET code
When I first heard that term, I thought it was opposite of dry-run. It isn’t. WET is an acronym for “write everything twice”. WET code is one of the largest maintenance problems.
If you see the same code being repeated with little to no change, rest assured you are looking at a lazy/ignorant programmer’s code.A good programmer goes that extra mile to identify the consistencies between duplicated things and to extract them into reusable methods or classes.
These are my suggestions that can improve one’s code. Even I make some of these mistakes at times, but I am trying to improve. If you have your own tips for fellow nerds and geeks do leave them in comments below.
Image courtesy: Tim Regan