0

OK, so when you are working on some Spring MVC project and you've got some model that has a few setter functions like setCountry(String country) I know most of the code and books just set the parameter without any validation, but would it be good practice to check for null?

Before:

public void setCountry(String country)
  this.country = country;

After:

public void setCountry(String country)
  if (country != null) {
    this.country = country;
  }

1 Answers1

0

It depends on your requirements, suppose you have a dropdown field in a form that takes input of a country. Now if you have set the country value to USA and submit it will be set as per your null checking condition.

Now assume the user has the ability to resubmit the form and he has reset the country field to empty and if you set a null checking condition inside your setter method. Then your field value will remain as it was before(USA) the form post. How would the user of your program get notified that his null input has been overlooked? There has to be a proper validation along side not accepting null as a value.

Now imagine another set of checkboxes. Where user may/ may not select any value. Initially he checked two values and later he decided to not select any in such case his input will have to be taken care of.

So basically you set validation rule outside the setter to observe user's input and notify him before doing any action with the data that the user has posted.

Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
  • Ok so I guess I should really validate input data before calling setter functions in models right? I think that is in line with most Spring tutorials. – Sonic on fire Apr 06 '16 at 15:13
  • Actually once you post it will be bind to your model via your setter methods. But the good practice is to not use the full model data unless you validate it. If the data validation is ok then you process the data else you inform the user about the validation failure. – Mustofa Rizwan Apr 07 '16 at 11:09