Cleaner Code: Keep Code Left 🖌️

Attended a great meetup recently about a coding philosophy called Keep Code Left, presented by Michael Andrew from Sage.

Thought it might be a good idea to make a record of what I have learned. Hopefully it may benefit others who may not have encountered this technique before.

In Keeping Code Left, the goals are:

  • Filter out unimportant cases as early as possible
  • Main body of a function should not be indented
  • Avoid deeply nested code blocks if possible
  • The useful result should be at the end of the function

Examples:

• Filter out unimportant cases as early as possible
• Main body of a function should not be indented

Bad:
function process(a) {
  if (a) {
    doSomething(a);
    doSomeOtherThing(a);
    doOneLastThing(a);
  } else {
    throw "Missing argument!";
  }
}

Good:
function process(a) {
  if (a == undefined)
    throw "Missing argument!";

  doSomething(a);
  doSomeOtherThing(a);
  doOneLastThing(a);
}

• The useful result should be at the end of the function

Bad:
function diff(a, b) {
  if (a > 0 && b >= a) {
    return b - a;
  } else if (a <= 0) {
    logError('a less than 0');
    return null;
  } else {
    logError('b less than a');
    return null;
  }
}

Good:
function diff(a, b) {
  if (a <= 0) {
    logError('a less than 0');
    return null;
  }

  if (b < a) {
    logError('b less than a');
    return null;
  }

  return b - a;
}