views:

97

answers:

4

Hi,

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

+4  A: 

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

Marco
Don't think that[StringLength(10, ErrorMessage="Too long")]public string FirstName { get; set; }Realy is more discoverable thanpublic string FirstName { get{ return firstName} set{ Enforce.StringLength(value, 10, "Too long"); firstName = value;}}although it is less code :)(edit)Can't SO have formatted comments?
PiRX
Just to add to Marco's answer, this can lead to many possibilities such as static analysis (compile time), document generation etc.
VinayC
@PiRX, agree with you to some extent. In theory, aspect based/declarative way cleans up the code from concerns that can be externalized. Whether .NET attributes fits the bill may be debatable.
VinayC
@PiRX - The difference is that an attribute is freely available metadata, while the Enforce.StringLength is a hidden implementation, and as such, the attribute can be used for things like automatic form validation. ASP.NET MVC does that if you create a form from a model that has attributes like that.
JulianR
@JulianR, actually I think it's main point of using attributes - you can allow other (sub)systems take control of some aspects.
PiRX
+1  A: 

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.

rockinthesixstring
A: 

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.

PiRX
A: 

One thing to consider when using attributes is because they are discoverable you can use them to add business level client side validation.

Kyle