Mar*_*ech 3 php methods refactoring class
我正在玩重构PHP类.我的原始类有一个构造函数和一个大型方法,它通过各种操作运行字符串并在结尾处吐出结果.
class String
{
public function __contstruct()
{
// a couple of initialisation things
}
public function make($string)
{
// very large method that does lots of different types of filtering to an input string
}
}
Run Code Online (Sandbox Code Playgroud)
我的类通过scrutinizer-ci运行,其中一个建议是使用Composer方法模式将大方法重构为较小的自包含方法.
https://scrutinizer-ci.com/docs/refactorings/compose-method
我做了这个,看起来更整洁,但这是我的问题/查询......
我的新课程现在看起来像这样
class String
{
public function __construct()
{
// a couple of initialisation things
}
public function make($string)
{
$string = $this->smallMethodOne($string);
$string = $this->smallMethodTwo($string);
$string = $this->smallMethodThree($string);
$string = $this->smallMethodFour($string);
$string = $this->smallMethodFive($string);
}
private function smallMethodOne($string) {
// do some stuff
return $string;
}
private function smallMethodTwo($string) {
// do some stuff
return $string;
}
private function smallMethodTwo($string) {
// do some stuff
return $string;
}
private function smallMethodThree($string) {
// do some stuff
return $string;
}
private function smallMethodFour($string) {
// do some stuff
return $string;
}
private function smallMethodFive($string) {
// do some stuff
return $string;
}
}
Run Code Online (Sandbox Code Playgroud)
我只是想知道是否有举办一个更好的方式make(),因为它没有方法感到正确的做这样的,只是运行了一堆的顺序方法.
Wes*_*Wes 16
你应该问自己的是:在不改变其他"smallMethod"行为的情况下,覆盖单个"smallMethod"会有多难?
如果您可以覆盖单个"smallMethod"而不触及其他人,那么您可能正在做正确的事情.
说你有这个:
public function deleteMe()
{
if($this->a == x || $this->b != y){
$this->cache->delete($this);
$this->storage->delete($this);
$this->refs->unlink($this);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果要扩展类并更改deleteMe()if()条件,该怎么办?您需要完全重写该方法,进行一行更改.这根本不方便.代替:
protected function checkDeletability()
{
return $this->a == x || $this->b != y;
}
protected function internalDelete()
{
$this->cache->delete($this);
$this->storage->delete($this);
$this->refs->unlink($this);
}
public function deleteMe()
{
if($this->checkDeletability())
$this->internalDelete();
}
Run Code Online (Sandbox Code Playgroud)
这样,您可以覆盖过程的单个部分,而无需触及其他部分.这就是为什么你"把一个大方法分成小方法"的原因.
所以,检查一下你是否满意.这才是最重要的!
| 归档时间: |
|
| 查看次数: |
574 次 |
| 最近记录: |