Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Properties: Validation in getters or setters?

Tags:

c#

properties

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?

like image 635
Gaston Gilbert Avatar asked Dec 14 '22 01:12

Gaston Gilbert


2 Answers

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.

like image 152
vbnet3d Avatar answered Dec 16 '22 15:12

vbnet3d


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.

like image 45
PhillipXT Avatar answered Dec 16 '22 15:12

PhillipXT