...
- 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:
...