Sunday, 15 June 2014

Indentations and Alignments

Hi Everyone,

Here is a habit that I picked up since Monash University about 10 years ago in order to enable easier code reading.

This applies to most programming languages including C#, Javascript, VBScript and SQL.

I am talking about indentations and the position of the braces, {}. Usually the standard would look like this:

function x(){
    //todo
}


function b()
if (condition) then
//todo
end if

for i = 0 to 5
if (condition) then
    //todo
end if  
next
end function

It is harder to read if there are no indentations or if the braces are not alinged properly. 

Instead of that, we can actually do:

function x()
{
    //todo
}


If we have a longer code like this, it is better with indentations as shown below:

function x()
{
    //todo
    if (condition)
    {
        switch (anotherCondition)
        {
            case a:
                //todo
                break;
            case b:
                //todo
                break;
            default:
                //todo
                break;
        ]
    }
    else
    {
        switch (condition)
        {
            case d:
                //todo
                break;
            case e:
                //todo
                break;
            default:
                //todo
                break;
        }
    }
}


Here's another example for VBScript:

 function b()
    if (condition) then
        //todo
    end if
  
    for i = 0 to 5
        if (condition) then
            //todo
        end if
    next
end function


and HTML 


    


    
        
            
        
      
        
            Label
        
    
  
    
        
        
    

As a conclusion, codes with indentation and braces aligned properly are neater and easier to see and analysed. It allows other programmers to know what the code is doing and where the code block ends precisely.

That's all,

Rogerkoo