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|