C# Is there a reason not to put functionality inside an Attribute class?

274 Views Asked by At

I'm writing an attribute which marks a method so that it can be displayed as a button that calls the method when clicked.

It seems appropriate that the attribute should be given the MethodInfo of the method I get it off, and that it can draw itself on screen and call that method when it gets clicked. That way the class is nice and self contained.

But I've never seen an attribute class that contains its actual functionality. They're always just data containers which are used by other classes.

Is there an actual performance related reason why functionality should be kept out of attribute classes?

2

There are 2 best solutions below

0
On BEST ANSWER

No, there's no performance related reason per se. It's more that attributes are meant as a way to add additional, declarative metadata for use with reflection.

One reason to not put too much functionality into an attribute is often that they only accept compile-time constants in the constructor(s), so you won't get constructor dependency injection. This is often solved by using method injection of dependencies instead.

ASP.NET MVC does this for their AuthorizationFilterAttribute and its derived attributes. You can take a look at different attributes with "behavior" in ASP.NET's filters test website here.

0
On

There is no technical reason why you can't put code in attribute classes. However, there are semantic reasons not to.

Attributes are metadata, ie they are declarative. Declarative information says what's required, not how it should be achieved.

Code on the other hand is procedural information; it describes how something is to happen.

Again whilst there's no technical reason why you can't mix declarative and procedural information, it can be seen as bad practice. The reasons for this are that mixing the two can make the code harder to read, harder to test and harder to maintain. These aren't guaranteed to happen, but more effort tends to have to be put in to avoid these problems than if the two are kept separate.

Events, such as a button click, are declarative and so your idea of using attributes for event handling fits the declarative model. It might be wiser though to put the event-handling, procedural, code in separate classes.