Search code examples
javaconstructorargument-validation

How to respond based on arguments in java constructor


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.


Solution

  • 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.