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?
I suggest you let your performData()
check if the validation is ok, that makes it a lot easier. You might also want to make performData()
public
to be accessible outside the class.
public class Parent {
protected int sum;
protected double commission;
protected boolean validateData() {
return isSumWrittenCorrectly();
}
private boolean isSumWrittenCorrectly() {
if (sum < 100) {
return false;
}
return true;
}
protected void performData() {
if(!validateData()) {
return;
}
commission = sum * 0.02;
}
}
class Child extends Parent {
private String email;
@Override
protected boolean validateData() {
if(!super.validateData()) {
return false;
}
if (!isEmailWrittenCorrectly()) {
return false;
}
return true;
}
@Override
protected void performData() {
super.performData();
if(!validateData()) {
return;
}
sendData(email, commission, sum);
}
}
In the end, it might also be easier to throw an exception in case of validation failing, that will save some true
false
comparisions.
public class Parent {
protected int sum;
protected double commission;
protected void validateData() {
if(!isSumWrittenCorrectly()) {
throw new IllegalArgumentException("sum is not correct");
}
}
private boolean isSumWrittenCorrectly() {
if (sum < 100) {
return false;
}
return true;
}
protected boolean performData() {
validateData();
commission = sum * 0.02;
}
}
class Child extends Parent {
private String email;
@Override
protected boolean validateData() {
super.validateData();
if (!isEmailWrittenCorrectly()) {
throw new IllegalArgumentException("email is not correct")
}
}
@Override
protected void performData() {
validateData();
super.performData();
sendData(email, commission, sum);
}
}