Answer the question
In order to leave comments, you need to log in
What is the correct way to validate data when creating an object in Java?
Good afternoon, dear java-gurus
, please tell me how to work more correctly with the object constructor when you need to do data validation?
Whether to do a check in the constructor itself and throw an exception if incorrect data is received. Or do you need to make a separate function that will first check the data for validity and only then call the constructor for this data?
Answer the question
In order to leave comments, you need to log in
Can be checked at creation (via constructor/factory/builder/etc). You can check through assert or through if, throwing the necessary error (some kind of IllegalArgumentException, for example).
You can tweak any convenient java validation framework . If you use the JavaEE API, then it seems to be already included there. It remains only to choose an implementation (if you use an application server, then most likely, the validation api is included in the server delivery, and in maven it is enough to specify the scope provided for the JavaEE API). Arrange the necessary annotations and enjoy the result.
How about Google for starters? stackoverflow.com/questions/2997768/java-construct...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question