常見的編碼陷阱3

 常見的編碼陷阱

6.避免三元冗餘

JavaScriptPHP中,過度使用三元語句是很常見的事情:

1         //javascript

2         returnfoo.toString()!==""?true:false;

3         //php

4         return(something())?true:false;

條件判斷的返回值永遠只有falsetrue,言外之意就是你無需把truefalse顯示添加到三元運算中。相反,你只需簡單的返回條件:

5         //javascript

6         returnfoo.toString()!=="";

7         //php

8         returnsomething();

PHP

7.適當的時候使用三元操作

If...else語句是大多數語言的重要組成部分。但有些簡單的事情,比如根據條件進行賦值,你很有可能會這樣寫:

9         if($greeting)

10     {

11     $post->message='Hello';

12     }

13     else

14     {

15     $post->message='Goodbye';

16     }

其實使用三元操作只需一行代碼就可以搞定,並保持了良好的可讀性:

17     $post->message=$greeting?'Hello':'Goodbye';

8.拋出異常,而不是採用盜夢空間式的嵌套(Inception-Style Nesting

多層次的嵌套是醜陋的、難以維護和不可讀的。下面的代碼是個簡單的例子,但是隨着時間的推移會變得更糟:

18     //anti-pattern

19     $error_message=null;

20     if($this->form_validation->run())

21     {

22     if($this->upload->do_upload())

23     {

24     $image=$this->upload->get_info();

25     if(!$this->image->create_thumbnail($image['file_name'],300,150))

26     {

27     $error_message='Therewasanerrorcreatingthethumbnail.';

28     }

29     }

30     else

31     {

32     $error_message='Therewasanerroruploadingtheimage.';

33     }

34     }

35     else

36     {

37     $error_message=$this->form_validation->error_string();

38     }

39     //Showerrormessages

40     if($error_message!==null)

41     {

42     $this->load->view('form',array(

43     'error'=>$error_message,

44     ));

45     }

46     //Savethepage

47     else

48     {

49     $some_data['image']=$image['file_name'];

50     $this->some_model->save($some_data);

51     }

如此凌亂的代碼,是否該整理下呢。建議大家使用異常這個清潔劑:

52     try

53     {

54     if(!$this->form_validation->run())

55     {

56     thrownewException($this->form_validation->error_string());

57     }

58     if(!$this->upload->do_upload())

59     {

60     thrownewException('Therewasanerroruploadingtheimage.');

61     }

62     $image=$this->upload->get_info();

63     if(!$this->image->create_thumbnail($image['file_name'],300,150))

64     {

65     thrownewException('Therewasanerrorcreatingthethumbnail.');

66     }

67     }

68     //Showerrormessages

69     catch(Exception$e)

70     {

71     $this->load->view('form',array(

72     'error'=>$e->getMessage(),

73     ));

74     //Stopmethodexecutionwithreturn,oruseexit

75     return;

76     }

77     //Gotthisfar,mustnothaveanytrouble

78     $some_data['image']=$image['file_name'];

79     $this->some_model->save($some_data);

雖然代碼行數並未改變,但它擁有更好的可維護性和可讀性。儘量保持代碼簡單。

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