关键词:
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(86400); Good: // Declare them as capitalized `const` globals. interface DateGlobal const SECONDS_IN_A_DAY = 86400; addExpireAt(DateGlobal::SECONDS_IN_A_DAY);
Bad: $address = ‘One Infinite Loop, Cupertino 95014‘; $cityZipCodeRegex = ‘/^[^,\\]+[,\\\s]+(.+?)\s*(\d5)?$/‘; preg_match($cityZipCodeRegex, $address, $matches); saveCityZipCode($matches[1], $matches[2]); Good: $address = ‘One Infinite Loop, Cupertino 95014‘; $cityZipCodeRegex = ‘/^[^,\\]+[,\\\s]+(.+?)\s*(\d5)?$/‘; preg_match($cityZipCodeRegex, $address, $matches); list(, $city, $zipCode) = $matchers; saveCityZipCode($city, $zipCode);
Bad: $l = [‘Austin‘, ‘New York‘, ‘San Francisco‘]; foreach($i=0; $i<count($l); $i++) oStuff(); doSomeOtherStuff(); // ... // ... // ... // 等等`$l` 又代表什么? dispatch($l); Good: $locations = [‘Austin‘, ‘New York‘, ‘San Francisco‘]; foreach($i=0; $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, 1); Good: function addMonthToDate($month, $date) // ... $date = new \DateTime(); addMonthToDate(1, $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 ‘777‘: 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开发-代码整洁之道(代码片段)
CleanCodePHP目录介绍变量使用见字知意的变量名同一个实体要用相同的变量名使用便于搜索的名称(part1)使用便于搜索的名称(part2)使用自解释型变量避免深层嵌套,尽早返回(part1)避免深层嵌套,尽早返回(part2)少用无意义的变量名... 查看详情
php代码整洁之道
介绍RobertC.Martin‘s的软件工程师准则CleanCode同样适用于PHP。它并不是一个编码风格指南,它指导我们用PHP写出具有可读性,可复用性且可分解的代码。并非所有的准则都必须严格遵守,甚至一些已经成为普遍的约定。这仅仅作为... 查看详情
代码整洁之道(代码片段)
有意义的命名1名副其实2避免误导3做有意义的分区废话都是冗余。Variable永远不应出现在变量名中,Table一词永远不应出现在表名中。当缺少明确约定:变量moneyAmout与money没区别,customerInfo与customer没区别,accountData与account没区别... 查看详情
代码整洁之道(代码片段)
有意义的命名1名副其实2避免误导3做有意义的分区废话都是冗余。Variable永远不应出现在变量名中,Table一词永远不应出现在表名中。当缺少明确约定:变量moneyAmout与money没区别,customerInfo与customer没区别,accountData与account没区别... 查看详情
代码整洁之道-对象和数据结构(代码片段)
现在,有一个计算面积的需求,其中一种实现如下:classSquarepublic$side;classGeometrypublicfunctionarea($shape)if($shapeinstanceofSquare)return$shape->side*$shape->side;return0; 有人看了,你这抽象的有问题啊,很明显是面向过程的,如果新加 查看详情
代码整洁之道(代码片段)
文章目录一、有意义的命名1.名副其实2.避免误导3.做有意义的区分一、有意义的命名软件中随处可见命名。我们给变量、函数、参数、类和封包命名、源代码文件命名、目录命名,良好的命名规范使得代码以及工程的维护难... 查看详情
整洁架构之道--三种经典的编程范式(代码片段)
本文是《CleanArchitecture》--整洁架构之道中关于编程范式相关章节的笔记,首发于公众号「Go招聘」这和软件架构的三大关注重点不谋而合:功能性、组件独立性以及数据管理。的方式。回答此问题的同时另外还会搬出这三个词语... 查看详情
读《cleancode代码整洁之道》之感悟(代码片段)
盲目自信,自认为已经敲了几年代码,还看什么整洁之道啊。我那可爱的书架读懂了我的心思,很明事理的保护起来这本小可爱,未曾让它与我牵手最近项目中的bug有点多,改动代码十分吃力,每看一行代码都带一句“这是什么... 查看详情
15个书写javascript代码的整洁之道(实用!)(代码片段)
...且别人能看懂吗?下面的规则可以让你的JavaScript代码更加整洁和清晰.规则1.不要使用随机的字符 查看详情
代码整洁之道(cleancode)读后感(代码片段)
第二次读代码整洁之道(CleanCode)了,在少许开发经验加持下,没有第一次那么晦涩后,整体对本书也有了共鸣,这本书应该作为指导手册,平时可以多翻一翻,说不定会有新的不同感悟,当然... 查看详情
架构整洁之道,看这一篇就够了!(代码片段)
...中就不会迷路,架构思想就是这样的知识。本文是《架构整洁之道》的读书心得,作者将书中内容拆解后再组织,不仅加入了个人的独到见解,而且用一张详细的知识脉络图帮助大家了解整本书的精华。如果你读过这本书,可以... 查看详情
《代码整洁之道》
代码整洁之道代码猴子(CodeMonkey):低水平编码者.童子军规.技艺(craftsmanship):知和行.学写整洁代码,掌握原则和模式,并付出行动.整洁代码代码呈现了需求的细节.这些细节无法被忽略或抽象,必须要严谨,精确,规范和详细.糟糕的代码... 查看详情
代码整洁之道源码分享(代码片段)
最近学习代码整洁之道,在练习的过程一直想找到章节中的源码案例,直接进行练习,无奈没有找到,只能自己耗时耗力的从头开始敲,总觉的讲解代码的书籍,不提供源码是可耻的,哈哈。分享链接为代码整洁之道书中部分章... 查看详情
整洁之道如何写出更整洁的代码(上)
如何写出更整洁的代码 代码整洁之道不是银弹,不会立竿见影的带来收益。 没有任何犀利的武功招式,只有一些我个人异常推崇的代码整洁之道的内功心法。它不会直接有效的提高你写代码的能力与速度,... 查看详情
typescript代码整洁之道
干净整洁的代码,不但质量更可靠,也为后期升级、维护打下了良好的基础。那么,整洁代码的衡量标准是什么?本文将RobertC.Martin的CleanCode思想融入到TypeScript,一起探讨研究代码整洁之道。 WTFs/Minute 1.命名的艺术计算... 查看详情
代码整洁之道读书笔记
代码整洁之道 前言如何用功 阅读大量代码 找优点和缺点第一章整洁代码不要留到以后,稍后等于永不烂代码影响生产力代码整洁性不但有关效率,还有关生存好代码 C++之父 尽量减少依赖关系,便于维护... 查看详情
代码整洁之道
文章目录代码整洁之道定义变量名字的时候常用的单词有意义的命名怎样写简洁的,别人一眼可以看的懂的方法方法参数越少越好注释格式别给方法返回null值我们该提炼方法中的变量还是不提炼方法中的变量?代码整洁之道定... 查看详情
代码整洁之道pdf下载
网盘下载地址:代码整洁之道PDF下载–易分享电子书PDF资源网 作者: [美]RobertC·Martin出版社: 人民邮电出版社原作名: CleanCode:AHandbookofAgileSoftwareCraftsmanship译者: 韩磊出版年: 2010-1-1页数: 388定... 查看详情