Daily Archives: June 6, 2005

Attributes and Complexity

Attributes can be seen just as a way of gaining some benefits of multiple-inheritance without the awful complexity that comes with that feature. Most languages have wisely done away with MI, and replaced with interfaces, and now attributes.

For example, let’s look at this code fragment in C#:

[Category(“Test Class”)]
public class MyClass
{
//implementation of MyClass
}

This assigns an instance of a CategoryAttribute to MyClass. The same thing could be accomplished in C++, using a base class:

public class MyClass : public CategoryAttribute
{
MyClass() : CategoryAttribute(“Test Class”) { }
//implementation of MyClass
};

However, the disadvantage of the C++ approach is:

  • How do you get the attributes for an arbitrary object? You can try dynamic_cast<categoryattribute *>(arbitraryObject) and check to see if the result is not NULL.
  • If you want many attributes, you are doing multiple-inheritance in a big way, which is a Bad Thing. You will probably get collisions eventually.
  • The whole idea of using attributes per se is kind of lost when using inheritance. By definition, it violates the inheritance principle of “is a” (MyClass is a Category? ummm… no). Classes “have” attributes (MyClass has a Category? yes)

Check out my latest book, the essential, in-depth guide to performance for all .NET developers:

Writing High-Performance.NET Code, 2nd Edition by Ben Watson. Available for pre-order: