关于编码常见的20个陷阱 你中枪了没?
作者:网络转载 发布时间:[ 2012/12/17 10:05:54 ] 推荐标签:
PHP篇
7、适当的时候使用三元操作
If...else语句是大多数语言的重要组成部分。但有些简单的事情,比如根据条件进行赋值,你很有可能会这样写:
1.if ($greeting)
2.{
3. $post->message = 'Hello';
4.}
5.else
6.{
7. $post->message = 'Goodbye';
8.}
其实使用三元操作只需一行代码可以搞定,并保持了良好的可读性:
$post->message = $greeting ? 'Hello' : 'Goodbye';
8、抛出异常,而不是采用盗梦空间式的嵌套(Inception-Style Nesting)
多层次的嵌套是丑陋的、难以维护和不可读的。下面的代码是个简单的例子,但是随着时间的推移会变得更糟:
1.// anti-pattern
2.$error_message = null;
3.if ($this->form_validation->run())
4.{
5. if ($this->upload->do_upload())
6. {
7. $image = $this->upload->get_info();
8. if ( ! $this->image->create_thumbnail($image['file_name'], 300, 150))
9. {
10. $error_message = 'There was an error creating the thumbnail.';
11. }
12. }
13. else
14. {
15. $error_message = 'There was an error uploading the image.';
16. }
17.}
18.else
19.{
20. $error_message = $this->form_validation->error_string();
21.}
22.// Show error messages
23.if ($error_message !== null)
24.{
25. $this->load->view('form', array(
26. 'error' => $error_message,
27. ));
28.}
29.// Save the page
30.else
31.{
32. $some_data['image'] = $image['file_name'];
33. $this->some_model->save($some_data);
34.}
如此凌乱的代码,是否该整理下呢。建议大家使用异常这个清洁剂:
1.try
2.{
3. if ( ! $this->form_validation->run())
4. {
5. throw new Exception($this->form_validation->error_string());
6. }
7. if ( ! $this->upload->do_upload())
8. {
9. throw new Exception('There was an error uploading the image.');
10. }
11. $image = $this->upload->get_info();
12. if ( ! $this->image->create_thumbnail($image['file_name'], 300, 150))
13. {
14. throw new Exception('There was an error creating the thumbnail.');
15. }
16.}
17.// Show error messages
18.catch (Exception $e)
19.{
20. $this->load->view('form', array(
21. 'error' => $e->getMessage(),
22. ));
23. // Stop method execution with return, or use exit
24. return;
25.}
26.// Got this far, must not have any trouble
27.$some_data['image'] = $image['file_name'];
28.$this->some_model->save($some_data);
虽然代码行数并未改变,但它拥有更好的可维护性和可读性。尽量保持代码简单。
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11