HomeCloud ComputingSeven little habits for writing higher code

Seven little habits for writing higher code



Don’t be afraid to over-log

Logs are low cost; log insights are priceless.

Alongside the identical traces, don’t be afraid to “overdo” your log entries. A whole and detailed log file is vastly extra useful than one that’s skinny and sparse. Log studying instruments are designed to slice, cube, and filter, and so don’t be afraid to make use of logging ranges, full and data-rich log entries, and verbose explanations of what’s going on.

Should you open it, shut it.

Construct the behavior earlier than you construct the logic.

Should you create or open one thing, instantly write the code to destroy or shut that factor. Generally, if you’re in a rush, you may neglect. For instance:


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

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

  // Oops: no shut! 
  // The file deal with stays open till the method ends.
  return buffer.toString().break up("n")[0];
}

Yeah, that’s not good. As an alternative, once you write the openSync name, instantly write the strive… lastly clause. Instantly.


operate readFirstLine(filePath: string): string {
  const file = fs.openSync(filePath, "r");
  strive {
     // do not put something right here till the lastly clause is written
  } lastly {
    // At all times shut what you open
    fs.closeSync(file);
  }
}

It’s a fantastic behavior to get into. Should you allocate it, all the time de-allocate it straight away. Should you write a whereas loop, be sure that there’s a strategy to get away of it earlier than you write any logic. Construct up the muscle reminiscence for this one.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments