setter 方法是否必须有一个参数?

发布于 2024-07-09 08:14:11 字数 513 浏览 8 评论 0原文

setter 方法是否必须有一个参数? 通常,setter 方法接受一个参数作为对象的某一属性的值。 如果我想首先测试依赖于另一个布尔参数的有效性,如果为 true,则首先验证,否则只需设置值,该怎么办?

我通过 ftp 服务器从客户端获取值。 有时这些文件包含垃圾值。 例如,电话号码如#3432838#9。 因此,在设置值之前,我需要删除那些垃圾字符。 我可以在 setter 方法中做到这一点吗? 这是一个有效的方法吗?

提前谢谢大家!

编辑:

这是否有效:

public void setSomething(String strValue){ 
     if(checkValidity(strValue)){ 
         // set the value 
     } else { 
         // set the value to an empty string
     }  
  }

Is it necessary for setter methods to have one argument? Usually setter methods accept one argument as the value of a certain property of an Object. What if I want to test first the validity which depends on another argument which is a boolean, if true, validate first, else just set the value.

I am getting the values from clients through ftp server. Sometimes those files contain garbage values. For instance, a phone number like #3432838#9. So before I set the value I need to remove those garbage characters. Can I do it in the setter methods? Is it a valid approach?

Thanks a bunch in advance!

EDIT:

Is this valid:

public void setSomething(String strValue){ 
     if(checkValidity(strValue)){ 
         // set the value 
     } else { 
         // set the value to an empty string
     }  
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

深者入戏 2024-07-16 08:14:11

在java bean框架模型中这是特别必要的,但一般来说不是强制性的。

当 setter 旨在“切换”某个值时,您可以使用不带参数的 setter。

void setCheck()

例如,可以将“check”布尔属性设置为 true。

因此,即使它不是 java bean 意义上的“setter”,您也可以想象 setter 用于其他目的。

另外,根据 JavaBean 规范第 7 节,setter 可以有多个参数,例如索引属性(索引属性支持一系列值。每当读取或写入该属性时,您只需指定一个索引来标识您想要的值。)

void setter(int index, PropertyType value); // indexed setter
void setter(PropertyType values[]); // array setter

在您的情况下,有效的方法是添加 函数签名的运行时异常
这样,您就不会为已经调用 setter 的所有其他类进行任何不必要的编译时异常检查。

或者,您可以将您的属性视为受约束属性并添加非运行时异常。

需要受约束的属性设置方法来支持 PropertyVetoException。
此文档向尝试更新的受限属性的用户提供
否决了。
因此,一个简单的约束属性可能如下所示:

PropertyType getFoo();
void setFoo(PropertyType value) throws PropertyVetoException;

允许在需要时添加 VetoableChangeListener。


关于您的代码片段,它是“有效的”,但可能不是最佳的,因为(如 这个问题):

  • 应在验证方法中将验证与 getter 或 setter 分开捕获。 这样,如果验证需要在多个组件之间重用,它是可用的。
  • 最好快速失败(因此我建议向 setter 添加异常)。

It is necessary specifically in the java bean framework model, but it s not mandatory in general.

You can have setter with no argument when they are meant to "swith" a value.

void setCheck()

could for instance be meant to set the "check" boolean attribute to true.

So even if it is not a "setter" in the java bean sense of the term, you can imagine setter used for other purposes.

Plus, according to section 7 of JavaBean specifications, a setter can have more than one argument, for instance for Indexed properties (An indexed property supports a range of values. Whenever the property is read or written you just specify an index to identify which value you want.)

void setter(int index, PropertyType value); // indexed setter
void setter(PropertyType values[]); // array setter

In your case, a valid approach would be to add a runtime exception to the signature of our function.
That way you do not put any unnecessary compilation-time exception checking for all of the other classes which are already calling your setter.

Or you could consider your property as a Constrained property and add a non-runtime exception.

Constrained property setter methods are required to support the PropertyVetoException.
This documents to the users of the constrained property that attempted updates may be
vetoed.
So a simple constrained property might look like:

PropertyType getFoo();
void setFoo(PropertyType value) throws PropertyVetoException;

which allows for VetoableChangeListener to be added if needed.


Regarding your snippet, it is "valid" but may not be optimal because (as said in this question):

  • Validation should be captured separately from getters or setters in a validation method. That way if the validation needs to be reused across multiple components, it is available.
  • It is better to fail fast (hence my proposition to add exception to the setter).
别低头,皇冠会掉 2024-07-16 08:14:11

通过 Java Bean 规范 setter 有一个参数。 如果您添加另一个,无论出于何种原因,它都不再被视为 setter。

Setter 对于“清理”其参数是完全有效的,如果无效则抛出异常。

By Java Bean specification setter have one argument. If you add another one, for whatever reason, it is not considered setter anymore.

Setter is perfectly valid to "clean up" its argument, or throw exception if is invalid.

熊抱啵儿 2024-07-16 08:14:11

为什么不。 验证和验证输入是包含在设置器中的一个很好的变体。 这里的问题是,如果您想允许在不验证的情况下设置成员。

可能您需要您使用的某些框架(用作 bean)的标准形式的 setter。 但如果你不受这种方式的限制,你可以尝试一下。

如果您认为其他代码应该进行验证但不应该设置错误的值,您也可以在 setter 中使用断言。

Why not. Verifying and validating the input is a good variant to include into the setter. The question here is, if you want to allow setting the member without validation.

Possibly you need the standard-form of the setter for some framework you use (usage as bean). But if you are not restricted in this way, you could try this.

You could also use asserts in the setter, if you think other code should do the validation but wrong values should never set.

难理解 2024-07-16 08:14:11

Joshua Bloch 所著的《Effective Java 第二版》(ISBN-13: 978-0-321-35668-0)一书中说,最好使用构建器模式而不是 bean 约定来创建对象。

例如( bean 模式):

NutritionFacts cocaCola = new NutritionFacts();
cocaCola.setServingSize(240);
cocaCola.setServings(8);
cocaCola.setCalories(100);
cocaCola.setSodium(35);
cocaCola.setCarbohydrate(27);

与构建器模式一起使用:

NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
   calories(100).
   sodium(35).
   carbohydrate(27).
   build();

构建器模式的实现:

// Builder Pattern
public class NutritionFacts {
    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;
    private final int sodium;
    private final int carbohydrate;
    public static class Builder {
        // Required parameters
        private final int servingSize;
        private final int servings;
        // Optional parameters - initialized to default values
        private int calories = 0;
        private int fat = 0;
        private int carbohydrate = 0;
        private int sodium = 0;
        public Builder(int servingSize, int servings) {
            this.servingSize = servingSize;
            this.servings = servings;
        }
        public Builder calories(int val)
        { calories = val; return this; }
        public Builder fat(int val)
        { fat = val; return this; }
        public Builder carbohydrate(int val)
        { carbohydrate = val; return this; }
        public Builder sodium(int val)
        { sodium = val; return this; }
        public NutritionFacts build() {
            return new NutritionFacts(this);
        }
    }
    private NutritionFacts(Builder builder) {
        servingSize = builder.servingSize;
        servings = builder.servings;
        calories = builder.calories;
        fat = builder.fat;
        sodium = builder.sodium;
        carbohydrate = builder.carbohydrate;
    }
}

当需要前两个参数时。
对于验证,您可以使用早期验证(在每个 方法中)或延迟验证(在 build() 方法中)。 其格式类似于 python 键值初始化。

In the book "Effective Java 2nd Edition" by Joshua Bloch (ISBN-13: 978-0-321-35668-0) saids that it's best to use the builder pattern than the bean convention for objects creations.

For instance (bean pattern):

NutritionFacts cocaCola = new NutritionFacts();
cocaCola.setServingSize(240);
cocaCola.setServings(8);
cocaCola.setCalories(100);
cocaCola.setSodium(35);
cocaCola.setCarbohydrate(27);

Usage with builder pattern:

NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
   calories(100).
   sodium(35).
   carbohydrate(27).
   build();

The implementation of builder pattern:

// Builder Pattern
public class NutritionFacts {
    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;
    private final int sodium;
    private final int carbohydrate;
    public static class Builder {
        // Required parameters
        private final int servingSize;
        private final int servings;
        // Optional parameters - initialized to default values
        private int calories = 0;
        private int fat = 0;
        private int carbohydrate = 0;
        private int sodium = 0;
        public Builder(int servingSize, int servings) {
            this.servingSize = servingSize;
            this.servings = servings;
        }
        public Builder calories(int val)
        { calories = val; return this; }
        public Builder fat(int val)
        { fat = val; return this; }
        public Builder carbohydrate(int val)
        { carbohydrate = val; return this; }
        public Builder sodium(int val)
        { sodium = val; return this; }
        public NutritionFacts build() {
            return new NutritionFacts(this);
        }
    }
    private NutritionFacts(Builder builder) {
        servingSize = builder.servingSize;
        servings = builder.servings;
        calories = builder.calories;
        fat = builder.fat;
        sodium = builder.sodium;
        carbohydrate = builder.carbohydrate;
    }
}

When the first two arguments ar required.
For validation you can use early validation (in each <field> method) or lazy validation (in the build() method). And the format is kind of python key-value initialization.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文