A simple Business Rules Manager
I read a seriously cool article today on Msdn about creating a "Rules Manager". In it, Rockford Lhotka demonstrates how to create a central controller for validation rules. The rules manager allows you to create rules at all sorts of levels and helps to abstract the task of managing validation away from individual Forms so that the validation logic is all in one place. As an example of this, imagine creating a "Human" class and assigning some rules such as:
- Name must not be empty
- Date Of Birth must be earlier than Date Of Death
Now, when you come to use a Human in the application you can simply write validation code such as:
myPerson.CheckRules() If myPerson.IsValid() Then ... Else For Each brokenRule As Rule In myPerson.BrokenRules ... Next End If
You could also add Rules at Form level which would allow you to create complex associations between arbitrary objects.
One of the really neat things about this article is that it demonstrates some excellent, real-world use of Delegates and Reflection. I might write about those some more tomorrow, but, one of the things that opened my eyes was the use of the Visual Basic CallByName
method. CallByName
is a function which allows you to invoke members on objects. Those objects can be anything... Forms, Controls, Custom Classes, etc.
Here is a small demo using CallByName which invokes a method on a custom class:
' When the MyForm Form loads the CallByName function ' is called on an instance of the Foo class passing ' an argument to the Speak method. Public Class MyForm Inherits System.Windows.Forms.Form Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim foo As New Foo CallByName(foo, "Speak", CallType.Method, New String() {"Hello World"}) End Sub End Class Public Class Foo Public Sub Speak(ByVal theWord As String) MessageBox.Show(theWord) End Sub End Class
Related Items
A Simple Business Rules Manager
CallByName documentation