Data constraints in a multi-tier application
I'm wondering about what are the best practises, particularly in a .NET world for this kind of scenario, which must be pretty common. My goals are to a) have decent performance and b) have as few instances of separate (but identical) constant values as possible. Here's the scenario:
- You have a database with some tables, and say a table has a varchar column with a maximum length of 255 characters. All good so far! (Constant count = 1)
- You then create a .NET 2.0 DataSet with TableAdapters for that table, so now the DataSet also knows that the column has a MaxLength of 255. (Constant count = 2)
- You now create a business object which has a property which also maps to the same column (and would be persisted by passing it back through the DataSet/TableAdapter from step 2). You add checks to this property to ensure it also never gets larger than the maximum length allowed. (Constant count = 3)
- You create a web form (or a Windows Forms for that matter) that has a text field for the user to edit the same column. You set the maxlength attribute of that text field so the browser restricts the user to the size limit for that field. You also add a server-side validator to validate the text field and enforce that size limit (just in case their web browser ignores the maxlength attribute). (Constant count = 4)
We've managed to embed the value '255' at least 4 times in our application! While that may not bother some people, it it does annoy me. The concept of having a single constant that represents a value and allows you to easily change the value in one place should you need to is something I've adopted for a long time.
So how can we reduce this down?
Assuming that we're going to stick with a normal relational database and keep the limit for the column there, then that's one instance we can't remove.
It is true that we could use database queries to retrieve that value and use it all over our app, but I'm pretty sure the performance for that would not be ideal, and it does mean that some potential compile-time checks might be missed.
If you assume that your UI tier only talks to the business layer, and the business layer is the only thing that talks to the data layer, what is the best way to percolate through these kind of values with as few separate constants as possible? If I change the length of the column in the database, I want to change as few constants in my code as possible, so that there's less chance I miss one and cause a problem with the application.
I'd be interested in other people's thoughts, or if anyone has links to content that covers this topic.