views:

93

answers:

3

This is mostly a request for comments if there is a reason I should not go down this road.

I have a multi-tierd, CodeSmith generated application. At the UI level there need to be some fields that are required, and the required fields will vary depending on field values in the bound entity. What I am thinking of doing is adding a "PropertyRequired" CustomAttribute to each property in the entities that I can set true or false when I load the entity in its manager. Then I will use Reflection to query the property and give visual feedback to the user at the UI level, and I can validate that all the required properties have a valid value in the manager before I save. I've worked this out as a proof of concept with one property in one entity, but before I try to extend it to the rest of the application I'd like to ask if there is someone with more experience to either tell me to go for it, or why I won't like it when I scale up. If this is a bad idea, or if you can suggest a better approach please offer your opinion.

+3  A: 

It is a pretty reasonable way to do it (I've done something very similar before) - but there are always downsides:

  • any code needing the entity will need the extra reference (assuming that the attribute and entity are in different assemblies)
  • the values (unless you are clever about it) must be determined at compile-time
  • you can't use it on entities outside of your control

In most cases the above aren't a problem. If they are an issue, you might want to support an external metadata model - but unless you need it, this would be overkill. Don't do it unless you must (meaning: go ahead and use attributes; they are usually fine).

Marc Gravell
+1  A: 

There is no inherent reason to avoid custom attributes. It is a supported CLR feature which is the backbone for many available products (Code Contracts, FxCop, etc ...).

JaredPar
A: 

This is not an unreasonable approach and healthier than baking this stuff into a UI tier. There are a couple of points worth considering before taking the full dive:

  • You are tightly coupling business logic with the business entity itself. Are there circumstances where a field being required or valid values could change? You may be limiting yourself or be faced with an inconsistent validation mechanism
  • Dynamic assignment is possible but more tricky - i.e. when you set a field to be required thats what it will be unless you override
  • Custom attributes can be quite inflexible if further down the line you wanted to do something more complicated - namely if you need to pass state into an attribute driven validation scheme. Attributes like declarative assignment. Only having a true/false required property shouldn't be an issue here though

Just being a devils advocate really, in general for a fairly simple application where you only care about required fields, this is quite a tidy way of doing it

dbez