Archive for December, 2004

Coding for Co-Workers, part 2

Tuesday, December 7th, 2004

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();
}

Programmers vs. Developers

Tuesday, December 7th, 2004

A small interlude: I am a developer, not a programmer.

Eric Sink is right when he says:You need Developers, not Programmers:

Instead of “programmers” (people that specialize in writing code), what you need are “developers” (people who will contribute in multiple ways to make the product successful).”

Coding for Co-Workers, part 1

Monday, December 6th, 2004

I write code for my co-worker, not for the compiler. In this series of articles, I try to explain what this means.

Useful names

Classes, methods, and variables should have a name that reflects their current purpose. This means that a developer who is unfamiliar with some code should be able to glance at it and have an idea what is it about. If the purpose changes, the name should change as well (Using a proper IDE which allows you to change all occurences helps a lot here).

If you decide on the name, or if the only thing you can decide on is something general like UserManager, this a good sign of code smell. Chances are that the class or method does too much, and can be refactored into smaller subclasses/submethods.

ReSharper

Wednesday, December 1st, 2004

I just love ReSharper, from Jetbrains, the makers of IntelliJ IDEA. Every day I learn more tricks that increase my productivity. Yesterday, I typed the following:

usersTable = new DataTable();

usersTable was not yet declared, so I this was indicated to me by ReSharper. It offered me to create a new field _usersTable, which was of type DataTable. Very impressive stuff!