PHP整洁之道
Bad:
$ymdstr = $moment->format('y-m-d');
Good:
$currentDate = $moment->format('y-m-d');
Bad:
getUserInfo();
getClientData();
getCustomerRecord();
Good:
getUser();
Bad:
// What the heck is 86400 for?
addExpireAt();
Good:
// Declare them as capitalized `const` globals.
interface DateGlobal {
const SECONDS_IN_A_DAY = ;
} addExpireAt(DateGlobal::SECONDS_IN_A_DAY);
Bad:
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/';
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches[], $matches[]);
Good:
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/';
preg_match($cityZipCodeRegex, $address, $matches);
list(, $city, $zipCode) = $matchers;
saveCityZipCode($city, $zipCode);
Bad:
$l = ['Austin', 'New York', 'San Francisco'];
foreach($i=; $i<count($l); $i++) {
oStuff();
doSomeOtherStuff();
// ...
// ...
// ...
// 等等`$l` 又代表什么?
dispatch($l);
}
Good:
$locations = ['Austin', 'New York', 'San Francisco'];
foreach($i=; $i<count($locations); $i++) {
$location = $locations[$i]; doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
dispatch($location);
});
Bad:
$car = [
'carMake' => 'Honda',
'carModel' => 'Accord',
'carColor' => 'Blue',
]; function paintCar(&$car) {
$car['carColor'] = 'Red';
}
Good:
$car = [
'make' => 'Honda',
'model' => 'Accord',
'color' => 'Blue',
]; function paintCar(&$car) {
$car['color'] = 'Red';
}
Bad:
function createMicrobrewery($name = null) {
$breweryName = $name ?: 'Hipster Brew Co.';
// ...
}
Good:
function createMicrobrewery($breweryName = 'Hipster Brew Co.') {
// ...
}
Bad:
function createMenu($title, $body, $buttonText, $cancellable) {
// ...
}
Good:
class menuConfig() {
public $title;
public $body;
public $buttonText;
public $cancellable = false;
} $config = new MenuConfig();
$config->title = 'Foo';
$config->body = 'Bar';
$config->buttonText = 'Baz';
$config->cancellable = true; function createMenu(MenuConfig $config) {
// ...
}
Bad:
function emailClients($clients) {
foreach ($clients as $client) {
$clientRecord = $db->find($client);
if($clientRecord->isActive()) {
email($client);
}
}
}
Good:
function emailClients($clients) {
$activeClients = activeClients($clients);
array_walk($activeClients, 'email');
} function activeClients($clients) {
return array_filter($clients, 'isClientActive');
} function isClientActive($client) {
$clientRecord = $db->find($client);
return $clientRecord->isActive();
}
Bad:
function addToDate($date, $month) {
// ...
} $date = new \DateTime(); // It's hard to to tell from the function name what is added
addToDate($date, );
Good:
function addMonthToDate($month, $date) {
// ...
} $date = new \DateTime();
addMonthToDate(, $date);
Bad:
function parseBetterJSAlternative($code) {
$regexes = [
// ...
]; $statements = split(' ', $code);
$tokens = [];
foreach($regexes as $regex) {
foreach($statements as $statement) {
// ...
}
} $ast = [];
foreach($tokens as $token) {
// lex...
} foreach($ast as $node) {
// parse...
}
}
Good:
function tokenize($code) {
$regexes = [
// ...
]; $statements = split(' ', $code);
$tokens = [];
foreach($regexes as $regex) {
foreach($statements as $statement) {
$tokens[] = /* ... */;
});
}); return tokens;
} function lexer($tokens) {
$ast = [];
foreach($tokens as $token) {
$ast[] = /* ... */;
}); return ast;
} function parseBetterJSAlternative($code) {
$tokens = tokenize($code);
$ast = lexer($tokens);
foreach($ast as $node) {
// parse...
});
}
Bad:
function showDeveloperList($developers) {
foreach($developers as $developer) {
$expectedSalary = $developer->calculateExpectedSalary();
$experience = $developer->getExperience();
$githubLink = $developer->getGithubLink();
$data = [
$expectedSalary,
$experience,
$githubLink
]; render($data);
}
} function showManagerList($managers) {
foreach($managers as $manager) {
$expectedSalary = $manager->calculateExpectedSalary();
$experience = $manager->getExperience();
$githubLink = $manager->getGithubLink();
$data = [
$expectedSalary,
$experience,
$githubLink
]; render($data);
}
}
Good:
function showList($employees) {
foreach($employees as $employe) {
$expectedSalary = $employe->calculateExpectedSalary();
$experience = $employe->getExperience();
$githubLink = $employe->getGithubLink();
$data = [
$expectedSalary,
$experience,
$githubLink
]; render($data);
}
}
Bad:
$menuConfig = [
'title' => null,
'body' => 'Bar',
'buttonText' => null,
'cancellable' => true,
]; function createMenu(&$config) {
$config['title'] = $config['title'] ?: 'Foo';
$config['body'] = $config['body'] ?: 'Bar';
$config['buttonText'] = $config['buttonText'] ?: 'Baz';
$config['cancellable'] = $config['cancellable'] ?: true;
} createMenu($menuConfig);
Good:
$menuConfig = [
'title' => 'Order',
// User did not include 'body' key
'buttonText' => 'Send',
'cancellable' => true,
]; function createMenu(&$config) {
$config = array_merge([
'title' => 'Foo',
'body' => 'Bar',
'buttonText' => 'Baz',
'cancellable' => true,
], $config); // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
// ...
} createMenu($menuConfig);
Bad:
function createFile(name, temp = false) {
if (temp) {
touch('./temp/'.$name);
} else {
touch($name);
}
}
Good:
function createFile($name) {
touch(name);
} function createTempFile($name) {
touch('./temp/'.$name);
}
Bad:
// Global variable referenced by following function.
// If we had another function that used this name, now it'd be an array and it could break it.
$name = 'Ryan McDermott'; function splitIntoFirstAndLastName() {
$name = preg_split('/ /', $name);
} splitIntoFirstAndLastName(); var_dump($name); // ['Ryan', 'McDermott'];
Good:
$name = 'Ryan McDermott'; function splitIntoFirstAndLastName($name) {
return preg_split('/ /', $name);
} $name = 'Ryan McDermott';
$newName = splitIntoFirstAndLastName(name); var_export($name); // 'Ryan McDermott';
var_export($newName); // ['Ryan', 'McDermott'];
Bad:
function config() {
return [
'foo': 'bar',
]
};
Good:
class Configuration {
private static $instance;
private function __construct($configuration) {/* */}
public static function getInstance() {
if(self::$instance === null) {
self::$instance = new Configuration();
}
return self::$instance;
}
public function get($key) {/* */}
public function getAll() {/* */}
} $singleton = Configuration::getInstance();
Bad:
if ($fsm->state === 'fetching' && is_empty($listNode)) {
// ...
}
Good:
function shouldShowSpinner($fsm, $listNode) {
return $fsm->state === 'fetching' && is_empty(listNode);
} if (shouldShowSpinner($fsmInstance, $listNodeInstance)) {
// ...
}
Bad:
function isDOMNodeNotPresent($node) {
// ...
} if (!isDOMNodeNotPresent($node)) {
// ...
}
Good:
function isDOMNodePresent($node) {
// ...
} if (isDOMNodePresent($node)) {
// ...
}
Bad:
class Airplane {
// ...
public function getCruisingAltitude() {
switch (this.type) {
case '':
return $this->getMaxAltitude() - $this->getPassengerCount();
case 'Air Force One':
return $this->getMaxAltitude();
case 'Cessna':
return $this->getMaxAltitude() - $this->getFuelExpenditure();
}
}
}
Good:
class Airplane {
// ...
} class Boeing777 extends Airplane {
// ...
public function getCruisingAltitude() {
return $this->getMaxAltitude() - $this->getPassengerCount();
}
} class AirForceOne extends Airplane {
// ...
public function getCruisingAltitude() {
return $this->getMaxAltitude();
}
} class Cessna extends Airplane {
// ...
public function getCruisingAltitude() {
return $this->getMaxAltitude() - $this->getFuelExpenditure();
}
}
Bad:
function travelToTexas($vehicle) {
if ($vehicle instanceof Bicycle) {
$vehicle->peddle($this->currentLocation, new Location('texas'));
} else if ($vehicle instanceof Car) {
$vehicle->drive($this->currentLocation, new Location('texas'));
}
}
Good:
function travelToTexas($vehicle) {
$vehicle->move($this->currentLocation, new Location('texas'));
}
Bad:
function combine($val1, $val2) {
if (is_numeric($val1) && is_numeric(val2)) {
return val1 + val2;
} throw new \Exception('Must be of type Number');
}
Good:
function combine(int $val1, int $val2) {
return $val1 + $val2;
}
Bad:
function oldRequestModule($url) {
// ...
} function newRequestModule($url) {
// ...
} $req = new newRequestModule();
inventoryTracker('apples', $req, 'www.inventory-awesome.io');
Good:
function newRequestModule($url) {
// ...
} $req = new newRequestModule();
inventoryTracker('apples', $req, 'www.inventory-awesome.io');
PHP整洁之道的更多相关文章
- <读书笔记> 代码整洁之道
概述 1.本文档的内容主要来源于书籍<代码整洁之道>作者Robert C.Martin,属于读书笔记. 2.软件质量,不仅依赖于架构和项目管理,而且与代码质量紧密相关,本书提出一 ...
- <代码整洁之道>、<java与模式>、<head first设计模式>读书笔记集合
一.前言 几个月前的看书笔记 ...
- 免费电子书:C#代码整洁之道
(此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:<Clean Code(代码整洁之道)>是一本经典的著作,那么对于编写整洁 ...
- 2015年第11本:代码整洁之道Clean Code
前一段时间一直在看英文小说,在读到<Before I fall>这本书时,读了40%多实在看不下去了,受不了美国人啰啰嗦嗦的写作风格,还是读IT专业书吧. 从5月9日开始看<代码整洁 ...
- android开发系列之代码整洁之道
说起代码整洁之道,想必大家想到更多的是那本经典重构书籍.没错,记得当时自己读那本书的时候,一边结合项目实战,一边结合书中的讲解,确实学到了很多东西,对我自己的编码风格影响极深.随着时间的流逝,书中很多 ...
- 读<<代码整洁之道>>的感想
花去了近一周的时间浏览一下这本书.总体感觉这本书写得不错. 我发现自己以前写的代码时多么的糟糕.有很多改进之处... 同时我也发现写出优秀的代码不易.优秀的代码不仅仅易读,并且易修改,易维护,程序易维 ...
- 如何写出如散文般的代码――《代码整洁之道》读书笔记(Ch1-Ch3)
不知道有多少人像我一样,程序出现问题时添加函数添加变量解决,变量名用a,b,c等"简单"的字母来表示.不知道有多少人像我一样,看完自己的代码,心里暗骂"什么玩意儿!&qu ...
- 《代码整洁之道》(Clean Code)- 读书笔记
一.关于Bob大叔的Clean Code <代码整洁之道>主要讲述了一系列行之有效的整洁代码操作实践.软件质量,不但依赖于架构及项目管理,而且与代码质量紧密相关.这一点,无论是敏捷开发流派 ...
- Programming好文解读系列(—)——代码整洁之道
注:初入职场,作为一个程序员,要融入项目组的编程风格,渐渐地觉得系统地研究下如何写出整洁而高效的代码还是很有必要的.与在学校时写代码的情况不同,实现某个功能是不难的,需要下功夫的地方在于如何做一些防御 ...
- Docker -- 系统整洁之道 -- 1
在上文Docker – 系统整洁之道 – 0中已经对Docker是什么,安装Docker以及怎么运行一个简单的容器有了初步了解,这篇文章介绍Docker的一些命令和Docker镜像的使用及操作. 一些 ...
随机推荐
- C#反射与特性使用简介
本文是学习特性与反射的学习笔记,在介绍完特性和反射之后,会使用特性与反射实现一个简单的将DataTable转换为List的功能,水平有限,如有错误,还请大神不吝赐教. 1. 反射:什么是反射 ...
- python-IO编程,文件读写
一.文件读写 1.打开文件 函数:open(name[. mode[. buffering]]) 参数: name:必须:文件的文件名(全路径或执行文件的相对路径.)) mode:可选:对文件的读写模 ...
- 程序员50题(JS版本)(六)
程序26:给一个不多于5位的正整数.要求:一.求它是几位数,二.逆序打印出各位数字. var test=456; var arr=[]; arr[0]=test%10; arr[1]=parseInt ...
- php+ajax实现登录按钮加载loading效果
php+ajax实现登录按钮加载loading效果,一个提高用户体验,二个避免重复提交表单,ajax判断加载是否完成. 登录表单 <form onsubmit="return chec ...
- pycharm设置自动换行的方法
只对当前文件有效的操作:菜单栏->View -> Active Editor -> Use Soft Wraps: 如果想对所有文件都有效,就要在setting里面进行操作:File ...
- 爬虫之Requests&beautifulsoup
网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本.另外一些不常使用的名字还有蚂蚁.自动索引.模拟程序或者蠕 ...
- docker容器日志收集方案(方案一 filebeat+本地日志收集)
filebeat不用多说就是扫描本地磁盘日志文件,读取文件内容然后远程传输. docker容器日志默认记录方式为 json-file 就是将日志以json格式记录在磁盘上 格式如下: { " ...
- jvisualvm 连接 jstatd 远程监控 jvm 或 Visual GC提示"不受此JVM支持“
Visual GC提示"不受此JVM支持",可以使用此方法解决. 一.添加配置文件 jstatd.all.policy [root@localhost /]# cd /usr/lo ...
- VMware14虚拟机下安装Centos6.5
一.下载VMware14,CentOS6.5光盘映像文件. https://pan.baidu.com/s/1WaTBnYuNC5dLYM_Ra2bjBQ 二.安装过程 1.打开VMware虚拟机 — ...
- 【Python 17】B分R计算器1.0(数值类型)
1.案例描述 基础代谢率(BMR):我们安静状态下(通常为静卧状态)消耗的最低热量,人的其他活动都建立在这个基础上. 计算公式: BMR(男) = (13.7*体重kg)+(5.0*身高cm)-(6. ...