在Getter/Setter或其他地方进行数据验证? [英] Data verifications in Getter/Setter or elsewhere?

查看:80
本文介绍了在Getter/Setter或其他地方进行数据验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在 getters setters 或代码的其他地方进行验证是个好主意.

对于优化加速代码,这可能会让您感到惊讶,我认为您不应该在getter和setter中进行验证,而应该在代码中进行验证您正在更新文件或数据库.我错了吗?

解决方案

好,为什么类通常包含带有公共getter/setter的私有成员的原因之一就是因为它们可以验证数据.

如果您的数字大于或等于1到100,我肯定会在setter中放入一些内容进行验证,然后抛出代码捕获的异常.原因很简单:如果您未在设置器中执行此操作,则每次设置时都必须记住1到100个限制,这会导致代码重复或忘记时会导致无效状态. /p>

关于性能,我在这里与Knuth在一起

我们应该忘记效率低下的问题,大约有97%的时间是这样:过早的优化是万恶之源."

I'm wondering if it's a good idea to make verifications in getters and setters, or elsewhere in the code.

This might surprise you be when it comes to optimizations and speeding up the code, I think you should not make verifications in getters and setters, but in the code where you're updating your files or database. Am I wrong?

解决方案

Well, one of the reaons why classes usually contain private members with public getters/setters is exactly because they can verify data.

If you have a Number than can be between 1 and 100, i would definitely put something in the setter that validates that and then maybe throw an exception that is being caught by the code. The reason is simple: If you don't do it in the setter, you have to remember that 1 to 100 limitation every time you set it, which leads to duplicated code or when you forget it, it leads to an invalid state.

As for performance, i'm with Knuth here:

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."

这篇关于在Getter/Setter或其他地方进行数据验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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