是时候和else关键字说再见了……

开发 后端
没有程序员不知道else关键字,If-else几乎遍布于所有编程语言,这种简单的条件逻辑使所有人都很容易理解。但优秀程序员的标志是,不使用这个关键字。

本文转载自公众号“读芯术”(ID:AI_Discovery)

没有程序员不知道else关键字,If-else几乎遍布于所有编程语言,这种简单的条件逻辑使所有人都很容易理解。

[[321176]]

但优秀程序员的标志是,不使用这个关键字。

笔者在开始编程的时候,最大错误之一是在编写条件句时过度使用else关键字,早五年前笔者就告别else了。

原因何在呢?

想一下else是什么意思,其意为“如果满足A就执行这个,如果不满足A就执行那个”。

是时候和else关键字说再见了……

图源:bevnet

如果A是二进制,就不存在问题——因为只存在两种情况。

但是如果A是二进制变量的集合,或者包含着更大的变量,出现问题的机会就可能会出乎意料的大,且难以理解、测试和维护。

避免if/else if,只使用if语句,花时间确保if组的输入条件是互斥的,这样答案就不依赖于执行顺序了。

  • 使用switch — case语句
  • 使用多态性处理复杂的条件情况,使代码更像状态模式。
  • 其保证了主要的执行通道,且有着更少的特殊情况。
  • 其迫使编程人员在每个函数开始时写入处理数据所需的所有条件。

示例

例子是这样的:一个信号灯(即信号灯对象)有着三种不同的状态,红色、黄色和绿色,每种状态都有着其自己的一系列规则。规则如下:

  • 假设信号灯目前是红色,则在一定延迟后,状态由红转绿。
  • 然后在另一个延迟之后,状态由绿转黄。
  • 短暂延迟后,状态由黄转红。
  • 不断循环

不要使用if-else关键字

constLightState= { 
           GREEN: 0, 
           YELLOW: 1, 
           RED: 2 
         } 
                      varTrafficLight=function () { 
                        var count =0  
                        // default state = red 
           var currentState =0
                       this.change=function(state) { 
             if (count++ >= 10 ) return 
             currentState = state 
             this.go(currentState) 
           } 
           this.go=function(state) { 
             if (currentState ==LightState.GREEN) { 
               console.log("Green -->for 1 minute") 
               this.change(LightState.YELLOW) 
             } 
             elseif (currentState ==LightState.YELLOW) { 
               console.log("Yellow -->for 10 seconds") 
               this.change(LightState.RED) 
             } elseif (currentState ==LightState.RED) { 
               console.log("Red -->for 1 minute"); 
               this.change(LightState.GREEN) 
             } else { 
               throwError("Invalid State") 
             } 
           } 
           this.start=function() { 
             this.change(LightState.GREEN) 
           } 
         } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.

更简单的方式

来看看不用else该怎么做:

this.go=function (state) { 
            if (currentState ==LightState.GREEN) { 
              console.log("Green -->for 1 minute") 
              this.change(LightState.YELLOW) 
            } 
            if (currentState ==LightState.YELLOW) { 
              console.log("Yellow -->for 10 seconds") 
              this.change(LightState.RED) 
            } 
            if (currentState ==LightState.RED) { 
              console.log("Red -->for 1 minute"); 
              this.change(LightState.GREEN) 
            } 
            if (currentState != LightState.GREEN&& currentState != LightState.RED&& currentState != LightState.YELLOW) { 
              throwError("Invalid State") 
            } 
        } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

或者可以用一个switch代替,不得不合并不同的场景时,它看起来干净得多,而if-else很快就会失控。

若干场景良好的情况下,switch 语句可能会比if-else语句更快。

this.go=function (state) { 
            if (currentState ==LightState.GREEN) { 
              console.log("Green -->for 1 minute") 
              this.change(LightState.YELLOW) 
            } 
            if (currentState ==LightState.YELLOW) { 
              console.log("Yellow -->for 10 seconds") 
              this.change(LightState.RED) 
            } 
            if (currentState ==LightState.RED) { 
              console.log("Red -->for 1 minute"); 
              this.change(LightState.GREEN) 
            } 
            if (currentState != LightState.GREEN&& currentState != LightState.RED&& currentState != LightState.YELLOW) { 
              throwError("Invalid State") 
            } 
        } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

可以使用状态模式删除这些代码中的所有if-else关键字

[[321178]]

图源:unsplash

在这里,引入了许多if-else block/switch语句来保护各种条件,这个状态模式适合这样的场景。它允许对象根据当前的状态有不同的行为,并且用户可以定义状态特定的行为。

在这种模式下,开始考虑信号灯的可能状态,然后相应地隔离代码。

  • 对于状态特定的行为,需要有单独的对象。
  • 信号灯中定义的操作将行为委托给当前状态的对象。
  • 状态本身触发状态转换

信号灯:Green(1 minute) → Yellow (10 seconds)→ Red (1 minute)

varTrafficLight=function () { 
                             var count =0 
                             // default state =green 
               var currentState =newGreen(this);  
                             this.change=function (state) { 
                   // limits number of changes 
                   if (count++ >= 10) return; 
                   currentState = state
                   currentState.go(); 
               } 
               this.start=function () { 
                   currentState.go(); 
               } 
           }  
                          varRed=function (light) { 
               this.light= light 
                             this.go=function () { 
                   console.log(("Red -->for 1 minute")) 
                   light.change(newGreen(light)); 
               } 
           }  
                          varYellow=function (light) { 
               this.light= light; 
             
               this.go=function () { 
                   console.log("Yellow -->for 10 seconds") 
                   light.change(newRed(light)); 
               } 
           }; 
                             varGreen=function (light) { 
               this.light= light; 
             
               this.go=function () { 
                   console.log("Green -->for 1 minute"); 
                   light.change(newYellow(light)); 
               } 
           }; 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.

输出如下:

Green → for 1 minute 
Yellow → for 10 seconds 
Red → for 1 minute 
Green → for 1 minute 
Yellow → for 10 seconds 
Red → for 1 minute 
Green → for 1 minute 
Yellow → for 10 seconds 
Red → for 1 minute 
Green → for 1 minute 
Yellow → for 10 seconds 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

好代码与糟糕代码的区别在哪,你get到了吗?

责任编辑:赵宁宁 来源: 读芯术
相关推荐

2023-02-26 00:17:45

2020-07-13 20:26:30

手机64G手机APP

2025-02-19 08:27:56

2013-12-20 09:59:34

小米闪购模式雷军

2024-11-08 14:00:29

关键字Animal编程

2021-07-21 07:11:21

TeamviewerWindowsMac

2019-10-10 10:30:26

MVCModelController

2013-03-19 11:28:01

Windows 7 R

2021-01-12 09:22:18

Synchronize线程开发技术

2013-08-13 14:22:33

开发者微软Windows Pho

2019-05-09 10:48:46

无人驾驶人工智能配送机器人

2014-07-14 11:47:03

火狐浏览器

2015-10-10 11:08:36

控制面板Windows 10微软

2009-08-01 08:46:47

2013-01-30 10:12:14

Pythonyield

2009-08-21 14:58:56

C# this关键字

2018-04-20 15:56:09

Pythonglobal关键字

2012-03-01 12:50:03

Java

2009-09-17 09:30:00

Linq LET关键字

2009-09-02 09:24:03

C# this关键字
点赞
收藏

51CTO技术栈公众号