Friday, May 14, 2010

How To Write Clean Multi-Step Code

Scenario

You have a process with some number of steps and each step must complete successfully before the next step can continue.  A scenario I've seen before in peer reviews and production code is a nested set of IF statements to determine if the next step should be processed, etc.
I've provided a simple (yet verbose example) of what this code might look like below.



Notice that we're checking each call to see if the previous call worked.  As you also may see we are duplicating essentially the same code over and over again.

A cleaner way to do this is to implement a while loop and standardize the code.  The loop will call each item in sequence and check if it should continue processing for each step.  As you can see this is a much cleaner way to implement a multi-step piece of code.

No comments:

Post a Comment