Data verifications in Getter/Setter or elsewhere?

2020-02-10 22:45发布

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?

8条回答
Deceive 欺骗
2楼-- · 2020-02-10 23:45

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."

查看更多
萌系小妹纸
3楼-- · 2020-02-10 23:50

I try to never let my objects enter an invalid state, so setters definitely would have validation as well as any methods that change state. This way, I never have to worry that the object I'm dealing with is invalid. If you keep your methods as validation boundaries, then you never have to worry about validation frameworks and IsValid() method calls sprinkled all over the place.

查看更多
登录 后发表回答