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:
- On constructor add the if() described above. The validation would work if the constructor is called from multiple places on your code. My concern is that class constructors should (IMHO) not contain any logic. Am I right?
- Validate somewhere outside the constructor - whether it's a factory method, builder class etc. But then we are forcing developers to not instantiate the class by using the constructor, but to use some artificial factory/builder.
- To validate constructors parameters by using Validate. It's not standard Java, but I saw people doing this. As for me it doesn't look right, because we're adding logic to the constructor - which doesn't look right for me.
- Any other good way I missed?
Any thoughts would be highly appreciated. Does anyone could suggest a best practice how to deal with the situation described abode?