Environment:
Windows 2008, VS 2008 SP1, asp.net MVC 1.0
------------------------------------------------------------------------------
Tea watching tonight, the mind suddenly flashed a thought, so open vs simple to do a realization, so with this article ... It's about entity validation, well, start from the beginning.
One. Probably the most original validation code
To make the problem as simple as possible, let's take a simple user class.
Now we're going to add a method to the user class to verify the legality of the user instance, and I believe a lot of people wrote the following code like this:
The Check () method simply applies a variety of rules to the properties of the user class, and then returns an illegal set of hints.
Validation is just a simple call to the entity check () method:
Well, I admit, it seems to be enough in general, but many people see a series of if may start to freak out, yes, I don't like it, then think of the most even way to eliminate them.
Two. An attempt based on the new characteristics of c#3.0
To eliminate if, consider linking those validation rules to a single line, so:
The validation extension methods for writing entity classes are as follows:
Then the check () method for the entity is changed to:
In this way, we eliminate the If by extending the method, but we link the validation rules and throw out the illegal information in an unusual way, so each validation can only get a single validation message, which is often not in line with the actual situation. Think about it.
Three. Continue to evolve
Then, to get a collection of validation error messages, improve:
To make the code look more like that, add a base class to the entity, called EntityBase.
Then write a validation class:
Then look at the modified check () method, and the validation class works at a glance:
No need to explain? In fact, it's also a chain, return the validation error message collection and see the results:
See here, you may say: "What, do not eliminate an If, what a big deal."
Uh ... Yes.. It's true ... Tricks, if there is a similarity, is purely coincidental.