javavalidation

How to validate constructor parameters on Java?


Let's say we use Java SE (no libraries) and have the following situation. We have a class:

public class DriverInfo {
    private final int age;

    public DriverInfo(int age) {
        this.age = age;
    }

    // getter here
}

In some countries there is a requirement that you can drive if you're 18 years old. In other words - we need to have some validation for age parameter. Something like:

if (age < 18) {
    throw new IllegalArgumentException("Age is not valid!");
}

So, my question is - where this validation should be? My thoughts are as follows:

Any thoughts would be highly appreciated. Does anyone could suggest a best practice how to deal with the situation described abode?


Solution

  • Validation in constructor is completely fine. This "no logic in constructor" rule does not apply on it, guess it's worded bit unfortunately. Task of constructor is to take dependencies from outside (dependency injection), make sure they are valid and then probably store them in instance attributes - creating valid instance in short.

    This way the rules of what is valid and what is not valid are kept inside the object, not detached in some factory.

    If the instance would be invalid, then throwing an exception, which explains what is wrong with parameters, is absolutely fine. It prevents invalid instances from roaming around system.

    Also this way with immutable objects you get guaranteed that all existing instances are valid all the time, which is great.

    Having some validation method on the object is possible and can be useful, but I'd prefer constructor validation any day. But if it's not possible, then it's better than nothing and it still keeps the rules for validity within the object. Like when some framework constructs your mutable object for you and requires parameterless constructor...you can forget to call it, but it's better than nothing.