开发者

What are the advantages of attribute based programming?

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 fashione开发者_如何学God way" ?

Thanks,

Scott


Because the constraint is discoverable without having to execute the code. With reflection you can access these constraints.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜