首页 > 解决方案 > 当某些子类不需要在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
{
}

放入startValidateAbstractClockIn如果子类必须进行验证,只需覆盖它,但这对我来说并不好。

标签: php

解决方案


推荐阅读