Tuesday, April 24, 2007

Duh! Annotation values as constants, not literals

One funny thing I discovered recently is that annotation values don't have to be literal values. You can reference constants. Thus I went from:

@Scope("perthread")
public class .... 

To:

@Scope(IOCConstants.PERTHREAD_SCOPE)
public class ...

I think this is a Good Thing, even though it's a bit more verbose (a static import helps there) because I know at compile time that there isn't a typo in my constant's variable name ... whereas @Scope("prthread") would not be caught until runtime.

4 comments:

  1. you can use Enums too.... seen in JPA

    g,
    kris

    ReplyDelete
  2. Strangely, that part I knew.

    ReplyDelete
  3. whereas @Scope("prthread") would not be caught until runtime.

    ...if then. One of the major problems of the run-time validation which seems to be so popular is that it's REALLY tricky to tell if you've screwed something up. You have to make sure you have a unit test which hits the particular scenario and successfully fails in the case of your particular typo.

    Worse, these kind of unit tests are notoriously heavyweight to write. For instance, in this case you'd have to have a pretty fancy unit test which involved firing off two different threads and interrogating them to find the difference: that's a lot of work. And if a unit test is a lot of work to write, it's all the more likely to be abandoned -- right when you needed it most!

    ReplyDelete
  4. Well, specifically: T5 IoC will not register this as an error until it realizes your service, at which point it will see the error, and identify the correct possible values.

    T5 IoC has also tested to death this issue, which is why I would much rather lean on that code that endlessly write ThreadLocal-based code to accomplish the same thing. Less code == good (if you can trust it).

    ReplyDelete

Please note that this is not a support forum for Tapestry. Requests for help will be deleted. Please subscribe to the Tapestry user mailing list if you are in need of support, or contact me directly for professional (for pay) support.

Spammers: Don't bother. I delete your comments and it's a waste of time for both of us. 垃圾邮件发送者:不要打扰。我删除您的评论和它的时间对我们双方的浪费