Coding style 这两种构造代码的方法有名字吗?

Coding style 这两种构造代码的方法有名字吗?,coding-style,structure,Coding Style,Structure,我用C语言为嵌入式系统做了很多编程工作。不久前,我向一位同事解释我的代码,以减少我们的总线因素。我们讨论了我构建代码的方式。我的代码更倾向于这样: while(1){ //read the inputs input1 = pin4 input2 = pin5 //define the mode if (input1) mode = CHARGE; else if (input2) mode = BOOST; else mod

我用C语言为嵌入式系统做了很多编程工作。不久前,我向一位同事解释我的代码,以减少我们的总线因素。我们讨论了我构建代码的方式。我的代码更倾向于这样:

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;
}
while(1){
    //handle first mode
    if (input1){
         mode = CHARGE;
         output1 = 1;
         output2 = 0;
    }

    //handle second mode
    else if (input2){
         mode = BOOST;
         output1 = 0;
         output2 = 1;
    }
}
他的代码更倾向于这样:

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;
}
while(1){
    //handle first mode
    if (input1){
         mode = CHARGE;
         output1 = 1;
         output2 = 0;
    }

    //handle second mode
    else if (input2){
         mode = BOOST;
         output1 = 0;
         output2 = 1;
    }
}
这两者在语义上是相同的,但是从A到B的方式是完全不同的

本质上,我的结构是确保在可能的情况下,任何给定变量只在代码中的一个位置设置。显然,在某些情况下这是不可能的,比如长串连续计算的结果。但总的来说,我发现这使我的代码更容易调试。如果某个特定变量的值有问题,则该问题只能存在于一个地方。如果我发现我需要在一个变量和另一个变量之间插入中间标志,如果只有一个地方可以这样做,那就容易多了

(我不知道我是怎么做到这一点的。我以前不习惯用这种方式编程。我想我是从当时的许多VHDL痛苦中学会的。)


我想知道,这两种构造代码的方法有没有名字?进一步阅读它们的优点和缺点会很有趣。

除了编码风格(可能还有其他含义)之外,我想不出一个特定的名称/定义

我必须说我更喜欢阅读代码的第二个版本

我理解您为什么说版本1更容易调试,但随着项目的发展,您可能更喜欢更容易理解它的功能,而不是在遇到问题时更容易调试的功能,因为您没有理解它…:)