Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data verifications in Getter/Setter or elsewhere?

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?

like image 475
TiTi Avatar asked Aug 05 '08 19:08

TiTi


2 Answers

Well, one of the reasons 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."

like image 133
Michael Stum Avatar answered Nov 04 '22 09:11

Michael Stum


@Terrapin, re:

If all you have is a bunch of [simple public set/get] properties ... they might as well be fields

Properties have other advantages over fields. They're a more explicit contract, they're serialized, they can be debugged later, they're a nice place for extension through inheritance. The clunkier syntax is an accidental complexity -- .net 3.5 for example overcomes this.

A common (and flawed) practice is to start with public fields, and turn them into properties later, on an 'as needed' basis. This breaks your contract with anyone who consumes your class, so it's best to start with properties.

like image 43
Leon Bambrick Avatar answered Nov 04 '22 09:11

Leon Bambrick