I have an object that represents physics characteristics of some air tunnel:
public class Tunnel
{
public double Length { get; set; }
public double CrossSectionArea { get; set; }
public double AirDensity { get; set; }
public double Pressure { get; set; }
//...
}
I need to check correctness of parameters: for example, Length must be > 0
, Pressure >= 0
and so on. The first idea was just to put checking to property accessor and throw exception on invalid data:
public class Tunnel
{
private double length;
public double Length
{
get { return length; }
set
{
if (value <= 0)
throw new TunnelParametersException("Invalid data");
length = value;
}
//...
}
But I have a collection of such object and it will be serialized/deserialized to/from XML-file. So the problem is that it will not work with serialization (if I'm not mistaken). User can edit file and enter whatever he want and I will not able to catch it.
So, as I understand, need to create some function (in Tunnel
class or in another one) that I will call to check that all values are correct. But here another problem: Tunnel
can have few invalid parameters. How should I return errors and process them? The program must return all found errors in one call. And this way is good for only my own use of classes. I probably can't obligate another programmer to use validation after every editing of data.
Give me please an advice how would be more correct to implement such checking of values and solve my problem - maybe some another flexible way so would be easy to manage and improve this code in the future. Thank you.
EDIT: Returning to my first idea, is there any way to validate data during or after serialization?
Simplest possible way:
//Returns empty list if no errors.
public List<TunnelErrors> Validate()
{
//Validate params
}