Reputation: 33
Suppose you have a private variable like so
private int _x;
And you have a property that provides external access to this variable:
public int X
{
get
{
return _x;
}
set
{
_x = value;
}
}
Is it better to put "validation" logic (value non-negative, within bounds, etc) in the getter portion or the setter portion? It seems like it might be acceptable in either, but is there a preferred option?
Upvotes: 3
Views: 6264
Reputation: 5787
Validation should be called first. If you want to use this approach you should implement your logic in set
clause.
If you want create nice clean code, you should consider dedicated method for it, e.g.:
public class Test
{
public int X { get; private set; }
public void SetX(int value)
{
//... your logic, throw exception if validation failed
X = value;
}
}
Your class should keep your object in valid state.
Upvotes: 1
Reputation: 172220
The validation logic should be in the setter, to prevent invalid data from even reaching _x
. That way, you have a useful invariant in your class: _x
will always contain a valid value.
The idiomatic way to perform validation is to throw an ArgumentException or any of its subclasses when the consuming code tries to assign an invalid value to X
.
Upvotes: 2
Reputation:
You want your code to fail as quickly as possible, which is at the point you try to set an invalid value.
When you fail in the setter, the user knows about the problem immediately, and can fix it. If you wait until they try to retrieve the value, you are waiting too late, and the user may have no idea what went wrong, or where.
If the invalid value gets used elsewhere in the code, you are propagating bad data throughout the application, making things much worse, and even less clear to the user what went wrong.
Upvotes: 3
Reputation: 1151
The setter is preferred, for the following reason: It is better to throw and exception or display a message to the user upon inputting a garbage value, rather than allowing the garbage value, and subjecting your class to internal bad data.
You will note that the MSDN Example uses the setter for input validation.
Upvotes: 3