第十八天
客串:屌絲的坑人表單神器
走過的那些事兒:數據庫那點事兒
起點:手把手教你做關鍵詞匹配項目(搜索引擎)---- 第一天
回顧:手把手教你做關鍵詞匹配項目(搜索引擎)---- 第十七天
上回說到小帥帥把代碼交給於老大時,於老大批了小帥帥,小帥帥真的感覺受委屈了。
我們回到站在技術總監的角度看問題,技術總監真的要做到監管代碼的可讀行嗎?
我記得很多公司都是提倡利益,利益作為衡量一個技術總監的價值。
技術總監做錯了嗎?超出他的職責范圍了嗎?
其實於老大看到 LinklistCharListHandle類裡面exec方法出現了三層foreach,就把小帥帥給批了。
好嚴格的於老大,還是於老大對小帥帥的期望比較高。
小帥帥沒辦法,他只好把foreach盡量提取出來,小帥帥的版本:
class LinklistCharListHandle extends CharListHandle {
public function exec(){
$sql = "select word from category_linklist where cid='$this->selectorItem->cid'";
$linklist = DB::makeArray($sql);
foreach($linklist as $strWords){
$words = explode(",",$strWords);
$this->propertiesTransferCharlist($words);
}
}
public function propertiesTransferCharlist($linkWords){
$properties = $this->selectorItem->getProperties();
foreach($properties as $property){
$this->charlist->addCore($property->value);
if(in_array($property->value,$linkWords)){
$this->addCores($linkWords);
}
}
}
public function addCores($words){
foreach($words as $char){
$this->charlist->addCore($char);
}
}
}
小帥帥提取了兩個方法,使程序更加能夠看懂了。
其實小帥帥的的做法就是使用重構-改善既有代碼的設計的技巧之一,Extract Method 提煉函數
Extract Method:將這段代碼放進一個獨立函數中,並讓函數名稱解析該函數的用途。
小帥帥很有成就感,繼續把代碼給於老大的時候,於老大提到了兩點。
1. propertiesTransferCharlist為什麼要接受個參數。
2. addCores到底是那個類的職責范圍。
小帥帥第2種他知道怎麼做,他把該方法移到Charlist類裡面,代碼如下:
<?php
class CharList {
private $core = array();
private $blacklist = array();
public function addCore($char){
if(!in_array($char,$this->core))
$this->core[] = $char;
}
public function addCores($words){
foreach($words as $char){
$this->addCore($char);
}
}
public function getCore(){
return $this->core;
}
public function addBlacklist($char){
if(!in_array($char,$this->blacklist))
$this->blacklist[] = $char;
}
public function getBlacklist(){
return $this->blacklist;
}
}
其實小帥帥的這次做法還是使用重構-改善既有代碼的設計的技巧之一,Move Method 搬移函數。
Move Method:在該函數最常引用的類中建立一個有著類似行為的新函數。將舊函數變成一個單純的委托函數,或是將舊函數完全移除。
小帥實在搞不懂第1個怎麼辦,又去請教於老大,於老大直接把代碼給了小帥帥,於老大的代碼為:
<?php
class LinklistCharListHandle extends CharListHandle {
private static $linklist;
public function exec(){
$this->propertiesTransferCharlist();
}
public static function linklist($cid){
if(!isset(self::$linklist) || !isset(self::$linklist[$cid]) || self::$linklist[$cid] == null){
$sql = "select word from category_linklist where cid='$cid'";
self::$linklist[$cid] = DB::makeArray($sql);
}
return self::$linklist[$cid];
}
public function propertiesTransferCharlist(){
$properties = $this->selectorItem->getProperties();
foreach($properties as $property){
$this->charlist->addCore($property->value);
$this->extendCharlist($property->value);
}
}
public function extendCharlist($char){
$linklist = self::linklist($this->selectorItem->cid);
foreach($linklist as $strWords){
$words = explode(",",$strWords);
if(in_array($char,$words)){
$this->charlist->addCores($words);
}
}
}
}
小帥帥看了,發表了一次感歎,原來代碼隨便改變下,區別這麼大,以前為啥從來沒有這感覺。
小帥帥真希望自己能夠獨單一面,不用天天去找於老大。