我可以在setter方法中编写验证逻辑吗? [英] Can I write validation logic in setter methods?

查看:97
本文介绍了我可以在setter方法中编写验证逻辑吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

是的,验证逻辑肯定是可以接受的。

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.

使用getter& setter是如此,没有人可以直接访问你的领域。如果您只想设置/获取值,可以将它们设为 public

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.

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

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

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

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

这篇关于我可以在setter方法中编写验证逻辑吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆