我正在阅读关于Object Calisthenics的内容,其中一条规则是包装原始类型和字符串:
class UIComponent {
public function repaint($animate = true)
{
//
}
}
$component->animate(false);
Run Code Online (Sandbox Code Playgroud)
变为:
class UIComponent {
public function repaint(Animate $animate)
{
//
}
}
class Animate {
private $animate;
public function __construct($animate = true)
{
$this->animate = $animate;
}
}
$component->animate(new Animate(false));
Run Code Online (Sandbox Code Playgroud)
这项技术有什么好处?在我看来,我认为这只是复杂的事情,并添加了更多的代码行.
在这种情况下,它确实有点超大,但还有其他一些例子,它可以有意义
class Identifier {
protected $id;
public function __construct ($id) {
if (!preg_match('~^{a-z0-9]$~i', $id)) throw new Exception("Invalid id '$id'");
$this->id = $id;
}
public function getId () { return $this->getId(); }
}
Run Code Online (Sandbox Code Playgroud)
所以这个是不可变的,它确保了特定的格式.当您在另一个类中对此类进行类型提示时,您无需测试该标识符是否有效
class MyClass {
protected $id;
public function __construct (Identifier $id) { $this->id = $id; }
}
Run Code Online (Sandbox Code Playgroud)
这只是一个简单的例子,事实上它在php中并不常见.
[..]并添加了更多代码行.
我不认为"更多代码行"本身就是坏事.如果它需要更多的行(甚至类),编写可读和干净的代码,它比紧凑但不可读的东西要好得多.