I want to do validation on my business code. I'm thinking on 2 ways to do this.
One, do the validation on my class property setters in the following fashion
class Student{
public string Name{
get { return _name; }
set {
if (value.IsNullOrEmpty) throw exception ...
}
}
}
Now, the problem with this approach is that, validation code is run every time Name gets assigned, which we may not need, like when fill it in with data from DB.
Two, which I prefer, put static methods on these entity classes, like
class Student{
public **static** void ValidateName(**string name**) {
if (string.IsNullorEmpty(name))
{
throw ...
}
...
}
Notice I'm using a static method instead of a instance method, like class Student{
public void Validate() {
// validation logic on instance properties
if (string.IsNullorEmpty(Name))
{
throw ...
}
...
}
is because I'm not always getting a Student obj passed in, I do get primitive types like string name passed into a method often time, like
public static FindStudentByName(string name) { // here I want to first do validation Student.ValidateName(name);
// qeury DB
...
}
If I do get passed in a student obj, then of course I can do
public static AddStudent(Student s) {
// call the instance method
s.Validate();
}
Now, I'd like to keep things very simple, so I don't want to go any one of the following approaches
Use attributes on properties, like [StringLength(25)].
One, because this requires Reflection and affects performance, there are tricks to get performance hit low, but again I want to keep it simpler the better.
Two, I want my site to be able to run in Medium Trust. As reflection as I understand it requires Full Trust.
Use any of the Validation Blocks out there, like MS. Enterprise Library etc found on CodePlex.
Now, I want to get your opinion on this,
what are some of the potential problems with the approach I'm going with?
Would this approach perform better, more readable, easier to maintain than the other approaches?
How are you doing validation on your middle tier?
Thank a bunch!
Ray.