Monday, July 4, 2016

Java Code Styles: The Basics

Making your code readable is essential when working with a team, asking for help, or making an application maintainable. You have probably worked with people who have omitted braces on single-line if statements, used white-space like there is no tomorrow and committed far more unspeakable crimes (in their code!) only to have them proudly stand by their code styles. Others of us are just oblivious to the value of good code styles and how to implement them.

I figured I'd put together a guide of the common malpractices I see (and have corrected for myself) to try and help combat this problem. Over time, I may make some edits and additions to the post as I learn and others point out holes. One last note, each language has its own best practices for code styles, and each company will have its own variation of these practices so these styles for Java may not be applicable to C++ or Prolog.

1) Put a space in your statements and loops

This one isn't obvious at first, but there is value in making your function calls look distinct from your statements and loops. Putting a space in between a for and its opening parenthesis is the way to achieve this:
turn this:
if(booleanOne) {
  doThatJazz();
}

into this:
if (booleanOne) {
  doThatJazz();
}

2) Keep your whitespace to 1 line max

The main reason I see people doing this is to try and put visual breaks in their code. If one line is not enough you should be thinking of inserting a comment not a bunch of whitespace.

4) Casing and Naming Matters

Naming members (methods, fields, classes, etc) of your code is essential to making it easy to understand. Do you really want to call a variable so that your readers have to go back to the declaration to find out what the hell it is? If you think that is bad, I have seen people give lists of elements singular names! In other words if you have a list of dogs don't declare it: List<dog> dog; declare it List<dog> dogs;
/rant
so what it boils down to for variables is:
  • Make your variable names descriptive, consiceness comes second.
  • Name list and arrays with plural names
  • Variables and functions are camelCased
  • Classes should be in PascalCase
  • Constants should be in ALL_CAPS

5) Keep your class members organized

a) Static variables
b) Fields
c) Abstract methods
d) Static methods
e) Constructors
f) Methods
g) Interfaces
h) Inner classes

7) Keep your methods short

Google recommends under 40 lines. If you are getting longer you can probably move some of the logic into other meaningful methods.

6) Put your opening braces on the 0th line

Proper indentation, closing braces and the method declaration/(opening of a statement) should serve as markers for the start and ends of a block. It is damn annoying to scroll through code, make life a bit easier for those who review your work.
This:
public void doThatJazz() 
{
  //tons of code
}

Should be this:
public void doThatJazz() {
  //tons of code
}

While we are on the topic of braces...

8) Always use braces in for loops and if statements


You have probably heard this one before, but just to drive it home: omitting the braces on your if statements and for loops makes your code more error prone and harder to read.
Consider this loop:
int i;
for (i = 0; i < 20; i++) 
  doThatJazz(i);
doThatPazzaz(i);

It is not immediately obvious which lines are supposed to be executed, especially since both methods take in i as an argument. Instead you should use your braces to make it clear and prevent errors if you make edits to the statement or loop in the future:
int i;
for (i = 0; i < 20; i++) {
  doThatJazz(i);
}
doThatPazzaz(i);

Phew, much better. As a side note, lack of clarity from omitting braces is compounded if you follow poor or inconsistent indentation practices.

9) 2 or 4 space indents, 4 space for continued lines.


Keep your code dense. Putting more indents than 2 or 4 spaces makes it a pain to read code, especially if you have nested if statements. Speaking of nested if statements...

10) Avoid nesting if statements and for loops

This is not only hard to read, but it also indicates that your code is not as performant as it could be.
Here we nest to the max:
public void preserveAnimal(Animal animal) {
  if (animal.isEndangered()) {
    if (animal instanceof Panda) {
      ((Panda)animal).feedBamboo();
    } else if (animal instanceof Marsupial){
      Marsupial marsupial = ((Marsupial)animal);
      if (marsupial instanceof Bilby) {
        Bilby bilby = (Bilby) marsupial;
        if (bilby.getWeight() > 3) {
          bilby.breed();
        } else {
          bilby.feed(); 
        }
      } else if (marsupial instanceof Koala) {
        ((Koala)marsupial).preventSyphilis();
      }
    }
  }
}

instead it can be expressed as:
public void preserveAnimal(Animal animal) {
  if (!animal.isEndangered()) {
    return;
  }

  if (animal instanceof Panda) {
    ((Panda)animal).feedBamboo();
    return;
  }
  if (animal instanceof Bilby){
    Bilby bilby = (Bilby) animal;
    if (bilby.getWeight() > 3) {
      bilby.breed();
    } else {
      bilby.feed(); 
    }
    return;
  }
  if (animal instanceof Koala) {
    ((Koala)animal).preventSyphilis();
  }
}

11) Limit your line length to 100 (for now)

Have you ever tried to read some example code only to find it stretched to the right into oblivion? Yea, its painful to read and no-one likes to do it. It's not just something you realized, researchers have also concluded that humans tend to read narrow tall text blocks more quickly and with better memory than long ones.
I remember when this was 80, with wider screens this value has jumped up, who knows, it may happen again soon!

12) Be consistent and enforce your code styles with your IDE settings

Whatever variant of code styles you choose to follow make sure to be consistent throughout your code. One way you can help enforce this is by using you can auto format your code. Here is an SO post describing where to access your settings for eclipse and the docs for accessing them in an IntelliJ based IDE (android studio).You should browse the options available and search online if you need to change something specific.

I hope you liked the styling I proposed and possibly picked up some new practices. Share your thoughts, additions or peeves in the comments!

Some Sample Code



0 comments:

Post a Comment