You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 DriverInfo instances. By validating here, you ensure no invalid (under-18) DriverInfo objects 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 DriverInfo object 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 DriverInfo would 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:19:00