Annotations and Attributes Are Evil

Relax, relax, they aren’t evil. They’re just misused, their misuse is easily promoted, and it can even come across as appealing. Spring enables AOP through annotations, Hibernate understands metadata specified as annotations, .NET’s XML serializer allows inline attributes to specify how to serialize an object’s properties, a certain JSON library does about the same thing for JSON. So you craft your class and start adding attributes. Notice anything wrong here?

Annotations are just a more appealing way of getting heavyweight objects, objects that attempt to do a Superman job of keeping everyone happy. Moreover, annotations imply assumptions about the usage of an object. With Hibernate, for example, you can only map a class to a single database schema with annotations. What is to say that the class was meant for a database schema? Well, it depends on the usage details. If a class represents a business entity, it may not want to promise much about how it will be serialized to a database. A data transfer object aimed at a particular data source, on the other hand, may get a pass.

Annotations/attributes are about the class, not about how this thing or that thing churns up the class. As such, they should be used with restraint and only if the usage of the class is inherently bound to the tool consuming the annotation/attribute, or if the attribute was not designed with a particular goal in mind. What I see out there is, for the most part, nothing like this. Some examples.

  • Generated classes meant to be mapped by NHibernate—yes!
  • [Author("Mnemonic")] or @Author("Mnemonic")—yes, on any class, as it is tool agnostic and intrinsic to the class.
  • Annotations on the client class to be consumed by MyObscureModule—no, thanks!
  • JSON annotations on a transfer object written for the UI—typically no. Think multiple UIs and you’ll get a feel of why not.

 

Post a Comment

You must be logged in to post a comment.