-
Notifications
You must be signed in to change notification settings - Fork 112
mistakes
Method can either return something or return void
. If it returns something than its name should explain what it returns, for example:
boolean isValid(String name);
String content();
int ageOf(File file);
If it returns void
than its name should explain what it does, for example:
void save(File file);
void process(Work work);
void append(File file, String line);
There is only one exception to the rule just explained - test methods for JUnit. They are explained below.
Method names in JUnit tests should be created as English sentences without spaces. It's easier to explain by example:
/**
* HttpRequest can return its content in Unicode.
* @throws Exception If test fails
*/
public void returnsItsContentInUnicode() throws Exception {
}
It's important to start your JavaDoc first sentence with the name of the class you're testing followed by can
. So, your first and the only sentence will always sound like "somebody can do something". Method name will say exactly the same, but without the subject. If I add a subject at the beginning of the method name I should get a complete English sentence, as in example above: "HttpRequest returns its content in unicode".
It's a good practice to always declare test methods as throwing Exception
.
Avoid composite names of variables, like timeOfDay
, firstItem
, or httpRequest
. I mean both class variables and in-method ones. A variable name should be long enough to avoid ambiguity in its scope of visibility, but not longer. A name should be a noun in singular or plural form, or its abbreviation, for example:
final List<String> names;
void sendThroughProxy(File file, Protocol proto);
private File content;
public HttpRequest request;
Sometimes you may have collisions between constructor parameters and in-class properties, when your constructor is saving incoming data into an instantiated object. In this case I recommend to use abbreviate by removing vowels, for example
public final class Message {
private String recipient;
public Message(final String rcpt) {
this.recipient = rcpt;
}
}
Don't calculate time with constants, like:
final long millis = min * 60 * 1000;
Instead, use TimeUnit
:
final long millis = TimeUnit.MINUTES.toMillis(2);
final long sec = TimeUnit.HOURS.toMinutes(1);
Don't forget to use @ToString
and @EqualsAndHashCode
annotations from Lombok. They add toString()
and equals()
and hashCode()
methods to your class during compilation. Why it's important? Because without them you will either 1) have default methods that don't do any good, or 2) will hav to create your own in every class, which is ineffective.
But don't forget to specify a list of private properties for @EqualsAndHashCode
, for example:
@ToString
@EqualsAndHashCode(of = { "name", "age" })
public final class User {
private final transient String name;
private final transient long age;
}