Home » Questions » Computers [ Ask a new question ]

Data verifications in Getter/Setter or elsewhere?

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

Asked by: Guest | Views: 38
Total answers/comments: 4
Guest [Entry]

"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."""
Guest [Entry]

"@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."
Guest [Entry]

"It depends.

Generally, code should fail fast. If the value can be set by multiple points in the code and you validate only on after retrieving the value, the bug appears to be in the code that does the update. If the setters validate the input, you know what code is trying to set invalid values."
Guest [Entry]

"From the perspective of having the most maintainable code, I think you should do as much validation as you can in the setter of a property. This way you won't be caching or otherwise dealing with invalid data.

After all, this is what properties are meant for. If all you have is a bunch of properties like...

public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}

... they might as well be fields"