Thursday, December 12, 2013

Structuring code: setting vs. evaluating

A while back I was explaining my code to a coworker, so as to reduce our bus factor. We got into a discussion about the way I structured my code. My code tends to be more like this:

while(1){
     //read the inputs
     input1 = pin4
     input2 = pin5

     //define the mode
     if (input1) mode = CHARGE;
     else if (input2) mode = BOOST;
     else mode = STANDBY;

     //define outputs
     if (mode == CHARGE) output1 = 1;
     else output1 = 0;

     if (mode == BOOST) output2 = 1;
     else output2 = 0;
}

His code tends to be more like this:


//handle first mode
if (input 1){
     mode = CHARGE;

     output1 = 1;
     output2 = 0;
}
//handle second mode
else if (input 2){
     mode = BOOST;
     output1 = 0;
     output2 = 1;
}

The two are semantically identical, but the way you get from A to B is totally different.

In essence, mine is structured around making sure that any given variable is only set in exactly one place in the code wherever possible. Obviously there are some cases where that can't be, like the results of long strings of sequential calculations. But in general, I find that this makes my code much easier to debug. If something is wrong with the value of one particular variable, that problem can only exist in exactly one place. And if I need to insert intermediate flags between one variable and another, it's much easier if there's only one place to do that.

I'm not sure how I got to this point. I didn't used to program this way. I think I learned it from lots of VHDL pain, back in the day. I wonder if there are names for these two approaches to structuring one's program. I'd be interested in reading more about the subject.

No comments:

Post a Comment