Skip to content

Coding Standard – 2.0

June 9, 2016

This is subsequent article from my previous one here.

A Switch Case Must Have A Default Case

Make it as a habit to include a default case whenever you create a switch case. This will use as a checking point in expecting the unexpected and force us to think of a recovery method. Example, do not do this:

switch(cond){
    case 0:
        case_0_action();
        break;
    case 1:
        case_1_action();
        break;
}

Do this

switch(cond){
    case 0:
        case_0_action();
        break;
    case 1:
        case_1_action();
        break;
    default:
        handle_the_unexpected();
        break;
}

While(1) Always Wrote With A Break

When we are waiting for hardware to complete UART transmission or waiting for ADC result, we usually would write in such a way:

while(1){
    if(SFR_Flag == 1)
        break;
}

Instead of writing as below, I usually avoid creating infinite loop and create an escape case as example below:

unsigned char ReadADC(unsigned char *result)
{
    unsigned char count=0;
    
    while(1){
        if(SFR_Flag == 1)
            break;
        count++;
        if(count >= MAX_WAIT)
            return 1;
    }
    //perform adc read
    return 0;
}

Type Checking: Getting Compiler To Do The Validation

When calling function, we need to passing parameter in/out. We can use a common type such at unsigned char/unsigned int to represent our parameter. But there is a better way in doing this. A typical method of passing parameter as below:

#define MAX_ACTION_KEY (2)
unsigned char Function1(unsigned char param1)
{
    if(param1 >= MAX_ACTION_KEY)
        return 1;
    return 0;
}

We can do the following instead:

typedef enum{
    RET_OK=0,
    RET_INVALID_PARAM_IN,
    RET_ERROR,
    MAX_RET_ERROR
}EnumReturnCode;

typedef enum{
    ACTION_KEY_LEFT=0,
    ACTION_KEY_RIGHT,
    MAX_ACTION_KEY
}EnumActionKey;

EnumReturnCode Function1(EnumActionKey param1)
{
    if(param1 >= MAX_ACTION_KEY)
        return RET_INVALID_PARAM_IN;
    return RET_OK;
}

The advantages of using this method:

  • compiler will perform stict type checking and report warning/error when invalid type is use. We can utilise this features to ensure we always pass the valid parameter into Function1
  • Is more elaborate to whoever reading the source code
Advertisements

From → Embedded System

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: