是時候和else關(guān)鍵字說再見了……
本文轉(zhuǎn)載自公眾號“讀芯術(shù)”(ID:AI_Discovery)
沒有程序員不知道else關(guān)鍵字,If-else幾乎遍布于所有編程語言,這種簡單的條件邏輯使所有人都很容易理解。
但優(yōu)秀程序員的標(biāo)志是,不使用這個關(guān)鍵字。
筆者在開始編程的時候,最大錯誤之一是在編寫條件句時過度使用else關(guān)鍵字,早五年前筆者就告別else了。
原因何在呢?
想一下else是什么意思,其意為“如果滿足A就執(zhí)行這個,如果不滿足A就執(zhí)行那個”。
圖源:bevnet
如果A是二進(jìn)制,就不存在問題——因為只存在兩種情況。
但是如果A是二進(jìn)制變量的集合,或者包含著更大的變量,出現(xiàn)問題的機(jī)會就可能會出乎意料的大,且難以理解、測試和維護(hù)。
避免if/else if,只使用if語句,花時間確保if組的輸入條件是互斥的,這樣答案就不依賴于執(zhí)行順序了。
- 使用switch — case語句
- 使用多態(tài)性處理復(fù)雜的條件情況,使代碼更像狀態(tài)模式。
- 其保證了主要的執(zhí)行通道,且有著更少的特殊情況。
- 其迫使編程人員在每個函數(shù)開始時寫入處理數(shù)據(jù)所需的所有條件。
示例
例子是這樣的:一個信號燈(即信號燈對象)有著三種不同的狀態(tài),紅色、黃色和綠色,每種狀態(tài)都有著其自己的一系列規(guī)則。規(guī)則如下:
- 假設(shè)信號燈目前是紅色,則在一定延遲后,狀態(tài)由紅轉(zhuǎn)綠。
- 然后在另一個延遲之后,狀態(tài)由綠轉(zhuǎn)黃。
- 短暫延遲后,狀態(tài)由黃轉(zhuǎn)紅。
- 不斷循環(huán)
不要使用if-else關(guān)鍵字
- 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)
- }
- }
更簡單的方式
來看看不用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")
- }
- }
或者可以用一個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")
- }
- }
可以使用狀態(tài)模式刪除這些代碼中的所有if-else關(guān)鍵字
圖源:unsplash
在這里,引入了許多if-else block/switch語句來保護(hù)各種條件,這個狀態(tài)模式適合這樣的場景。它允許對象根據(jù)當(dāng)前的狀態(tài)有不同的行為,并且用戶可以定義狀態(tài)特定的行為。
在這種模式下,開始考慮信號燈的可能狀態(tài),然后相應(yīng)地隔離代碼。
- 對于狀態(tài)特定的行為,需要有單獨的對象。
- 信號燈中定義的操作將行為委托給當(dāng)前狀態(tài)的對象。
- 狀態(tài)本身觸發(fā)狀態(tài)轉(zhuǎn)換
信號燈: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));
- }
- };
輸出如下:
- 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
好代碼與糟糕代碼的區(qū)別在哪,你get到了嗎?