29 Sep 2012

Code indention: it is this simple

Codes should be sexy. They should be beautiful. One great ingredient of this is code indention. And you should do it. It makes your code neat and easy to go through. Most good editors automatically indent your code. But it is really not difficult doing it yourself. Code indention is just about identifying nested blocks within your code and spacing them from the left appropriately. This separates the block from the nesting parent.

Let's look at a markup example.

In HTML, it is obvious a code block is a container block tag. Just prefix containing elements with few spaces (I use tabs). If it contains another container tag, indent again. Repeat this for all container tags.

1
2
3
4
5
6
7
8
<footer>
  <div>
    <img src="" />
    <p>
      &amp;copy; Year
    </p>
  </div>
</footer>

If the content of the container tag is just a one-liner, no need indenting. An example is the P tag above.

1
2
3
4
5
6
<footer>
  <div>
    <img src="" />
    <p>&amp;copy; Year</p>
  </div>
</footer>

In core programming, it is simple as indenting contents of conditional statements, loops and method declarations. One easy way to spot the block is the curly brackets {}.

Here is a javascript (node) example:

1
2
3
4
5
6
7
app.post('/', function(req, res){
  var collection = new mongodb.Collection(db, 'keywords');
  collection.insert({_id: req.body.keyword}, {safe: true}, function(err, records){
    req.session.keyword = req.body.keyword;
    res.redirect('/'+encodeURIComponent(req.body.keyword));
  });
});

...and PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
if ($query['_id']) {
  $aid = $query['_id'];
  if (count($target_members))
    $members = $target_members;
  else
    $members = $this->getMembers();
    
  $q = array();
  foreach ($members as $v) {
    // ...
  }
}

Sometimes though, indenting doesn't only apply to code blocks. Since the primary idea is to make your code neat, you can use it for long-lined statements as well. An example of this is array declaration.

1
2
3
4
5
6
<?php
$query = array(
  'ts' => new MongoDate(),
  'member_id' => (int) $member_id,
  'object' => $object
);

...JSON as well

1
2
3
4
5
6
7
8
9
10
11
12
{
  "name": "prowork-notifications", 
  "fullName": "Prowork Notifications", 
  "description": "Prowork Notifications Addon for Firefox"
  "author": "Opeyemi Obembe (http://twitter.com/kehers)", 
  "homepage": "http://prowork.me/", 
  "icon": "data/icon.png",
  "icon64": "data/icon64.png",
  "license": "MPL 2.0", 
  "id": "...", 
  "version": "0.2",
}

Remember, good code is not just about writing codes that work. Making your code easy to understand and work on is important too.

My name is Opeyemi Obembe. I build things for web and mobile. You should follow me on Twitter (@kehers).