This is some notes on Java Style. It is far from complete, thus, I reserve the right to update it without notice :-) It is also a personal preference, so of course YMMV. Caveat lector. Use at own risk. Etc.
What I’ve done some places is to set the IDE preferences, export them to a file, and get each new developer to start by importing those.
Naming
Use upper-camelcase for classes and all class-like things: Customer
, SoccerGame
, SeasonTicket
.
Class-like things include class
, interface
, enum
, annotation, record
.
Use lower-camelcase for methods, fields, and local variables: i
, customer
, currentShoppingCard
Use all-lower-case for package names.
Avoid overly-short variable names (except i
, j
, k
… as loop indexes, s
or sb
for
very-local String
or StringBuilders
, etc.).
The IDE will type names out for you once they’re known, so:
-
don’t skimp on readability
-
do learn to use name completion!
The following naming convention is most strictly observed in Android code:
-
Instance fields begin with "m", e.g.,
mDataArray
; -
Static fields begin with "s", e.g.,
sGlobalCounter
; -
Less-commonly used: local variables inside methods begin with "_".
Formatting
I personally adhere to the "one true brace style" promulgated by Dennis Ritchie who invented the C language, the syntactic ancestor of awk, C++, Java, C#, perl (block syntax only!) and other languages.
if (condition) { // handle it }
for (loop-control-stuff) { // do iterated stuff }
No parens around the expression of a return
statement.
return Math.PI * radius * radius;
White space
A single space after all keywords (as above). Single space before and after each operator. No space between method name and "(", nor after "(".
int i = 42 * Math.sqrt(a * a + b * b);
Indent with tabs, not spaces. Set tabstop=4 in your editor.
One indent after: class-like statement, method-header, control-flow
public class Foo { public static void main(String[] args) { if (args.length > 0) // Do something with args
One blank line:
-
before each method
-
after the method header (any boilerplate vars such as loggers, serial version UIDs, etc)
-
between "paragraphs" of code that implement major steps of the method’s work.
Expand Imports
Don’t use "*" imports. The IDEs will manage imports for you.
Warning Police
Remove unused imports; Eclipse "Organize Imports will do this. IntelliJ "Optimize imports" for some reason will not, but you can tell it to in Settings.
Remove unused variables, etc.
Get rid of all warnings while there’s only a few. When there are hundreds, they will never go away, and valuable warnings (i.e., real bugs) will disappear into the noise.