Tuesday, June 28, 2011

Code for interview

If we hire a software engineer in the company I work for, we always want to see some code of the applicant. This can be some part of an open source project the applicant is contributing, something from a course the person attends (in case of graduates) or they solve a short task we tell them.
I always find it extremely enlightening to see how people code because it tells you a lot about the way they think and work. Most of the time I am crestfallen however, about the quality of the code presented. So here is my list of things I look for in such code:
  • Short and concise. Don't try to show how much complexity you can handle, instead demonstrate that you avoid it as much as reasonably possible. Remove unneeded lines of code.
    If you are using code from an open source project, pick a single good source file which demonstrates how smart you are. Make it easy to access that file (e.g. send it by e-mail, don't tell the employer to download the latest 1.5 GB tarball and look for your name in the version history...).
  • Good names. Classes, methods, variables should have names that are as short as possible but telling.
  • Avoid gotos. All Gotos. Write your methods so that they are Dijkstra-Diagrams. Code is much easier to read if all the methods are exited at the last line of code. This means to avoid things like return-statements in the middle of the method, breaks in loops, fallthrough case-statements.
    Even exceptions are a kind of goto but you cannot usually avoid them, as they are given by the environment.
  • Don't comment what is obvious from the code. Some applicants try to demonstrate how well they are documenting their code by writing things like this:
    x = x + 1; // increase x by 1
    or
    /** Get name. */
    void String getName() {
      if (name == null) {
        name = createName();
      }
      return name;
    }
    In the first case, just remove the comment. In the second one could better comment that the method creates the name, if this has not yet happened. But it would be better yet to call that method getOrCreateName() because that would be a more fitting name.
  • Avoid long methods. If one of your method is longer than 20 lines you can possible split it up. Depending on the situation you can do so by inserting "section comments" or introducing helper methods. Using helper methods is usually the better method as it fosters reuse.