0

I have a MVC type architecture for new user registration to my app. The user submits the registration form to the controller servlet. This servlet extracts the user parameters and passes them to a class constructor, which represents (and returns) a template(or dummy) user with all the fields initialized based on the arguments.

I remember people insisting on argument validation in methods or constructors before using them. Now I try to check the arguments for their validity(for example they are not null). So when I find any argument having invalid value, How do I notify the servlet that this particular argument is invalid, because I cannot return a value from the constructor.

Please help me.

me_digvijay
  • 5,374
  • 9
  • 46
  • 83

3 Answers3

1

You should use another service or some class to validate your data, and throw exception from method or pass message back to servlet

jmj
  • 237,923
  • 42
  • 401
  • 438
1

Validate before calling the constructor. If anything is wrong get back to user with error. If everything is fine then only call constructor and create objects.

Ajinkya
  • 22,324
  • 33
  • 110
  • 161
  • But, someday some other person may use my user class and suppose he doesn't implement validation before calling the constructor(relying on me to have implemented the validation in the constructor.) – me_digvijay Feb 08 '13 at 07:04
  • @DigvijayYadav: As others mentioned Throwing exception will be a good way of handling this scenario. Also while creating your class thinking about what class gonna do is more important than what data others gonna provide to it. – Ajinkya Feb 08 '13 at 07:12
  • Ok, now I got what you mean. So I need to implement validation before calling the constructor and also throw an exception from the constructor for users who don't implement validation before calling the constructor. Thanx. – me_digvijay Feb 08 '13 at 07:24
  • @DigvijayYadav: Yes. Because validating every possible case in constructor will make it very complex. – Ajinkya Feb 08 '13 at 08:46
0

Do validation in servlet before calling the constructor. If validation fails forward to an error.jsp where you display which input parameter was null or invalid.

Subin Sebastian
  • 10,870
  • 3
  • 37
  • 42