<p>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?</p>

<p>Specifically, I would like to avoid code similar to:</p>

<pre><code>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
}
</code></pre>

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

<p>I did find <a href="http://www.hickorysystems.com/sw_validation.html" rel="noreferrer">this</a>, 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?</p>

<p>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.</p>

[{'answer_id': 46035, 'author': 'Ben Scheirman', 'author_id': 3381, 'author_profile': 'https://Stackoverflow.com/users/3381', 'pm_score': 3, 'selected': False, 'text': '<p>I\'d return some type of ValidationSummary for each one... or an IList depending on how you want to structure it.</p>\n\n<p>you could also opt to do some magic like this:</p>\n\n<pre><code>using(var validation = new ValidationScope())\n{\n   ValidateTable1();\n   ValidateTable2();\n   ValidateTable3();\n\n   if(validation.Haserrors)\n   {\n       MessageBox.Show(validation.ValidationSummary);\n       return;\n   }\n\n   DoSomethingElse();\n}\n</code></pre>\n\n<p>then the ValidateTable would just reach into the current scope, like this:</p>\n\n<pre><code>ValidationScope.Current.AddError("col1", "Col1 should not be NULL");\n</code></pre>\n\n<p>something to that effect.</p>\n'}, {'answer_id': 72421, 'author': 'jerhinesmith', 'author_id': 1108, 'author_profile': 'https://Stackoverflow.com/users/1108', 'pm_score': 5, 'selected': True, 'text': '<p>Just an update on this: I decided to go with the <a href="http://en.wikipedia.org/wiki/Decorator_pattern" rel="noreferrer">Decorator pattern</a>.  That is, I have one \'generic\' table class that implements an <code>IValidateableTable</code> interface (which contains <code>validate()</code> method). Then, I created several validation decorators (that also <code>implement IValidateableTable</code>) which I can wrap around each table that I\'m trying to validate.</p>\n\n<p>So, the code ends up looking like this:</p>\n\n<pre><code>IValidateableTable table1 = new GenericTable(myDataSet);\ntable1 = new NonNullNonEmptyColumnValidator(table1, "ColumnA");\ntable1 = new ColumnValueValidator(table1, "ColumnB", "ExpectedValue");\n</code></pre>\n\n<p>Then, all I need to do is call <code>table1.Validate()</code> which unwinds through the decorators calling all of the needed validations.  So far, it seems to work really well, though I am still open to suggestions.</p>\n'}, {'answer_id': 111392, 'author': 'David Robbins', 'author_id': 19799, 'author_profile': 'https://Stackoverflow.com/users/19799', 'pm_score': 2, 'selected': False, 'text': '<p>Two approaches:  </p>\n\n<ol>\n<li><a href="http://www.lhotka.net/cslanet/Default.aspx#" rel="nofollow noreferrer">CSLA</a> where anonymous methods on business objects are used for validation.</li>\n<li>Read <a href="http://blog.jpboodhoo.com/HandlingDynamicRulesAPrecursor.aspx" rel="nofollow noreferrer">JP Boodhoo\'s</a> blog where he has implemented a rules engine and has very detailed posts and sample code published.  You can also see him at work on <a href="http://www.dnrtv.com/default.aspx?showNum=71" rel="nofollow noreferrer">DNR Tv</a> episode that\'s well worth watching.</li>\n</ol>\n'}, {'answer_id': 190640, 'author': 'Galghamon', 'author_id': 26511, 'author_profile': 'https://Stackoverflow.com/users/26511', 'pm_score': 1, 'selected': False, 'text': '<p>I think you are really talking about a concept called <a href="http://en.wikipedia.org/wiki/Database_constraints" rel="nofollow noreferrer">constraints</a> in the world of databases. Constraints are how a database guarantees the integrity of the data it contains. It makes much more sense to put this sort of logic in the database, rather than the application (even Access offers rudimentary forms of constraints, such as requiring uniqueness of values in a column, or values from a list, etc.).<br>\nInput validation (of individual fields) is of course a different matter, and any application should still perform that (to provide nice feedback to the user in case of problems), even if the DB has well-defined constraints of the table columns.</p>\n'}, {'answer_id': 44581032, 'author': 'Andres A.', 'author_id': 170945, 'author_profile': 'https://Stackoverflow.com/users/170945', 'pm_score': 2, 'selected': False, 'text': '<p>I would try with a combination of the Factory and Visitor patterns:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nnamespace Example2\n{\n    interface IVisitor\n    {\n        void Visit(Table1 table1);\n        void Visit(Table2 table2);\n    }\n\n    interface IVisitable\n    {\n        void Accept(IVisitor visitor);\n    }\n\n    interface ILog\n    {\n        void Verbose(string message);\n        void Debug(string messsage);\n        void Info(string message);\n        void Error(string message);\n        void Fatal(string message);\n    }\n\n    class Error\n    {\n        public string Message { get; set; }\n    }\n\n    class Table1 : IVisitable\n    {\n        public int Id { get; set; }\n        public string Data { get; set; }\n        private IList&lt;Table2&gt; InnerElements { get; } = new List&lt;Table2&gt;();\n\n        public void Accept(IVisitor visitor)\n        {\n            visitor.Visit(this);\n\n            foreach(var innerElement in InnerElements)\n                visitor.Visit(innerElement);\n        }\n    }\n\n    class Table2 : IVisitable\n    {\n        public int Id { get; set; }\n        public int Data { get; set; }\n\n        public void Accept(IVisitor visitor)\n        {\n            visitor.Visit(this);\n        }\n    }\n\n    class Validator : IVisitor\n    {\n        private readonly ILog log;\n        private readonly IRuleSet&lt;Table1&gt; table1Rules;\n        private readonly IRuleSet&lt;Table2&gt; table2Rules;\n\n        public Validator(ILog log, IRuleSet&lt;Table1&gt; table1Rules, IRuleSet&lt;Table2&gt; table2Rules)\n        {\n            this.log = log;\n            this.table1Rules = table1Rules;\n            this.table2Rules = table2Rules;\n        }\n\n        public void Visit(Table1 table1)\n        {\n            IEnumerable&lt;Error&gt; errors = table1Rules.EnforceOn(table1);\n\n            foreach (var error in errors)\n                log.Error(error.Message);\n        }\n\n        public void Visit(Table2 table2)\n        {\n            IEnumerable&lt;Error&gt; errors = table2Rules.EnforceOn(table2);\n\n            foreach (var error in errors)\n                log.Error(error.Message);\n        }\n    }\n\n    class RuleSets\n    {\n        private readonly IRuleSetFactory factory;\n\n        public RuleSets(IRuleSetFactory factory)\n        {\n            this.factory = factory;\n        }\n\n        public IRuleSet&lt;Table1&gt; RulesForTable1 =&gt;\n            factory.For&lt;Table1&gt;()\n                .AddRule(o =&gt; string.IsNullOrEmpty(o.Data), "Data1 is null or empty")\n                .AddRule(o =&gt; o.Data.Length &lt; 10, "Data1 is too short")\n                .AddRule(o =&gt; o.Data.Length &gt; 26, "Data1 is too long");\n\n        public IRuleSet&lt;Table2&gt; RulesForTable2 =&gt;\n            factory.For&lt;Table2&gt;()\n                .AddRule(o =&gt; o.Data &lt; 0, "Data2 is negative")\n                .AddRule(o =&gt; o.Data &gt; 10, "Data2 is too big");\n    }\n\n    interface IRuleSetFactory\n    {\n        IRuleSet&lt;T&gt; For&lt;T&gt;();\n    }\n\n    interface IRuleSet&lt;T&gt;\n    {\n        IEnumerable&lt;Error&gt; EnforceOn(T obj);\n        IRuleSet&lt;T&gt; AddRule(Func&lt;T, bool&gt; rule, string description);\n    }\n\n    class Program\n    {\n        void Run()\n        {\n            var log = new ConsoleLogger();\n            var factory = new SimpleRules();\n            var rules = new RuleSets(factory);\n            var validator = new Validator(log, rules.RulesForTable1, rules.RulesForTable2);\n\n            var toValidate = new List&lt;IVisitable&gt;();\n            toValidate.Add(new Table1());\n            toValidate.Add(new Table2());\n\n            foreach (var validatable in toValidate)\n                validatable.Accept(validator);\n        }\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/46029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1108/']