When people think of writing code, they often just think of it as writing instructions to perform a certain function. Little care is often given to how the code is presented. You may ask, what’s the point? What’s the difference? After all, the code still runs right? You couldn’t be more wrong…
People who take pride in their work, would love to show it to others. If you cannot even take the slightest effort to make your code presentable to others, it shows that you do not take pride in your work. However, sometimes it is not the coder’s fault. They just don’t know how to write their code properly. Well, it is time to learn :)
Variable/Function/Class/etc Naming
Descriptive Names
This is by far the most important aspect of writing code. The name should always be able to describe its purpose. Just by reading, a person would know what the variable is for or what the function will do. For example:
Bad:
$var1 = 'Hawk';
$var2 = '[email protected]';
$var3 = 'Web Developer';
v( $var2 );Good:
$name = 'Hawk';
$email = '[email protected]';
$position = 'Web Developer';
validate_email( $email );Better:
$staff_name = 'Hawk';
$staff_email = '[email protected]';
$staff_position = 'Web Developer';
validate_email( $staff_email );The 3rd example is better because the variable more accurately describes its value. While $name is sufficient in most cases, it can be confusing. Does the e-mail address belong to the staff or the client? Be as descriptive as you can while being concise. Try to keep the names below 32 characters.
Naming Style
If you noticed, in my examples i used an underscore to seperate the words. This is purely personal preference, i just find it easier for me to read. You may choose to use another common method like staffName, staffEmail, staffPosition, validateEmail(). You will normally see this used in most Microsoft based applications.
Also, try not to abbreviate too much. If you have to shorten the names, use well-known abbreviations like number being shortened to no. or num.
Code layout
1 instruction per line
We have plenty of lines to use, it is not in short supply. So use them to aid readability.
Bad:
$staff_name = 'Hawk'; $staff_email = '[email protected]';
$staff_position = 'Web Developer'; validate_email( $staff_email );Good:
$staff_name = 'Hawk';
$staff_email = '[email protected]'
$staff_position = 'Web Developer';
validate_email( $staff_email );I think its pretty clear which is easier on the eyes :)
Whitespaces are your friends
How would you like it if you had to read an article that did not use any whitespaces to seperate words? For example: (Howwould youlikeitifyouhadtoreadanarticlethatdidnotuseanywhitespacestoseperatewords?). See, even one sentence is going to make your eyes bleed! Code should be treated the same way.
Bad:
$staff_name='Hawk';
$staff_email='[email protected]'
$staff_position='Web Developer';
validate_email($staff_email);Good:
$staff_name = 'Hawk';
$staff_email = '[email protected]'
$staff_position = 'Web Developer';
validate_email( $staff_email );Better:
$staff_name = 'Hawk';
$staff_email = '[email protected]'
$staff_position = 'Web Developer';
validate_email( $staff_email );Lining up the values like the 3rd example makes it alot easier to read. It may not seem like much when you have a few variables like this, but when it gets longer you’ll find out just how much easier it is. Heck, if that doesn’t persuade you… it is neat! That should be a good enough reason :p
Indentation
Open any technical book, take a look at its table of contents. You will see the main chapters and sub-chapters. The sub-chapters are always indented to clearly show that these chapters are part of main chapter. The structure of the chapter is clear, your code should also be the same. At one glance, your structure should be clear.
Bad:
while ( $condition = true )
{
dosomething();
if ( $condition = false )
{
break;
}
}Good:
while ( $condition = true )
{
dosomething();
if ( $condition = false )
{
break;
}
}See how the indentation makes things so much clearer? This doesn’t just apply to programming, when you do your HTML you should also always indent your code properly to give it a clear structure. Once again short examples may not show much benefit. I do not want to make this blog entry too long so i didn’t include larger chunks of code.
Real Example
Now that we have learnt the basics of writing readable code, lets take a look at a real example and how we can improve it to make it better. Lets take a look at a code snippet to create a JPEG thumbnail from a JPEG file if the JPEG image exceeds a certain width.
$width=425;
$quality=80;
$dimension=getimagesize($image_file);
$pic_width=$dimension[0];
$pic_height=$dimension[1];
$src=imagecreatefromjpeg($image_file);
if ($dimension[0]>$width){
$height_ratio=($pic_height/$pic_width);
$resized_width=$width;
$resized_height=$width*$height_ratio;
}else{
$resized_width=$pic_width;
$resized_height=$pic_height;
}
$resized=@imagecreatetruecolor($resized_width,$resized_height);
@imagecopyresampled($resized,$src,0,0,0,0,$resized_width, $resized_height,$pic_width,$pic_height);
imagejpeg($resized,$picture_path.$image_name,$quality);As you can see, its pretty ugly and hard to read. No whitespaces, poor variable naming and little use of new lines. Lets make this better.
$thumbnail_width = 425;
$jpeg_quality = 80;
$dimension = getimagesize($image_file);
$pic_width = $dimension[0];
$pic_height = $dimension[1];
$source = imagecreatefromjpeg($image_file);
if ( $dimension[0] > $width )
{
$height_ratio = ( $pic_height / $pic_width );
$resized_width = $thumbnail_width;
$resized_height = $thumbnail_width * $height_ratio;
}
else
{
$resized_width = $pic_width;
$resized_height = $pic_height;
}
$thumbnail = @imagecreatetruecolor( $resized_width,
$resized_height );
@imagecopyresampled( $thumbnail, $source, 0, 0, 0, 0,
$resized_width, $resized_height,
$pic_width, $pic_height );
imagejpeg( $thumbnail, $picture_path . $image_name,
$jpeg_quality);There much easier to read now isn’t it? There are many ways to make code readable, each person will have their own preference. Just make sure whatever that preference is, you stick to it. If in a team, ensure that everyone agrees to a coding standard. That way the code wouldn’t look like rojak :p. Above all, be consistent.
Since this entry is called “The art of Writing Code”, I’ll add a link to ASCII art code. The code is written and formatted to create an image and it is fully functional. Of course i do not recommend anyone to do this for serious projects, but for entertainment sake it could be fun :). See some code art!
Hehe… replying here for the first time… lol
well, the statements are actually for common cases… if your code is more concerntrated to its security, it’s naming & formatting should be misterious enough, to prevent hacking… ^^
Don’t forget to add comments in your code! ;)
Code art..?! -.-“
Not really, that is just security through obscruity. Your code itself should be strong enough that even when people see and understand it, it will be hard to break.
This is why the best encryption techniques are those that are open. It has to be reviewed by others to verify its strength.
I purposely left comments out :)
The purpose of this article is to show that your code is self documented. The code explains itself. You should only add comments to really complex code which gives the person a better understanding on what the heck you’re doing.
Comments have the tendency of being out-of-date. Your code however will always be up to date. So only write comments if you have to, otherwise leave them out.
Good article Hawk!
I’ve got something to say about comments too: Comments is cool.
If you’ve got a lot of code, like pages and pages, comment headings can help you find the section you are looking for quickly, e.g.
/* ##### Section name ##### */This serves as a visual marker so you can quickly scan your code, and not have to read it, so that you can find what you are looking for quickly.
That’s pretty useless…. in ANY editor you’ll have a find function. Use it :) If you wrote your code properly, segments should be easy to find since you named them well.
If you’re using an IDE, some have code folding so the code isn’t one big lump. If it doesn’t have that feature, IDEs will often list out functions and classes used. It would be easy to jump around.
That said, if your code is too frigging long you probably need to refactorise your code somewhere. Break it out into smaller more manageable pieces.
Comments should only be used in 2 cases.
1) To describe a complex procedure
2) To generate documentation ala phpDoc or JavaDoc
I disagree with your opinions on comments. Good comment blocks aren’t about describing procedures. It’s about explaining why a piece is being used, and what is expected to be achieved. If I read someone’s well-written code (without comments), sure I’ll be able to understand what he’s doing – but why did he use that code? Is there a more efficient way? None of these questions can be answered with good coding.
Exactly why i said only keep comments for complex code :). Much too often you’ll see comments like this:
Such comments are pretty pointless. If the code is performing a simple procedure, then it should easily describe itself.
Even for “why” that code is being used, it should only be written for good reason. Saying:
is bad since it doesn’t help us in any way. But writing:
is acceptable. This provides information which you might not have known from just seeing the code.
As for more efficient ways… only our experience can help us in that. Comments won’t do much much really.