您的位置:首页 > 编程语言

常见的编码陷阱3

2013-02-19 09:57 288 查看
常见的编码陷阱[/b]

6.避免三元冗余
在JavaScript和PHP中,过度使用三元语句是很常见的事情:
1 //javascript
2 returnfoo.toString()!==""?true:false;
3 //php
4 return(something())?true:false;
条件判断的返回值永远只有false和true,言外之意就是你无需把true和false显示添加到三元运算中。相反,你只需简单的返回条件:
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);
虽然代码行数并未改变,但它拥有更好的可维护性和可读性。尽量保持代码简单。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编程 问题