Suggested coding guidelines
- Indentation: suggest to use 4 spaces; 2 spaces works as well – but be consistent! No tabs please!
- Spaces:
- a single space before “(“, “{“
- a single space after “)”
- a single space around operators
- Example: “if (a == b && x != y) {“; avoid “if(a==b&&x!=y){“
- Blocks: “{“, at the end of the line that starts the block, end the block with “}” in a separate line
- Statements: earlier restrictions on line length (of 80/132) were likely for printing of the code on paper. Most of us shouldn’t be printing source code on paper now. So, a statement need not be broken into multiple lines – even if it is few hundred characters long.
- Avoid static members as much as possible. Such use often make it difficult later when the class needs to be used in wider context.
- Where possible, use final members. It can help improve the readability significantly.
- Class member declaration in the following order:
- static members: public, protected, private; within each accessor, ‘final’ members precede non-final
- instance members: public, protected, private; within each accessor, ‘final’ members precede non-final
- Vertically align start of: typeName, variableName, assignment operator
- methods: public, protected, private; within each accessor, static methods precede non-static
- methods: all constructors immediately after ‘public static’ methods
- methods: all getters/setters immediately after constructors
- methods: all @Override methods immediately after getter/setters
- methods: use a consistent name for variable holding the return value. Suggested name ‘ret’
- methods: use a single return for each method (as much as possible)
- methods: avoid methods with large number of lines; suggested length 24 (from good old days!)
- Blank line before and after each ‘for/while/do/if-else’ block
- Blank line after each variable declaration block
- Separate assignment lines from the rest
Consider using attached coding style files for IntelliJ and Eclipse.
Here is a sample code to demonstrate above guidelines:
class MyClass {
public static final String CONFIG_INDEX_TYPE = "index.type";
public static final String CONFIG_INDEX_TYPE_DEF_VALUE = "solr";
private static final Logger LOG = LoggerFactory.getLogger(MyClass.class);
protected final String id;
protected String updatedBy;
private final String name;
private int count;
public static void main(String[] args) {
// ...
}
public MyClass(String name) {
this.id = 0;
this.name = name;
init();
}
public String getId() { return id; }
public String getName() { return name; }
public String getUpdatedBy() { return updatedBy; }
public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; }
public boolean doWork() {
boolean ret = true;
for (int i = 0; i < count; i++) {
if (count > 0 && count % 1000) {
LOG.info(...);
}
test();
}
return ret;
}
private void init() {
this.count = 0;
test();
// ...
}
}