php - 当某些子类不需要在PHP中的抽象类中执行方法时如何改进代码
问题描述
代码
abstract class AbstractClockIn
{
public function validate(): void
{
if (! $this->startValidate()) {
// Save error to log
throw Exception('');
}
}
abstract protected function startValidate(): bool;
abstract public method doSomething(): void;
}
class A extends AbstractClockIn
{
protected function startValidate(): bool
{
// Validate process
return true || false;
}
public function doSomething(): void
{
// Do something
}
}
class B extends AbstractClockIn
{
protected function startValidate(): bool
{
// No need validate so always return true;
return true;
}
public doSomething(): void
{
// Do something
}
}
try {
$a = new A();
$a->validate();
$a->doSomething();
} catch(Exception $e) {
echo $e->getMessage();
}
如果需要子类可以扩展,在某些情况下子类不需要做startValidate
但需要放置startValidate
以确保需要验证的子类工作良好,这意味着startValidate
子类中有很多无用的,有一个想法:
abstract class AbstractClockIn
{
public function validate(): void
{
if (! $this->startValidate()) {
throw Exception('');
}
}
protected startValidate(): bool
{
return true;
}
}
class A extends AbstractClockIn
{
protected function startValidate(): bool
{
// Validate process
return true | false;
}
}
class B extends AbstractClockIn
{
}
放入startValidate
,AbstractClockIn
如果子类必须进行验证,只需覆盖它,但这对我来说并不好。
解决方案
推荐阅读
- python-3.x - Python List - 如何评估json字符串值中的空白/空值/空格并将其替换为某个默认值?
- node.js - 如何让猫鼬运行验证器?
- kubernetes - 可以在没有集群管理员角色的情况下使用 argo 吗?
- linux - 我们是否应该始终使用这种寄存器顺序进行系统调用?
- r - 从各种不同的计数在 R 中构建一个 tibble
- python - 深度学习预测结果范围(BPSK)
- vue.js - “在‘vue’中找不到导出‘默认’(导入为‘Vue’)
- javascript - 如何从动态 HTML 表中获取特定的用户输入数据(Onchange 函数,数值)
- google-sheets - 如何对多个 INDEX+MATCH 结果求和
- c++ - 如何从 C++ 中 O(n) 中的关联 NxN 矩阵中删除行和列?