Attributes – The New Macros ?

Do you remember the times when C++ was the mainstream programming language in enterprise level projects ?
A popular approach was to simplify the code by defining a lot of macros.
Even Microsoft did that very extensively in their MFC implementation for instance in their ubiquitous messagemaps.
The benefit was an easy progamming model – just add a few macros and be happy.
On the other hand it was very difficult to understand what really happened in the background.
This was especially true for user defined macros which could only be used in the context of a certain project.

Later languages like Java and C# took over and macros became history (C# has a preprocessor but no macros). The nightmare was over.
Todays software systems aren’t easier than in the past. Therefore the language engineers considered it to be a good idea to support some metainformation facility in form of attributed programming.

In .NET you have attributes.

public string HelloWorld()
return “Hello, .World!”;

Java introduces the Language metadata facility (JSR175) which is currently a community draft. This approach is based on javadoc comments.

* @common:operation
public String HelloWorld()
return “Hello, World!”;

Looks somehow similar, right ?

But it’s not.

In .NET the attributes are stored in the assemblies metadata and therefore can be accessed at runtime.
They can be determined by reflection as shown in the following example:

class Test
static void Main(string[] args)
Type t = typeof (Test);
MemberInfo[] members = t.GetMember(“DoIt”);
object[] attrs = members[0].GetCustomAttributes(false);

public static void DoIt()

public class CoolAttribute : Attribute

In Java they merely serve to generate code at compile time.
Java supports reflection as well. But due to the fact that the attributes are not stored in the metadata they can’t be determined by reflection at runtime.

What’s the conclusion ?

On one hand both approaches are very useful to simplify the programming model for the developer.

On the other hand they are like C++ macros. A developer can define his/her own attributes which nobody outside a project might know.
This leads to applications which are hard to maintain.
In order to create maintainable software systems I think developers should define their own attributes/annotations as little as possible.
This will ease the job especially for new team members which join a project at a later time.

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>