jacobko
jacobko

Reputation: 8960

Should I make a constants class for my annotations?

Which is better?

  1. @SuppressWarnings("unchecked")
  2. @SuppressWarnings(AnnotationConstants.UNCHECKED)

Where AnnotationConstants is a typical constants class...

public final class AnnotationConstants {
    private AnnotationConstants() { }

    public static final String UNCHECKED = "unchecked";

    ...
}

I know that there are a lot of general arguments for and against constants classes--and that's exactly what I'm not interested in. I want to know if a constants class specifically for annotations is a good idea or a bad idea.

Upvotes: 3

Views: 999

Answers (4)

Scott Stanchfield
Scott Stanchfield

Reputation: 30642

I'd agree with Holsam for SuppressWarnings - use the strings

If you're writing your own annotation, I'd recommend usng enums where possible for things that could be represented as a set of constants

Upvotes: 2

Hosam Aly
Hosam Aly

Reputation: 42443

For @SuppressWarning and the likes, I don't think so. I prefer writing the constants directly, and have the compiler check them if possible. Eclipse does a nice job at that.

Upvotes: 0

krosenvold
krosenvold

Reputation: 77141

I'd say a little bit of both, please.

In Spring, you could say something like @Scope(Scopes.SESSION) or @Scope(Scopes.REQUEST), which attaches a specific kind of behavior to the annotation so I'd say always use a constants class, which is good for traceability.

If you're just supressing warnings, there's little likelyhood that you want to really trace this, so just go with the literal.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500495

For this specific example I'd stick with literals. After all, you're trying to suppress warnings - if you use the wrong literal, the warning won't be suppressed, which will draw your attention to the problem.

Upvotes: 6

Related Questions