Seven little habits for writing better code

Don’t be afraid to over-log

Logs are cheap; log insights are priceless.

Along the same lines, don’t be afraid to “overdo” your log entries. A complete and detailed log file is vastly more valuable than one that is thin and sparse. Log reading tools are designed to slice, dice, and filter, and so don’t be afraid to use logging levels, complete and data-rich log entries, and verbose explanations of what is going on.

If you open it, close it.

Build the habit before you build the logic.

If you create or open something, immediately write the code to destroy or close that thing. Sometimes, if you are in a hurry, you might forget. For example:


function readFirstLine(filePath: string): string {
  const file = fs.openSync(filePath, "r");  // File handle opened

  const buffer = Buffer.alloc(100);
  fs.readSync(file, buffer, 0, 100, 0);

  // Oops: no close! 
  // The file handle stays open until the process ends.
  return buffer.toString().split("\n")[0];
}

Yeah, that’s not good. Instead, when you write the openSync call, immediately write the try… finally clause. Immediately.


function readFirstLine(filePath: string): string {
  const file = fs.openSync(filePath, "r");
  try {
     // don't put anything here until the finally clause is written
  } finally {
    // Always close what you open
    fs.closeSync(file);
  }
}

It’s a great habit to get into. If you allocate it, always de-allocate it right away. If you write a while loop, make sure there is a way to break out of it before you write any logic. Build up the muscle memory for this one.

Donner Music, make your music with gear
Multi-Function Air Blower: Blowing, suction, extraction, and even inflation

Leave a reply

Please enter your comment!
Please enter your name here