views:

223

answers:

5

I can't make up my mind between

@MyAnnotation
public void foo(){}

and

@MyAnnotation public void foo(){}

Is there a best-practice emerging?

+14  A: 

We use the first case.

Annotations don't fit on one line in some cases.

  • What happens in that annotations keep adding up in our project, responsibility after responsibility. Having annotations for really different concerns on the same line becomes messy.
  • Also, some annotation can become really big, and be multi-liners on their own (I think of Hibernate mapping redefinition in a subclass).
KLE
I second that. Also I'd recommend to apply annotations in some fixed order e.g. alphabetically sorted.
yawn
A: 

Well, we can't even agree where to put an { :-(

My preference is the former, especially as there can be more than one annotation.

The examples I'm familiar with use this style.

djna
+1  A: 

Annotations can have parameters, it can become very long if you put the annotation plus its parameters plus the method header all on one line.

@MyAnnotation(name = "This is the name", version = "1.0")
public void foo () {
    // ...
}
Jesper
+1  A: 

I'd say there is no hard fast rule for this. You may want to do either depending on the situation.

For example, if your class has big bunch of short methods, it's sometimes desirable to condense them onto one line to reduce code noise:

@MyAnnotation public int foo1(){ return 1; }
@MyAnnotation public int foo2(){ return 2; }
@MyAnnotation public int foo3(){ return 3; }
etc etc

Like-wise, if you have a more substantial method with a complex annotation, the expanded form is more desirable.

Andy Holt
+1  A: 

I would generally use the first case.

However, one particular instance where I put the annotation on the same line is with the @Test annotation in JUnit. This is fairly short, doesn't usually take any parameters, and above all usually appears in a context where a human reader would subconsciously expect it to be there anyway. When you're annotating public void nullary methods in a test class, I'd argue that the extra brevity of rolling the annotation into the same line is better (i.e. less of a distraction, can see more code on screen) than putting it on a separate line,

In the general case, you do want your annotations to stand out, as they're often a departure from what the developer would expect from an unannotated method. So, for example, if I set a timeout on my @Test annotation I will put it on the preceding line so that it doesn't just get lost in the boilerplate.

Andrzej Doyle