常見的編碼陷阱4

 常見的編碼陷阱

9.False——Happy方法

RubyPython開發者常常關注一些微小的異常,這是相當不錯的事情。如果有地方出錯就會拋出異常並且你會立即知道問題所在。

PHP中,特別是使用比較老的框架,如CodeIgniter,與拋出異常相比,它僅僅返回一個flase值,並且把錯誤字符串分配給其他一些屬性。這就驅使你使用get_error()方法。

Exception-happy遠遠好於false-happy。如果代碼裏面存在錯誤(例如不能連上S3下載圖片,或者值爲空等),然後拋出一個異常,你也可以通過繼承Exception類來拋出特定的異常類型,例如:

1         classCustomExceptionextendsException{}

拋出自定義類型異常會讓調試變得更加容易。

10.Use Guard Clauses

使用if語句控制函數或方法的執行路徑是很常見的事情,如果if條件爲true就執行if裏面的代碼,否則就執行else裏面的代碼。例如下面這段代碼:

2         functionsomeFunction($param){

3         if($param=='OK'){

4         $this->doSomething();

5         returntrue;

6         }else{

7         returnfalse;

8         }

9         }

這是很常見的意大利麪條式的代碼,通過轉換條件對上述代碼進行優化,不僅可以增加其可讀性,看起來還會更加簡單,如下:

10     functionsomeFunction($param){

11     if($param!='OK')returnfalse;

12     $this->doSomething();

13     returntrue;

14     }

11.使用While進行簡單的迭代

使用for進行循環是很常見的事情:

15     for(vari=0;i<x;i++){

16     ...

17     }

當然,for循環也有許多優勢,但是對於一些的循環,使用while或許會更好:

18     vari=x;

19     while(i--){

20     ...

21     }

12.保持方法可維護性

讓我們來看一下這個方法:

22     classSomeClass{

23     functionmonsterMethod(){

24     if($weArePilots){

25     $this->goAndDressUp();

26     $this->washYourTeeth();

27     $this->cleanYourWeapon();

28     $this->takeYourHelmet();

29     if($this->helmetDoesNotFit())

30     $this->takeAHat();

31     else

32     $this->installHelmet();

33     $this->chekcYourKnife();

34     if($this->myAirplain()=="F22")

35     $this->goToArmyAirport();

36     else

37     $this->goToCivilianAirport();

38     $this->aim();

39     $this->prepare();

40     $this->fire();

41     }

42     }

43     }

再看如下代碼:

44     classSomeClass{

45     functionmonsterMethod(){

46     if($weArePilots){

47     $this->prepareYourself();

48     $this->tryHelmet();

49     $this->findYourAirport();

50     $this->fightEnemy();

51     }

52     }

53     privatefunctionprepareYourself(){

54     $this->goAndDressUp();

55     $this->washYourTeeth();

56     $this->cleanYourWeapon();

57     $this->chekcYourKnife();

58     }

59     privatefunctiontryHelmet(){

60     $this->takeYourHelmet();

61     if($this->helmetDoesNotFit())

62     $this->takeAHat();

63     else

64     $this->installHelmet();

65     }

66     privatefunctionfindYourAirport(){

67     if($this->myAirplain()=="F22")

68     $this->goToArmyAirport();

69     else

70     $this->goToCivilianAirport();

71     }

72     privatefunctionfightEnemy(){

73     $this->aim();

74     $this->prepare();

75     $this->fire();

76     }

77     }

對比兩段代碼,第二段代碼更加簡潔、可讀和可維護。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章