java - 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?
解决方案
以下是一种常见的技术。可惜靠需要调用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() {
...
}
这允许父类控制行为,例如为受保护的回调方法提供参数。
推荐阅读
- python - 在熊猫中使用滚动函数,其中时间索引非常稀疏
- docker - 您可以在不拉取远程存储库中标记 docker 映像吗?
- c++ - 为什么构建 Docker 容器时找不到所需的 libboost-all-dev 版本?
- python - 用python模拟卫星绕地球的轨道?
- javascript - 为什么 mouseEvent.offset 在同一位置单击时不同
- html - 溢出 -x hidden 在移动设备上不起作用
- java - 如何修复 Spring Tool Suit 4 中的 Port 8080 错误?
- arrays - 快速访问 JSON 响应数组中的数组?
- c++ - 如何修复“没有这样的文件或目录”库错误?我正在使用 Mingw-w64 编译器和 Netbeans IDE
- django - 在 Django 中创建了自定义权限并为组和用户分配了权限,但 @permission_required 失败