如何成为一名优秀的工程师(语义篇)

开发 后端
好的语义表达是团队协作中高效迭代的润滑剂,好的语义表达是线上未知代码问题排查的指南针。

好的语义表达是团队协作中高效迭代的润滑剂,好的语义表达是线上未知代码问题排查的指南针。

本篇文章巨长,如果你比较“懒”,来我讲给你听(直播中有更多细节) 回放地址

看完这个还不过瘾?学习使你快乐?还想学习?快上车

不要让其他人读不懂你的代码,其他人可能就是一周后的你。时刻以“如果你写的这段代码出现故障,一个陌生人接手你的代码需要多久能处理完这个bug”来监督自己。

日常中应该多多刻意提升自己语义表达,百利而无一害。那么我们应该从哪些细节去做好语义表达呢?  

如何成为一名优秀的工程师(语义篇) 

以下代码全为我的艺术创作,不属于任何实际项目

命名

案例1 

  1. function getGoods($query, $shopId) 
  2.     $goodsId = Goods::add($query["uid"], $query["name"]); 
  3.     return Shop::add($goodsId, $shopId); 
  4.  
  5. class Goods 
  6.     public static function add($uid, $name
  7.     { 
  8.         $id = mt_rand(1, 100000); 
  9.         return $id; 
  10.     } 
  11.  
  12. class Shop 
  13.     public static function add($goodsId, $shopId) 
  14.     { 
  15.         $id = mt_rand(1, 100000); 
  16.         return $id; 
  17.     } 
  18. }  

如何成为一名优秀的工程师(语义篇) 

案例2 

  1. function getUserInfo($teamId, $youId = []) 
  2. {  
  3. }  

如果仅仅有这个函数名和参数名,谁能猜到参数的意义呢? 

如何成为一名优秀的工程师(语义篇) 

案例3

  1. class Db 
  2.     /** 
  3.      * @param string $table 数据库表名 
  4.      * @param array  $data  新增数据 
  5.      * 
  6.      * @return int 新增主键 
  7.      */ 
  8.     public static function insert(string $table, array $data) 
  9.     { 
  10.         $id = mt_rand(1, 1000); 
  11.         return $id; 
  12.     } 
  13.  
  14. class ViewLogStore 
  15.     private $table = "view_log"
  16.  
  17.     function setHistory($data) 
  18.     { 
  19.         Db::insert($this->table, $data); 
  20.     } 
  21. }  

 

案例4

假如业务代码里有这些类 

  1. class WechatUserModel{ 
  2. class WechatGroupModel{ 
  3. class WechatMessageModel{ 
  4. }  

而我们查询数据库发现 

 

这样我们根据业务代码就非常不方便找到对应的表,而且其他人接手我们项目的时候,也会摸不着头脑。或者说这可能是三个人三次迭代开发造成的,那么他们彼此都没有去参考前面人的命名规则。

来自灵魂的拷问

 

注释

说完命名,下面说下注释。注释里还有什么学问?Are you kidding me?

一个数组对象成员,你知道怎么写吗?

类的魔术方法调用的注释,你知道怎么写吗?

对象数组 

  1. /** 
  2.  * @var Ads[] 
  3.  */ 
  4. public $adsList = [];  

 

  1. $blocks = [];/** @var $blocks Block[] **/  

如何成为一名优秀的工程师(语义篇)

@method 的使用 

  1. /** 
  2.  * @link http://manual.phpdoc.org/HTMLframesConverter/default
  3.  * 
  4.  * @method static int search(string $query, $limit = 10, $offset = 0) 
  5.  */ 
  6. class SearchServiceProxy 
  7.     public static function __callStatic($method, $arguments) 
  8.     { 
  9.         if (!method_exists("SearchService", $method)) { 
  10.             throw new \LogicException(__CLASS__ . "::" . $method . " not found"); 
  11.         } 
  12.  
  13.         try { 
  14.             $data = call_user_func_array(["SearchService", $method], $arguments); 
  15.         } catch (\Exception $e) { 
  16.             error_log($e->getMessage()); 
  17.             return false
  18.         } 
  19.  
  20.         return $data; 
  21.     } 
  22. }  

 

 

 

@deprecated 使用  

  1. class SearchService 
  2.  
  3.     /** 
  4.      * @param string $query 
  5.      * @param int    $limit 
  6.      * @param int    $offset 
  7.      * 
  8.      * @return array 
  9.      * @deprecated 
  10.      */ 
  11.     public static function search(string $query, $limit = 10, $offset = 0) 
  12.     { 
  13.         return [ 
  14.             ["id" => 1, "aaa"], 
  15.             ["id" => 2, "bbb"], 
  16.         ]; 
  17.     } 
  18.  

 

 

 

注释其他注意事项

注释解释张冠李戴,方法名更新,方法的功能业务注释没更新;复制别人的代码把 @author 信息也复制过来了,错误了还要把锅甩给别人。

注释更多参考 http://manual.phpdoc.org/HTML...

函数、方法

案例1

先说明一句,不好的代码不妨碍它成为一个优秀的软件。PHP MySQL 烂代码多的去了。

找到一个开源软件里面的代码,功能非常抢到,但是这个方法内容太多,一些不足点我标注出来了。 

 

 

 

案例2

拿上面我举例子,还记得下面这种图吗? 

 

优化方案1 

  1. class ArrayUtils{ 
  2.     public static function fetch($arr, $keys, $setNull = false
  3.     { 
  4.         $ret = array(); 
  5.         foreach($keys as $key
  6.         { 
  7.             if ($setNull) 
  8.             { 
  9.                 $ret[$key] = $arr[$key]; 
  10.             } 
  11.             else 
  12.             { 
  13.                 isset($arr[$key]) && $ret[$key] = $arr[$key]; 
  14.             } 
  15.         } 
  16.         return $ret; 
  17.     } 
  18.  
  19.  
  20. class ViewLogStore 
  21.     private $table = "view_log"
  22.  
  23.     function record($data) 
  24.     { 
  25.         $fields = array( 
  26.             'uid'
  27.             'url'
  28.             'referer'
  29.             'created_time' 
  30.         ); 
  31.         $data = ArrayUtils::fetch($data, $fields); 
  32.         Db::insert($this->table, $data); 
  33.     } 
  34.  

优化方案2 

  1. class Db 
  2.     /** 
  3.      * @param string $table 数据库表名 
  4.      * @param Entity $data  新增对象 
  5.      * 
  6.      * @return int 新增主键 
  7.      */ 
  8.     public static function insert(string $table, Entity $data) 
  9.     { 
  10.         $array = $data->toArray(); 
  11.         var_export($array); // test 
  12.  
  13.         $id = mt_rand(1, 1000); 
  14.         return $id; 
  15.     } 
  16.  
  17. class ArrayUtils 
  18.     /** 
  19.      * 针对成员都是私有属性的对象 
  20.      * 
  21.      * @param      $obj 
  22.      * @param bool $removeNull 去掉空值 
  23.      * @param bool $camelCase 
  24.      * 
  25.      * @return array 
  26.      */ 
  27.     public static function Obj2Array($obj, $removeNull = true, $camelCase = true
  28.     { 
  29.         $reflect = new \ReflectionClass($obj); 
  30.         $props = $reflect->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PRIVATE | \ReflectionProperty::IS_PROTECTED); 
  31.  
  32.         $array = []; 
  33.         foreach ($props as $prop) { 
  34.             $prop->setAccessible(true); 
  35.             $key = $prop->getName(); 
  36.  
  37.             // 如果不是驼峰命名方式,就把对象里面的 createTime 转成 create_time 
  38.             if (!$camelCase) { 
  39.                 $key = preg_replace_callback("/[A-Z]/"function ($matches) { 
  40.                     return "_" . strtolower($matches[0]); 
  41.                 }, $key); 
  42.                 $key = ltrim($key"_"); 
  43.             } 
  44.  
  45.             $value = $prop->getValue($obj); 
  46.  
  47.             if ($removeNull == true && $value === null) { 
  48.                 continue
  49.             } 
  50.  
  51.             if (is_object($value)) { 
  52.                 $value = self::Obj2Array($value); 
  53.             } 
  54.  
  55.             $array[$key] = $value; 
  56.         } 
  57.  
  58.         return $array; 
  59.     } 
  60.  
  61. class Entity 
  62.     public function toArray(){ 
  63.         return ArrayUtils::Obj2Array($this); 
  64.     } 
  65.  
  66. class ViewLogEntity extends Entity 
  67.     /** 
  68.      * @var int 
  69.      */ 
  70.     private $uid; 
  71.  
  72.     /** 
  73.      * @var string 
  74.      */ 
  75.     private $url; 
  76.  
  77.     /** 
  78.      * @var string 
  79.      */ 
  80.     private $referer; 
  81.  
  82.     /** 
  83.      * @var string 
  84.      */ 
  85.     private $createdTime; 
  86.  
  87.     /** 
  88.      * @param int $uid 
  89.      */ 
  90.     public function setUid(int $uid) 
  91.     { 
  92.         $this->uid = $uid; 
  93.     } 
  94.  
  95.     /** 
  96.      * @param string $url 
  97.      */ 
  98.     public function setUrl(string $url) 
  99.     { 
  100.         $this->url = $url; 
  101.     } 
  102.  
  103.     /** 
  104.      * @param string $referer 
  105.      */ 
  106.     public function setReferer(string $referer) 
  107.     { 
  108.         $this->referer = $referer; 
  109.     } 
  110.  
  111.     /** 
  112.      * @param string $createdTime 
  113.      */ 
  114.     public function setCreatedTime(string $createdTime) 
  115.     { 
  116.         $this->createdTime = $createdTime; 
  117.     } 
  118.  
  119.  
  120. class ViewLogStore 
  121.     private $table = "view_log"
  122.  
  123.     function record(ViewLogEntity $viewLogEntity) 
  124.     { 
  125.         Db::insert($this->table, $viewLogEntity); 
  126.     } 
  127.  
  128. // 测试 
  129.  
  130. $viewLogEntity = new ViewLogEntity(); 
  131. $viewLogEntity->setUid(1); 
  132. $viewLogEntity->setReferer("https://mengkang.net"); 
  133. $viewLogEntity->setUrl("https://segmentfault.com/l/1500000018225727"); 
  134. $viewLogEntity->setCreatedTime(date("Y-m-d H:i:s",time())); 
  135.  
  136. $viewLogStore = new ViewLogStore(); 
  137. $viewLogStore->record($viewLogEntity);  

案例3

这还是函数吗?(不仅仅是语义,属于错误) 

  1. /** 
  2.  * @method mixed fetchList(string $sql, array $argv); 
  3.  */ 
  4. class Model 
  5.  
  6.     public function __construct($table
  7.     { 
  8.  
  9.     } 
  10.  
  11. function getUserList($startId, $lastId, $limit = 100) 
  12.     if ($lastId > 0) { 
  13.         $startId = $lastId; 
  14.     } 
  15.  
  16.     $sql = "select * from `user` where id > ? order by id asc limit ?,?"
  17.  
  18.     $model = new Model('user'); 
  19.     return $model->fetchList($sql, [intval($startId), intval($limit)]); 
  20.  

$startId和$lastId两个参数重复

案例4

尽量减少参数引用 

  1. function bad($input1, $input2, &$input3) 
  2.     //...logic 
  3.  
  4.     $input3 = "xxx"
  5.  
  6.     return true
  7.  

案例5

参数类型明确,返回值类型明确,不要出现 mixed。这个我直接拿官方的函数来举例,对权威也要有怀疑的眼光。纯属个人看法。 

 

 

 

案例6 

 

 

 

上面例子中你会发现这个addUser写得不想一个函数(方法)而像一个远程api接口。而且在右边的代码中需要每次使用的时候都要用is_array来判断。这是非常不友好的语义表达。PHP Java 这样的高级语言有异常,我们要善用异常。 

 

 

 

好的语义表达是团队协作中高效迭代的润滑剂,好的语义表达是线上未知代码问题排查的指南针。这篇博客到这里就结束了,不知道你是否有一些收获呢? 

 

 

责任编辑:庞桂玉 来源: segmentfault
相关推荐

2017-04-14 10:37:21

2012-11-29 10:05:20

2016-02-25 11:42:19

2021-07-29 11:14:03

DevOpsLinux工程师

2009-02-10 15:39:59

软件评测师软考经验

2016-10-21 15:57:10

2016-06-27 10:40:12

软件测试敏捷开发

2011-05-03 08:54:36

2017-09-21 09:44:00

编程程序员软件开发

2014-05-22 10:43:26

移动开发者优秀

2013-09-25 10:47:25

创新公司员工

2014-12-23 09:40:41

CTO

2020-06-29 14:54:19

网络技术专家讲座

2014-01-13 11:04:32

2013-01-07 09:41:48

2021-01-18 09:00:00

人工智能机器学习工程师

2016-01-28 11:18:09

卓越前端工程师

2021-05-25 09:51:42

架构运维技术

2018-03-29 11:23:25

IT人员云计算工程师

2009-04-02 18:29:05

点赞
收藏

51CTO技术栈公众号