开发者

Implementation of class data validation

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 wa开发者_高级运维s 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
}


What comes into my mind is this.

I would keep a readonly IsValid property. On the getter I would do all my validation and say true or false.

In any place where I use the object I would would check to see if the object.IsValid is true.


try making your files pass through a wrapper function everytime, and making the files on disk read-only for normal user,i.e, if the user has to edit the file he does so only through your program, when the user is finished editing u pass all the data through your function to see if the whole data is still valid or not,


For the edit : make the serialization streams pass through a sort-of buffer function,that processes the data before serialization or during it, depending on which way is easier to implement, if you chose the former, the data will first be validated(the return type and parameter type will be same) and then be serialized, otherwise the data will be checked as it is converted..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜