What are the advantages of attribute based programming?
-
26-09-2019 - |
Question
I am working with WCF RIA services and have come across a sample using attributes:
[StringLength(10, ErrorMessage="Too long")]
public string FirstName { get; set; }
...
While attributes aren't restricted to WCF RIA, it reminded me of a question: why is declarative or attribute based programming perferable to coding a validation routine "the old fashioned way" ?
Thanks,
Scott
Solution
Because the constraint is discoverable without having to execute the code. With reflection you can access these constraints.
OTHER TIPS
The biggest benefit is re-usability. It's great to be able to set it once (Name, Required, Regex, etc) and then use it in your WCF app, as well as your MVC app, and everything stays consistent.
It's not that attribute based programming is superior than "old fashioned way" validation. In general:
- It looks cleaner (at least to me)
- It's a bit easier to slap attribute atop method/property than find place where to put code validation
Otherwise there is no big difference between both approaches.
One thing to consider when using attributes is because they are discoverable you can use them to add business level client side validation.