在类中实现验证的最佳方式

本文关键字:最佳 方式 验证 实现 | 更新日期: 2024-06-14 08:34:53

我的应用程序中存在设计问题。我有一个类,其中的字段具有某种业务逻辑验证。这个类以两种方式实例化并填充数据。。第一:由类的使用者:从前端发送并填充到对象中并保存在数据库中的数据。第二:获取存储的数据时。在第二个要求中,我有一个问题。我不想验证数据,因为由于删除或修改现有数据,存储的数据可能不符合业务逻辑。因此,我需要在没有验证的情况下用保存的数据填充对象。

因此,请建议我在类中添加验证逻辑的最佳方法,这样当它用于数据保存时,就应该对它进行验证,而在获取数据时,如果数据库表中存在键字段,就不应该验证任何字段。例如:

class customer
{
    private string customerCode;
    private string customerName;
    private List<Project> projectList;
    //These property contains validation logic for data assigned to them.
    public string CustomerCode{get; set;}
    public string CustomerName{get; set;}
    public List<Project> projectList{get;set;};
    public bool SetData(ref string message)
    {
        //Fetch From Database and set it to fields.
        //Here to avoid validation I can use fields directly to skip validation.
        this.CustomerCode = DataTable[CustomerCode];
        this.CustomerName = DataTable[CustomerName];
        //But here its not possbible to skip validation in Project class
        foreach(projectID in DataTable[Projects])
        {
            //**Problem Area**.... every project I add is validated according to business logic, but it may be possible that even after completion of a project users of the system want to list all the projects of that customer.
            this.ProjectList.Add(new Project(projectID));
        }
    }
}

在类中实现验证的最佳方式

查看问题的一种更通用的方法是让一个对象具有两种验证策略。在这种情况下,你说第二种策略是忽略任何验证。然而,在未来,您可能会发现添加一些次要或辅助验证是有用的,因此有了更通用的方法的想法。正如Davis Osborne所建议的,验证对象的最佳方法是创建特定的验证类。总之,我将创建两个验证对象,并根据上下文使用合适的对象来验证我的对象。通过这种方式,您的方法将准备使用您将来碰巧包含的任何验证,您只需要更新设计的验证方面。

创建一个位于公共接口后面的特定验证器。然后,如果需要此策略,可以对其进行单元测试并可能进行替换,以提供自定义验证场景。

为验证类作为一个整体和每个属性提供支持。