Monday, May 19, 2014

Mistake proofing in C programs

The Japanese concept of ‘poka-yoke’ talks about preventing mistakes by introducing certain mechanisms. It was originally designed for machinery which can be applied for any other aspect of life as well. What about mistake proofing in programming, especially with C programs? 

The earlier we get to know about mistakes in programs it is easier to fix them.

Let us consider the following code snippet (Fig 1): 

Fig 1: Simple if condition to check against MAX_VALUE
It is a simple conditional code where integer variable value is compared against absolute value MAX_VALUE and prints appropriate messages. While this appears to be a very simple program many times during development the equal-to operator (‘==’) is mistakenly replaced with assignment (‘=’) operator, which will yield unfavorable results (Fig 2): 


Fig 2: Small mistake giving incorrect results 
In this case message under if condition always will get printed irrespective of value of variable value.

Now how do we prevent this mistake? Very simple, change the way the equal-to operator is used (Fig 3). 



Fig 3: Mistake proofing during compile time
That way if assignment operator is used against an absolute lvalue, appropriate error message is given during compilation phase itself (Fig 4):


Fig 4: Error getting detected in compile time itself
By making such small changes in the code and making it as a programming practice, developers can avoid mistakes during programming which can be called as ‘poka yoke’. There could be many such examples that can be adopted for writing error free programs by getting issues earlier phase of development.

What other mistake proofing mechanisms you can think of? What other facilities that C offers for developers to operate in prevention mode? 

No comments:

Post a Comment