I’ve been using Data Annotations recently. For those of you outside the .NET world, Data Annotations are Attributes that bind validation and display rules to your model properties. Some examples of basic validation annotations would be
And the display attributes would be
Each validation message has an optional error message that appears to the right of the invalid field along with an optional summary at the top of the page.
Rethinking nTier Applications
At first I winced at some of the display attributes because they are ultimately writing HTML from the data layer, which seems like a violation of tier separation since html is part of the display layer. But looking at the simplicity, reuse and consistency this system provides, it just makes sense.
Employing convention over configuration, the data layer can set many overridable features that would traditionally be considered business layer or display layer. Likewise, the business layer can override the data layer with more specific display names if the model is used by several business layer. The display layer could do the same. The nice thing is that 90% of the time, default values don’t need to be overridden.
You have a User entity with a Name property.
Your data layer might provide a display name of “User Name”. This value appears in the label next to the input on the page.
Lets say you have business objects called Employee and Supervisor, which inherits from User. Supervisor may wish to override this display name as “Supervisor Name” but Employee might just want to go with the default. Additionally, you might have 50 pages which use various combinations of Employee and Supervisor that could override these display names as needed.
You might be asking, what’s the point? Why not always define label text in the html page where it belongs? I felt the same way, but html pages are generally not reusable, so you may end up repeating the word “Supervisor” 50 times, then your client could ask you to change it to “Manager” (this actually happened). You can do a global find-replace, or just have a few inconsistencies. But in the practical world, the data layer provides a central location for any information that gets repeated throughout your application, allowing more consistency in your Display layer.
Potential IDE Improvements
Because these features are finite and provide predefined options for most of what you need (like a regex for email), I could easily foresee the next iteration of Entity Framework providing a GUI interface to attach these attributes to entity properties in the ORM. In fact, much of this information, such as required, data type and string length, are included in the ORM, but they don’t percolate up to client-side validation. It may have been a design decision on their part or they may have just run out of time. The point is, I don’t think basic validation is going to be something developers will have to spend much (if any) time coding in the near future.