PHP篇
7.适当的时候使用三元操作
If…else语句是大多数语言的重要组成部分。但有些简单的事情,比如根据条件进行赋值,你很有可能会这样写:
- if ($greeting)
- {
- $post->message = ‘Hello’;
- }
- else
- {
- $post->message = ‘Goodbye’;
- }
其实使用三元操作只需一行代码就可以搞定,并保持了良好的可读性:
- $post->message = $greeting ? ‘Hello’ : ‘Goodbye’;
8.抛出异常,而不是采用盗梦空间式的嵌套(Inception-Style Nesting)
多层次的嵌套是丑陋的、难以维护和不可读的。下面的代码是个简单的例子,但是随着时间的推移会变得更糟:
- // anti-pattern
- $error_message = null;
- if ($this->form_validation->run())
- {
- if ($this->upload->do_upload())
- {
- $image = $this->upload->get_info();
- if ( ! $this->image->create_thumbnail($image[‘file_name’], 300, 150))
- {
- $error_message = ‘There was an error creating the thumbnail.’;
- }
- }
- else
- {
- $error_message = ‘There was an error uploading the image.’;
- }
- }
- else
- {
- $error_message = $this->form_validation->error_string();
- }
- // Show error messages
- if ($error_message !== null)
- {
- $this->load->view(‘form’, array(
- ‘error’ => $error_message,
- ));
- }
- // Save the page
- else
- {
- $some_data[‘image’] = $image[‘file_name’];
- $this->some_model->save($some_data);
- }
如此凌乱的代码,是否该整理下呢。建议大家使用异常这个清洁剂:
- try
- {
- if ( ! $this->form_validation->run())
- {
- throw new Exception($this->form_validation->error_string());
- }
- if ( ! $this->upload->do_upload())
- {
- throw new Exception(‘There was an error uploading the image.’);
- }
- $image = $this->upload->get_info();
- if ( ! $this->image->create_thumbnail($image[‘file_name’], 300, 150))
- {
- throw new Exception(‘There was an error creating the thumbnail.’);
- }
- }
- // Show error messages
- catch (Exception $e)
- {
- $this->load->view(‘form’, array(
- ‘error’ => $e->getMessage(),
- ));
- // Stop method execution with return, or use exit
- return;
- }
- // Got this far, must not have any trouble
- $some_data[‘image’] = $image[‘file_name’];
- $this->some_model->save($some_data);
虽然代码行数并未改变,但它拥有更好的可维护性和可读性。尽量保持代码简单。
9.False——Happy方法
Ruby或Python开发者常常关注一些微小的异常,这是相当不错的事情。如果有地方出错就会抛出异常并且你会立即知道问题所在。
在PHP中,特别是使用比较老的框架,如CodeIgniter,与抛出异常相比,它仅仅返回一个flase值,并且把错误字符串分配给其他一些属性。这就驱使你使用get_error()方法。
Exception-happy远远好于false-happy。如果代码里面存在错误(例如不能连上S3下载图片,或者值为空等),然后抛出一个异常,你也可以通过继承Exception类来抛出特定的异常类型,例如:
- class CustomException extends Exception {}
抛出自定义类型异常会让调试变得更加容易。
10.Use Guard Clauses
使用if语句控制函数或方法的执行路径是很常见的事情,如果if条件为true就执行if里面的代码,否则就执行else里面的代码。例如下面这段代码:
- function someFunction($param) {
- if ($param == ‘OK’) {
- $this->doSomething();
- return true;
- } else {
- return false;
- }
- }
这是很常见的意大利面条式的代码,通过转换条件对上述代码进行优化,不仅可以增加其可读性,看起来还会更加简单,如下:
- function someFunction($param) {
- if ($param != ‘OK’) return false;
- $this->doSomething();
- return true;
- }
11.使用While进行简单的迭代
使用for进行循环是很常见的事情:
- for (var i = 0; i < x; i++) {
- …
- }
当然,for循环也有许多优势,但是对于一些的循环,使用while或许会更好:
- var i = x;
- while (i–) {
- …
- }
12.保持方法可维护性
让我们来看一下这个方法:
- class SomeClass {
- function monsterMethod() {
- if($weArePilots) {
- $this->goAndDressUp();
- $this->washYourTeeth();
- $this->cleanYourWeapon();
- $this->takeYourHelmet();
- if($this->helmetDoesNotFit())
- $this->takeAHat();
- else
- $this->installHelmet();
- $this->chekcYourKnife();
- if($this->myAirplain() == “F22”)
- $this->goToArmyAirport();
- else
- $this->goToCivilianAirport();
- $this->aim();
- $this->prepare();
- $this->fire();
- }
- }
- }
再看如下代码:
- class SomeClass {
- function monsterMethod() {
- if($weArePilots) {
- $this->prepareYourself();
- $this->tryHelmet();
- $this->findYourAirport();
- $this->fightEnemy();
- }
- }
- private function prepareYourself() {
- $this->goAndDressUp();
- $this->washYourTeeth();
- $this->cleanYourWeapon();
- $this->chekcYourKnife();
- }
- private function tryHelmet() {
- $this->takeYourHelmet();
- if($this->helmetDoesNotFit())
- $this->takeAHat();
- else
- $this->installHelmet();
- }
- private function findYourAirport() {
- if($this->myAirplain() == “F22”)
- $this->goToArmyAirport();
- else
- $this->goToCivilianAirport();
- }
- private function fightEnemy() {
- $this->aim();
- $this->prepare();
- $this->fire();
- }
- }
对比两段代码,第二段代码更加简洁、可读和可维护。
本文共10061个字 创建时间:2015年8月27日23:31