Statements

Contents

Simple Statements

Each line should contain only one statement.

Return Statements

A return statement should not use outer most parentheses.

Do not use:

return (n * (n + 1) / 2);

use:

return n * (n + 1) / 2;

 

Do not make return statements more complicated than they are:

Do not use:

if(booleanExpression)
{
    return true;
}
else
{
    return false;
}

Use:

return booleanExpression;

Use the conditional operator (?) if possible in return statements:

Do not use:

if(condition)
{
    return x;
}
return y;

Use:

return (condition ? x : y); This violates the first rule of no paranthesis

 

If, if-else, if else-if else Statements

if, if-else and if else-if else statements should look like this:

if(condition)
{
    statements;
}
if(condition)
{
    statements;
}
else
{
    statements;
}
if(condition)
{
    statements;
}
else if(condition)
{
    statements;
}
else
{
    statements;
}

Note: If statements should always be followed by brackets. The reason for this is that non bracket statements can easily give flow errors when the code is extended which is less likely to happen when using brackets.

// These two statements could easily cause future problems. 
if(condition) statement;
if(condition)
    statement;

For / Foreach Statements

A for statement should have the following form:

for(int i = 0; i < 5; ++i) 
{
    statements;
}

or single lined (consider using a while statement instead):

for(initialization; condition; update);

A foreach should look like:

foreach(int i in IntList) 
{
    statements;
}

Note: Same goes here as for the if statements. Single statements should also be encapsulated by brackets, to avoid future problems.

While/do-while Statements

A while statement should be written as follows:

while(condition) 
{
    statements;
}

An empty while should have the following form:

while(condition);

A do-while statement should have the following form:

do 
{
    statements;
} 
while(condition);

Switch Statements

A switch statement should be of the following form:

switch(condition) 
{
	case A:
               statements;
               break;
    case B:
               statements;
               break;
    default:
               statements;
               break;
}

Try-catch Statements

A try-catch statement should follow this form:

try 
{
    statements;
} 
catch(Exception) {} catching exception Exception is usualy bad practice. Give another example or mention it.

or

try 
{
    statements;
} 
catch(Exception e) 
{
    statements;
}

or

try 
{
    statements;
} 
catch(Exception e) 
{
    statements;
} 
finally 
{
    statements;
}