V
V
Vetal Matitskiy2015-04-06 09:13:16
Java
Vetal Matitskiy, 2015-04-06 09:13:16

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

3 answer(s)
B
bromzh, 2015-04-07
@vetalmatitskiy

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.

A
anyd3v, 2015-04-06
@anyd3v

How about Google for starters? stackoverflow.com/questions/2997768/java-construct...

H
Hayter, 2015-04-06
@Hayter

In general, you should use the Builder pattern instead of constructors and already validate the necessary parameters in it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question