2014年4月4日 星期五

[CleanCode]Adjust your if-else//整頓你的if-else

判斷流程複雜時, 我們會需要很多層if-else在程式裡, 最後很容易變成如下又肥又醜的模樣:
We need  many if-else struct when the flow is complicated, then the struct of program will become big and ugly, as below:

 if(A)

{
      do A-1...
      if(B)
      {
            do B-1...

            if(C)
            {
                  do C-1...
            }else{
                  do C-2...
                  return...
            }
      }else{
            do B-2...

            return...
      }
}else{
      do A-2...

      return...
}


真是讓人看得眼花撩亂, 不是嗎?
These make us dazzle, isn't it?

其實我們可以換種寫法:
Actually, we can change a way:

if(!A)

{
      do A-2...

      return...
}

do A-1...

if(!B)
{
      do B-2...

      return....
}

do B-1...

if(!C)
{
      do C-2...

      return...
}

do C-1...


程式運作的邏輯一樣, 但看起來是不是好讀多了呢?
The logic program operating is same, but it become much good to read.

這種技巧是把做完可以直接return的判斷式獨立出來; 利用"return後下方的程式碼不會執行"的特性, 使程式的結構脫離if-else必須一層包一層的窘境
This way is separating the statement which process return when operating done; the code struct can be breaking away the dilemma of if-else layer packet layer, by using the feature of "program will not execute the codes after return".

如此, 我們可以在看多層判斷式時不必再辛苦的對照程式碼在哪一層判斷式 , 大大增加了程式的可讀性
So we don't need to look for codes in the multi-layer predicate, it increases the program's readability.

=======================
希望這對你有幫助,歡迎提供建議
Hope this help you, welcome to advice me.