Java 我可以在 setter 方法中编写验证逻辑吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20378045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:30:10  来源:igfitidea点击:

Can I write validation logic in setter methods?

javaoopencapsulation

提问by Mac

Are setter methods only used to set the value of attributes as it is passed as argument? Can we write some validation logic before assigning the value to the attributes?

setter 方法是否仅用于设置作为参数传递的属性值?我们可以在将值分配给属性之前编写一些验证逻辑吗?

采纳答案by Jeroen Vannevel

Yes, validation logic is definitely acceptable.

是的,验证逻辑绝对可以接受。

It should be noted though that if you have extensive validation you might want to extract this to a specific validator service. But for simple validations you can safely do this.

但应该注意的是,如果您有广泛的验证,您可能希望将其提取到特定的验证器服务。但是对于简单的验证,您可以安全地执行此操作。

The entire idea behind using getters & setters is so nobody will have direct access to your fields. If you just wanted to set/get the value, you can make them public.

使用 getter 和 setter 背后的整个想法是,没有人可以直接访问您的字段。如果你只是想设置/获取值,你可以 make them public

Instead, we use setters to validate the incoming data and see if it complies with the rules we set.

相反,我们使用 setter 来验证传入的数据并查看它是否符合我们设置的规则。

This concept is also called "Encapsulation", a cornerstone of Object-Oriented Programming.

这个概念也称为“封装”,是面向对象编程的基石。

回答by NPE

Sure, there's nothing wrong with making setters only accept valid values.

当然,让 setter 只接受有效值并没有错。

回答by halileohalilei

It is actually encouraged to validate the input (check whether it fits your data abstraction) to your setter method, so yes you can.

实际上鼓励验证输入(检查它是否适合您的数据抽象)到您的 setter 方法,所以是的,您可以。

回答by Balduz

Yes, you can add validation logic in your setter attributes before assigning the values. In fact, you must do it if it is possible that unwanted values may be sent to the setters.

是的,您可以在分配值之前在 setter 属性中添加验证逻辑。事实上,如果不想要的值可能会被发送到 setter,你就必须这样做。

回答by Dropout

Sure. You can include a validation. It is acceptable, but not neccessary. You just have to take into account that if you don't validate it then any values will try to get set to the variable (meeting the data type requirements).

当然。您可以包含验证。这是可以接受的,但不是必需的。您只需要考虑到,如果您不验证它,那么任何值都将尝试设置为变量(满足数据类型要求)。

Basically if you have

基本上如果你有

public void setNickname(String nick)
{
    this.nickname = nick;
}

and you want to validate it you can either do it inside the setter - for example

并且您想验证它,您可以在 setter 中执行它 - 例如

public void setNickname(String nick)
{
    if(nick.matches("[a-zA-Z]+"){ // only letters
        this.nickname = nick;
    }else{
        // react
    }
}

or outside of the setter before using it

或在使用之前在 setter 之外

if(nick.matches("[a-zA-Z]+"){ // only letters
    account.setNickname(nick);
}

or you can use a method to validate it or even a separate validator class. There are a lot of possibilities.

或者您可以使用一种方法来验证它,甚至是一个单独的验证器类。有很多可能性。

You don't have to be afraid of developers being dazzled by this, like some say here.

你不必害怕开发人员会被这件事弄得眼花缭乱,就像这里的一些人所说的那样。

回答by Tomás

There is absolutely nothing stopping you from doing any kind of other operation inside a setter of a property. You could do anything from validation to setting the value of some other property etc. etc. Thats not to say you should however. Use your good judgement and common sense to decide what to put in there. If the setter is bulked out with innumerable lines of code then you should question your program structure...

绝对没有什么可以阻止您在属性的 setter 中执行任何类型的其他操作。你可以做任何事情,从验证到设置其他属性的值等等。但这并不是说你应该这样做。使用您良好的判断力和常识来决定在那里放什么。如果 setter 被无数行代码填满,那么你应该质疑你的程序结构......

回答by Marcin Szymczak

As long as you do not modify other fields of class it is correct to validate.

只要您不修改类的其他字段,验证就是正确的。

You should also consider removing setters and using constructor with valitation or builder in Joshua Bloh version

您还应该考虑在JoshuaBloh版本中删除 setter 并使用带有验证或构建器的构造函数