简体   繁体   English

Java:通过使用最终的设置方法避免警告“构造函数中的可重写方法调用”

[英]Java: Avoid warning “Overridable method call in constructor” by using final setters

I always used setters as a place to validate a value before assigning it to a field. 在将值分配给字段之前,我总是使用setter作为验证值的地方。

public class Person {
    private int id;

    public int getId() {
        return this.id;
    }

    public int setId(int id) {
        if (id < 0) {
            throw new IllegalArgumentException("id must be positive.");
        }
        this.id = id;
    }

    public Person(int id) {
        setId(id);
    }
}

What I think is good about it is that I now have one place where a value gets validated before assignment and I can call it from everywhere. 我认为这样做的好处是,我现在有一个地方可以在赋值之前对值进行验证,并且可以在任何地方调用它。 But the compiler warns me about that overridable method call in the constructor of the class. 但是编译器警告我有关类的构造函数中该可重写方法的调用。 I read What's wrong with overridable method calls in constructors? 我读了构造函数中可重写的方法调用怎么了? and understand the issues this might cause and that it is recommended to use a Builder Pattern instead. 并了解可能导致的问题,建议您改用构建器模式 But would it be also okay to just add final to the getters and setters instead to prevent overriding those properties? 但是,也可以只将final添加到getter和setter中,以防止覆盖这些属性,这还可以吗?

would it be also okay to just add final to the getters and setters instead to prevent overriding those methods? 只是将final添加到getter和setter中来防止覆盖这些方法,也可以吗?

Yes, it would. 是的,会的。 In addition to stopping the warning, it would make your code more robust, because subclasses would not be able to change the validation in your setters, either on purpose or by accident. 除了停止警告之外,这还将使您的代码更健壮,因为子类将无法有意或无意更改设置器中的验证。

Another solution would be to make a private method for validating the data, and call it from both the constructor and the setter. 另一个解决方案是创建一个用于验证数据的私有方法,并从构造函数和设置方法中调用它。 This would solve the problem as well: 这也将解决问题:

private void setIdChecked(int id) {
    if (id < 0) {
        throw new IllegalArgumentException("id must be a positive.");
    }
    this.id = id;
}
public void setId(int id) {
    setIdChecked(id);
}
public Person(int id) {
    setIdChecked(id);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM