Sunday, December 30, 2012

Annotations in Dart

‹prev | My Chain | next›

While mucking about with constant constructors in Dart, I happened across a mention of a feature that is new to me: annotations. This mention in the spec was the first time that I have ever heard of annotations, so it seems worth stopping for a bit of investigation. I tend to doubt that understanding will come today, but stranger things have happened.

A bit of research reveals that annotations are similar to annotations in Java or attributes in C#, which goes a long way toward explaining why I have never heard of them. That also might explain why I may find it difficult to wrap my brain around them.

Per the spec:
Reflective access to metadata is not yet implemented as of the M2 release.
In other words, I will not be able to use Dart annotations directly in my code—at least not yet. That's just as well, because I doubt that I could figure them out tonight anyway.

What I can do is adopt the BugFix example from C# attributes in Programming C#. The example in there presents attributes / annotations as a mechanism for formalizing comments. In this case, bug fixes. Using what I know about constant constructors, I create a constant constructor for a BugFix class:
class BugFix {
  final int number;
  final String author;
  final String comment;
  const BugFix({this.number, this.author, this.comment});
}
Now, above the Cookie class upon which I have been working laboriously, I can indicate when I have applied bug fixes and a bit of information about them:
@BugFix(number: 42, comment: "Typo")
@BugFix(number: 45, author: "Chris", comment: "Typo")
class Cookie {
  int number_of_chips;
  Cookie({this.number_of_chips:0});
}
If I code up a main clause that puts this code to good use:
main() {
  var cookie = new Cookie();
  print("cookie has ${cookie.number_of_chips} chips");
}
I find that the code is executed normally—as if the annotation did not exist:
$ dart annotations.dart 
cookie has 0 chips
But I have formalize the manner in which bug fixes are associated with code.

I cannot say that I have have ever wanted something like that in a real codebase, but it does help to get a better feel for these beasties. Perhaps tomorrow I can come up with a better example of how I might want to use annotations—at least until they are available in reflection.


Day #615

1 comment: