1

To use a made up example, suppose I have a form.submit() method and I want to validate the form before submission. Should the validation go inside the method or outside of it in the calling code?

If I put the validation inside the method then I can be assured that it is always checked and not worry about someone calling the method without the conditions being met. However, for someone reading the calling code, it may not be obvious that the validation is happening, leading them to checking it twice by adding their own checks in the calling code. If all they see is form.submit() in the calling code, they may not realize it's doing the validation, leading them to duplicate it in the calling code by adding if-conditions surrounding the method call.

What is the proper way to handle this?

public void submit() {
    if(this.isValid()) {
        // do submission
    }
}

...

form.submit();

OR

public void submit() {
    // do submission
}

...

if(form.isValid())
    form.submit();
Nick Manley
  • 63
  • 1
  • 3

1 Answers1

0
public void validateAndSubmit() {
    if(this.isValid()) {
        this.submitWhenValid()
    }
}
public void submitWhenValid() {
    // do submission
}
...

form.validateAndSubmit();
user1494736
  • 2,425
  • 16
  • 8