Java SE(无第三方库)下构造方法参数验证:年龄校验位置咨询
Where to Place Age Validation for DriverInfo in Java SE
Great question! For your immutable DriverInfo class (since age is marked private final), the optimal spot to add the age validation logic is directly inside the constructor. Here's why and how to implement it:
Why the Constructor?
- Guarantees object validity from creation: The constructor is the only entry point for creating
DriverInfoinstances. By validating here, you ensure no invalid (under-18)DriverInfoobjects ever exist in your application. This prevents bugs where invalid data could propagate through your code before being caught. - Aligns with immutability principles: Since your class is immutable (no setters for
age), there's no other point where the age value could change. Validating during construction ensures the object remains valid for its entire lifecycle.
Updated Code Example
public class DriverInfo { private final int age; public DriverInfo(int age) { if (age < 18) { throw new IllegalArgumentException("Age is not valid! Must be at least 18."); } this.age = age; } // Getter method for age public int getAge() { return age; } }
What About Other Options?
- Putting validation in the getter: This is too late—an invalid
DriverInfoobject would already exist, and the error would only be thrown when someone tries to access the age. This could lead to unexpected failures later in your code flow. - Validating outside the constructor: This is error-prone because every place that creates a
DriverInfowould need to remember to run the validation. It's easy to miss this in one spot, leading to invalid objects slipping through.
Bonus: Handling Multiple Constructors
If you ever add more constructors to DriverInfo, make sure they all delegate to the main constructor that includes validation. This avoids duplicating validation logic:
public class DriverInfo { private final int age; // Main constructor with validation public DriverInfo(int age) { if (age < 18) { throw new IllegalArgumentException("Age is not valid! Must be at least 18."); } this.age = age; } // Secondary constructor delegates to main one public DriverInfo(String ageStr) { this(Integer.parseInt(ageStr)); } public int getAge() { return age; } }
内容的提问来源于stack exchange,提问作者Ernestas Kardzys
相关产品推荐
相关产品推荐

