数据验证设计模式 [英] Data Validation Design Patterns

查看:365
本文介绍了数据验证设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有数据库表的集合(例如在Access文件中),并且需要根据具有所有表的两个常规规则的规则集以及特定于一个或多个表的特定规则来验证此集合中的每个表有一个表的子集,有人可以推荐一个好的设计模式来研究吗?

If I have a collection of database tables (in an Access file, for example) and need to validate each table in this collection against a rule set that has both common rules across all tables as well as individual rules specific to one or a subset of tables, can someone recommend a good design pattern to look into?

具体来说,我想避免代码类似于:

Specifically, I would like to avoid code similar to:

void Main()
{
    ValidateTable1();
    ValidateTable2();
    ValidateTable3();
}

private void ValidateTable1()
{
    //Table1 validation code goes here
}

private void ValidateTable2()
{
    //Table2 validation code goes here
}

private void ValidateTable3()
{
    //Table3 validation code goes here
}

此外,我决定使用log4net来记录所有错误和警告,所以每个方法都可以被声明为 void ,不需要返回任何东西。这是一个好主意,或者最好创建一些 ValidationException ,捕获所有异常并将它们存储在 List< ValidationException> 在打印结束之前全部打印出来?

Also, I've decided to use log4net to log all of the errors and warnings, so that each method can be declared void and doesn't need to return anything. Is this a good idea or would it be better to create some sort of ValidationException that catches all exceptions and stores them in a List<ValidationException> before printing them all out at the end?

我找到了这个,看起来可能会起作用,但我希望能够实际找到一些代码示例。有什么建议么?有没有人在过去做过类似的事情?

I did find this, which looks like it may work, but I'm hoping to actually find some code samples to work off of. Any suggestions? Has anyone done something similar in the past?

对于某些背景,程序将被编写在C#或VB.NET中,表将更可能存储在Access或SQL Server CE。

For some background, the program will be written in either C# or VB.NET and the tables will more than likely be stored in either Access or SQL Server CE.

推荐答案

只是一个更新:我决定用装饰图案。也就是说,我有一个通用表类实现了一个IValidateableTable接口(包含一个 Validate()方法,然后我创建了几个验证装饰器(也实现了IValidateableTable)我可以绕过我要验证的每个表。

Just an update on this: I decided to go with the Decorator pattern. That is, I have one 'generic' table class that implements an IValidateableTable interface (that contains a Validate() method. I then created several validation decorators (that also implement IValidateableTable) that I can wrap around each table that I'm trying to validate.

所以,代码最终看起来像这样:

So, the code ends up looking like this:

IValidateableTable table1 = new GenericTable(myDataSet);
table1 = new NonNullNonEmptyColumnValidator(table1, "ColumnA");
table1 = new ColumnValueValidator(table1, "ColumnB", "ExpectedValue");

然后,我需要做的就是调用 table1.Validate()通过调用所有需要的验证的装饰器来解开,到目前为止,它似乎工作得很好,虽然我仍然可以接受建议。

Then, all I need to do is call table1.Validate() which unwinds through the decorators calling all of the needed validations. So far it seems to be working really well, though I am still open to suggestions.

这篇关于数据验证设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆