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镜像的使用及操作. 一些 ...
随机推荐
- MySQL单行函数
1.CONCAT(str1,str2,...) 返回来自于参数连结的字符串.如果任何参数是NULL,返回NULL.可以有超过2个的参数.一个数字参数被变换为等价的字符串形式. select CONC ...
- 用EF的三种方式(SqlServer数据库和Oracle数据库)
SqlServer数据库 1.DB First 现有DB,生成edmx文件 贴一下生成的model //------------------------------------------------ ...
- Vue在ASP.NET MVC中的进行前后端的交互
Vue在ASP.NET MVC中的进行前后端的交互 Preface: 由于最近在研究前端相关的技术,作为前端非常优秀的框架Vue,个人在学习的过程中遇到一些问题,网上相关资料有限,所以在这这里总结一下 ...
- [Go] go get获取官方库被墙解决
1.直接在github上clone对应的代码 , 地址为: https://github.com/golang/xxxxxxx.git xxxxxxx为所缺的库名 , 比如net库 text库 h ...
- Win10系统简单开启热点
介绍 笔记本电脑使用的都是无线网卡,我们可以通过这网卡来开启热点供手机使用,说起开热点,大家都是想到的使用360随身wifi或者是猎豹wifi来开启热点吧,我个人不太喜欢使用这些软件,原因因为有DNS ...
- nginx系列2:搭建nginx环境
我们选择编译安装nginx. 1,下载nginx 进入nginx的官网下载页面:http://nginx.org/en/download.html 找到稳定版本Stable version的下载入口开 ...
- 原生JS编写兼容IE6,7,8浏览器无缝自动轮播(带按钮切换)
项目要求页面兼容IE6,7,8等浏览器,我们可能会遇到这个轮播效果,轮播板块要求:无限循环.自动轮播和手动切换功能,每一次滚动一小格,网上有很多这类插件,例如:swiper等! 但是很多都是不兼容IE ...
- node处理表单文件,获取formdata的数据
参考文章:https://blog.csdn.net/a895458278/article/details/48055143# 应用: formidable使用: 原生的node.js在处理客户端以P ...
- arcgis api 3.x for js 入门开发系列十三地图最短路径分析(附源码下载)
前言 关于本篇功能实现用到的 api 涉及类看不懂的,请参照 esri 官网的 arcgis api 3.x for js:esri 官网 api,里面详细的介绍 arcgis api 3.x 各个类 ...
- 基础环境系列:Apache2.4.37
一.安装 进入官网http://www.apache.org/,滑至最下方,排名第一的HTTP Server就是我们需要的. 当前时间的最新版本是2.4.37.呃……并没有msi版本,我们选择最后一个 ...