Coding for Co-Workers, part 2

This is the second article in a series about writing code for my co-workers. Here is part one.

Clarity

In order to be understood with the least possible effort, my code needs to be as clear as possible. I want to make the code so simple that is is boring to read.

Braces

For instance, this is why I always use braces, even if a statement is a single line, like so:

// good
if (foobar) {
  DoSomething();
} else {
  DoSomethingElse();
}
// bad 
if (foobar)
  DoSomething();
// worse
if (foobar) DoSomething();

Ternary operator

I also try to avoid the ternary, or conditional operator ?:, except in most simple cases. There is just too much stuff happening on a single line when you use it:

// bad 
foo = !bar ? (baz + 13) : (baz / 42);
// good
if (!bar) {
    foo = baz + 13;
} else {
    foo = baz / 42;
}
// better
if (bar == false) {
    foo = baz + 13;
} else {
    foo = baz / 42;
}

!

Note that I also prefer to use == false instead of !. Again, clarity is the reason.

Assignment in conditionals

Finally, I try to avoid assignments in conditionals. Instead, I split it into two statements:

// bad
while ((line = inputReader.readLine()) != null) {
  System.out.println(line);
}
// good
while  (line != null) {
  System.out.println(line);
  line = inputReader.readLine();
}

Comments are closed.