Suppose I have a class like this
class A
{
private int _x; //must be between [-10 10]
private int _y; //must be between [10 20]
}
Using properties I have a couple of variants for the variables
public int X
{
get { return _x; }
set
{
if (!(value >= -10 && value <= 10))
throw new Exception("Some error text");
_x = value;
}
}
or
public int X
{
get { return _x; }
set
{
if (!(value >= -10 && value <= 10))
return;
_x = value;
}
}
(same for _y).
In first case I’m not sure I want to use exceptions (they are slow and have other known problems). In second I’m paying for not using them with the ambiguity of values (in some different way for _x and _y).
Obviously I can use in my situation (if dealing with a list of objects) smth like that
public bool IsValid = true;
//...
public int X
{
get { return _x; }
set
{
if (!(value >= -10 && value <= 10))
{
IsValid = false;
return;
}
_x = value;
}
}
class AWrapper
{
public List<A> AList {get; set;}
public AWrapper(List<A> list)
{
AList = list.Where(x => x.IsValid == true).ToList();
}
}
or some validator class or… I guess some other things. So I just want to form the criteria for myself – which technique is better and when…