当前位置: 首页 > 后端技术 > PHP

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

时间:2023-03-29 15:55:39 PHP

良好的语义表达是团队合作高效迭代的润滑剂,良好的语义表达是在线未知代码排查的指南针。这篇文章很长,如果你“偷懒”,我来告诉你(更多详情在直播中)播放地址看完是不是很有趣?学习使你快乐?还想学?上车,别让别人看不懂你的代码。一周后其他人可能就是你。永远用“如果你写的代码失败了,陌生人接管你的代码来处理这个bug需要多长时间”来监控自己。日常生活中,刻意改善自己的语义表达,有益无害。那么应该从哪些细节来做好语义表达呢?以下代码是我的全部艺术,不属于任何实际项目命名案例1functiongetGoods($query,$shopId){$goodsId=Goods::add($query["uid"],$query["name"]);returnShop::add($goodsId,$shopId);}类商品{publicstaticfunctionadd($uid,$name){$id=mt_rand(1,100000);返回$id;}}classShop{publicstaticfunctionadd($goodsId,$shopId){$id=mt_rand(1,100000);返回$id;}}case2functiongetUserInfo($teamId,$youId=[]){}如果只有这个函数名和参数名,谁能猜出参数的含义?Case3classDb{/***@paramstring$table数据库表名*@paramarray$data新数据**@returnint新主键*/publicstaticfunctioninsert(string$table,array$data){$id=mt_rand(1,1000);返回$id;}}classViewLogStore{private$table="view_log";函数setHistory($data){Db::insert($this->table,$data);}}案例4如果业务代码中有这些类classWechatUserModel{}classWechatGroupModel{}classWechatMessageModel{}和我我们查询了数据库,发现根据业务代码查找对应的表非常不方便,而且当其他人接手我们的项目时,也会一头雾水或者这可能是三个人开发了三次迭代造成的人,所以他们彼此没有任何关系。参考前面的命名规则。灵魂拷问笔记命名完了,下面说说笔记。笔记里还有什么?你在开玩笑吧?一个数组对象成员,你知道怎么写吗?你知道如何为类魔术方法调用编写注释吗?对象数组/***@varAds[]*/public$adsList=[];$blocks=[];/**@var$blocksBlock[]**/@method的使用/***@linkhttp//manual.phpdoc.org/HTMLframesConverter/default/**@methodstaticintsearch(string$query,$limit=10,$offset=0)*/classSearchServiceProxy{公共静态函数__callStatic($method,$arguments){if(!method_exists("SearchService",$method)){thrownew\LogicException(__CLASS__."::".$method."notfound");}try{$data=call_user_func_array(["SearchService",$method],$arguments);}catch(\Exception$e){error_log($e->getMessage());返回假;}返回$数据;}}@deprecateduseclassSearchService{/***@paramstring$query*@paramint$limit*@paramint$offset**@returnarray*@deprecated*/publicstaticfunctionsearch(string$query,$limit=10,$offset=0){return[["id"=>1,"aaa"],["id"=>2,"bbb"],];}}NotesOtherNotesComments解释张冠李戴,方法名更新了,方法的函数业务注释没有更新;抄别人的代码,@author的信息也抄,写错了,还得把责任推给别人注释更多参考http://manual.phpdoc.org/HTML...函数、方法案例1让我先解释一下,糟糕的代码并不妨碍它成为一个优秀的软件。PHP和MySQL中有很多错误代码。我在一个开源软件里找到了代码,功能很抢手,但是这个方法内容太多,我标记了一些不足之处。案例2上面以我为例。还记得下面这张图吗?优化方案1classArrayUtils{publicstaticfunctionfetch($arr,$keys,$setNull=false){$ret=array();foreach($keysas$key){if($setNull){$ret[$key]=$arr[$key];}else{isset($arr[$key])&&$ret[$key]=$arr[$key];}}返回$ret;}}classViewLogStore{private$table="view_log";函数记录($data){$fields=array('uid','url','referer','created_time');$data=ArrayUtils::fetch($data,$fields);数据库::insert($this->table,$data);}}优化方案2classDb{/***@paramstring$table数据库表名*@paramEntity$data新对象**@returnint新主键*/publicstaticfunctioninsert(string$table,Entity$data){$array=$data->toArray();var_export($数组);//测试$id=mt_rand(1,1000);返回$id;}}classArrayUtils{/***对于成员都是私有属性的对象**@param$obj*@parambool$removeNull移除空值*@parambool$camelCase**@returnarray*/publicstaticfunctionObj2Array($obj,$removeNull=true,$camelCase=true){$reflect=new\ReflectionClass($obj);$props=$reflect->getProperties(\ReflectionProperty::IS_PUBLIC|\ReflectionProperty::IS_PRIVATE|\ReflectionProperty::IS_PROTECTED);$数组=[];foreach($propsas$prop){$prop->setAccessible(true);$key=$prop->getName();//如果不是驼峰命名,将对象中的createTime转换为create_timeif(!$camelCase){$key=preg_replace_callback("/[A-Z]/",function($matches){return"_".strtolower($matches[0]);},$key);$key=ltrim($key,"_");}$value=$prop->getValue($obj);如果($removeNull==true&&$value===null){继续;}if(is_object($value)){$value=self::Obj2Array($value);}$array[$key]=$value;}返回$array;}}classEntity{publicfunctiontoArray(){returnArrayUtils::Obj2Array($this);}}classViewLogEntityextendsEntity{/***@varint*/private$uid;/***@varstring*/private$url;/***@varstring*/private$referer;/***@varstring*/private$createdTime;/***@paramint$uid*/publicfunctionsetUid(int$uid){$this->uid=$uid;}/***@paramstring$url*/publicfunctionsetUrl(string$url){$this->url=$url;}/***@paramstring$referer*/publicfunctionsetReferer(string$referer){$this->referer=$referer;}/***@paramstring$createdTime*/publicfunctionsetCreatedTime(string$createdTime){$this->createdTime=$createdTime;}}classViewLogStore{private$table="view_log";函数记录(ViewLogEntity$viewLogEntity){Db::insert($this->table,$viewLogEntity);}}//测试$viewLogEntity=newViewLogEntity();$viewLogEntity->setUid(1);$viewLogEntity->setReferer("https://mengkang.net");$viewLogEntity->setUrl("https://segmentfault.com/l/1500000018225727");$viewLogEntity->setCreatedTime(date("Y-m-dH:i:s",time()));$viewLogStore=newViewLogStore();$viewLogStore->记录($viewLogEntity);案例3这还是函数吗?(不只是语言义,属于错误)/***@methodmixedfetchList(string$sql,array$argv);*/classModel{publicfunction__construct($table){}}functiongetUserList($startId,$lastId,$limit=100){if($lastId>0){$startId=$lastId;}$sql="select*from`user`whereid>?orderbyidasclimit?,?";$model=newModel('用户');return$model->fetchList($sql,[intval($startId),intval($limit)]);}$startId和$lastId两个参数重复Case4Minimizeparameterreferencesfunctionbad($input1,$input2,&$input3){//...逻辑$input3="xxx";returntrue;}Case5参数类型明确,返回值类型明确,不要出现混用,本人直接以官方函数为例,对权威持怀疑态度。纯属个人意见。案例6在上面的例子中,你会发现这个addUser并不是写成一个函数(方法)而是写成一个远程api接口。而右边的代码中,每次使用的时候都需要用is_array来判断。这是一种非常不友好的语义表达。PHP、Java等高级语言都有异常,我们要好好利用异常。良好的语义表达是团队合作高效迭代的润滑剂,良好的语义表达是排查线上未知代码问题的指南针。这篇博客就到这里了,不知道大家有没有收获呢?放三个二维码很累。创建原创博客并不容易。如果你认为它很好,你可以给它一个奖励。谢谢。