首页 > 解决方案 > How to break overridden method if it's base method fails?

问题描述

I have a method called validateData in my Parent class. In my Child class I override that method adding some additional functionality. If everything is ok, I need to call method called sendData(). Here is my code in Java:

  public class Parent {

    protected int sum;
    protected double commission;

    protected void validateData() {
        if (!isSumWrittenCorrectly()) {
            return;
        }

        performData();
    }

    private boolean isSumWrittenCorrectly() {
        if (sum < 100) {
            return false;
        }

        return true;
    }


    protected void performData() {
        commission = sum * 0.02;
    }


}


class Child extends Parent {
    private String email;

    @Override
    protected void validateData() {
        super.validateData();

        if (!isEmailWrittenCorrectly()) {
            return;
        }

        performData();
    }

    @Override
    protected void performData() {
        super.performData();


        sendData(email, commission, sum);

    }
}

So, the problem is, even if sum can be incorrectly written, the performData of child class can be called anyway. How to prevent this? I had an idea that validateData needs to return boolean and in my child class I check through super keyword. But it is a bad idea I think. So, how to break overridden method if it's base method fails?

标签: javaoop

解决方案


以下是一种常见的技术。可惜靠需要调用super.validateData

public class Parent {
    protected boolean validateData() { ... }

public class Child extends Parent {
    protected boolean validateData() {
        if (!super.validateData()) {
            return false;
        }
        ...
    }

或者,您可以将功能拆分为

  • 提供的服务 ( public final validateData) 和
  • 要求提供 ( protected dataValidate/onValidateData)。

所以:

public class Parent {
    public final void validateData() {
        boolean valid = dataValidated();
        ...
    }
    protected boolean dataValidated() {
        return true;
    }

public class Child extends Parent {
    @Override
    protected boolean dataValidated() {
        ...
    }

这允许父类控制行为,例如为受保护的回调方法提供参数。


推荐阅读