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

Was it helpful?

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:

  1. It looks cleaner (at least to me)
  2. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top