2011-02-03 50 views
3

在這種情況下會被認爲是「最佳實踐」。我已經得到了團拜遠程資源的一類,它看起來有點像這樣:面向對象設計:返回值或設置屬性?

class Gather { 
    public function getAll($locations) { 
     $results = array('All','My','Results'); 
     return $results; 
    } 
} 

我的問題是,將它視爲返回結果,或將它們分配作爲一個屬性的最佳做法?即。

// This 
$results = $gatherer->getAll(); 
// vs This 
$gatherer->getAll(); // now $gatherer->results can be used 

它很可能我只是這得太多,但我有沒有正規的訓練,我想知道是否有做這樣的事情的「更正確」的方式。

回答

6

毫無疑問,第一個($ results = $ gatherer-> getAll())是首選。原因是價值與其來源之間的關係是明確的。在第二種情況下,讀者不清楚$ gatherer->結果是通過調用getAll()來填充的。也許它來自其他呼叫,或者它始終存在,或由外部呼叫者設置。

這也使得讀者更容易通過追蹤來了解呼叫。當getResults()返回值時,讀者應該閱讀getResults()的實現來查看它的來源。

+0

我同意。如果結果'屬於'收集實例,並且收集對象將隨後執行後續工作,則此替代方法僅適用。 – 2011-02-03 16:21:09

1

最近我一直在與這個相同的問題摔跤。在第二個版本

$gatherer->getAll(); // now $gatherer->results can be used 

我想你的命名約定更改爲

$gatherer->initResults(); 

那麼很明顯,結果是$採集的屬性。你甚至可以這樣定義$ gatherer-> initResults()像這樣:

public function initResults() { 
    $this->results = $this->getAll(); 
} 

public function getAll() { 
    // do whatever to get results 
} 

那麼,你可以使用任何一種形式。

對不起,我知道這是更多的評論,然後答案,但它是如此的代碼沉重,它實際上是不可讀的評論。