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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With