Avoid Hazards by Making Decisions Once and Only Once

Posted November 11, 2013 by Curtis Cooley

Once a decision is made in your code, using flags and decision statements to make the same decision over and over again is hazardous.

The safe way is to remove the duplication and make the decision once and only once.

An Example

I worked on a system with a very low bandwidth connection to other computers.

The low bandwidth meant we sent codes, instead of serializing command objects, so the receiving computer used a switch statement to decide which command to execute.

The data sent down also had request information. We used a second switch statement to create the correct request object for the command.

We were making the same decision twice, basically doubling the number of flow control statements. Unsafe.

At the time we didn't think of decision statements as hazards.

 
"Of course you didn't think of them as hazards. They are fundamental to programming!"
 

Making decisions is what makes computers useful, but every decision path through your system increases the chance of bugs.

One way to reduce the number of decision paths is to avoid making the same decision more than once.

In our case, a bug hit us precisely because of the duplicated decisions we were making in the code!

By educating our command objects to be able to create request objects, we fixed the bug and collapsed our two major switch statements into one.

Are If's Really Hazardous?

Over the years I have learned that too many flow control statements can be hazardous.

Every time I think I need another flow control statement, I ask myself, "is there a way to complete my task and not add another if?"

In other words, am I making a new decision or repeating another one?

Think about flow control statements
as possible hazards in your workplace.

In the previous example there were duplicate switch statements because we did not ask if the decision had already been made.

Eliminating the extra decision statements simplified the code.

If you want to write safer code pay attention to decision statements. Consider them hazardous and avoid duplicating them.

How can you make your code safer?