Skip to content

Coding Standard – 1.0

May 18, 2016

Throughout my career life as embedded software/firmware engineer, I always study and ‘blend’ my changes by following existing style. Along the way I pick up way of coding that has become part of a norm. Maybe it has become too common that I think everyone would practise the same, and apparently I am wrong on this. I have come across come code that is seems should not be written by any engineer. This encourage me to write on this article, listing down coding method. Hopefully someone will find it useful and avoiding the same pitfall in future.

Never Use Magic Number

All the number should be declare by defining a symbol, and use the symbol in the source code. It is prohibited to use number in the source code directly.

Example: Replace the following

for(i=0;i<5;i++)

with

#define NUM_ITEMS    (5)
for(i=0;i<NUM_ITEMS;i++)

The rasionale behind this is for future code maintenance. E.g. increasing the items from 5 to 6 just require a line change. While for the first code, engineer have to search all the source code and change each of it from 5 to 6.

One Define At Single Place

For one project, when defining a symbol, always ensure there is only a single define located at a single file. Never, never define the same symbol in multiple files.

Example: File A

#define NUM_ITEMS    (5)

File B, same define again

#define NUM_ITEMS    (5)

Instead, create a project scope header file, e.g. global_define.h, and put the NUM_ITEMS define in it.

File A, File B, just include the header file

#include "global_define.h"

Do Not Create Multiple Define That Represent Same Meaning

Defining the same item with different name is a bad practise. Example, defining a size of buffer:

#define MAX_BUFFER_SIZE       (10)
#define MAX_BUFF_SIZE         (10)
#define MAX_CAR               (10) //buffer is use to represent car

Abusing define in such a way will create un-maintainable source code. It would be a nightmare to make changes of these code, like increasing the buffer size from 10 to 11.

Lastly…

The key points is always writing maintainable code. Always ask yourself what if in future things need expands, is my code good enough to cater that?

Advertisements
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: