12.2 C
New York
Wednesday, February 26, 2025

11 rules for writing better code



And you need to be very, very sure before you decide that there can be no more than three of anything in your system. A corollary to this rule is…

Don’t hard-code anything

This seems obvious, but some developers love to hard-code stuff. Sweet baby Elvis, I even see this kind of thing all the time:


someString.PadLeft(13);

I mean, really? Why 13? Why not 14? Or 12? How about a constant that explains the meaning of the value?

You may not think so, but every time you create an object inside a class, you are hard-coding that class and its implementation. For example:


class SimpleEncryptor {
  public encrypt(plainText: string): string {
    const weakEncryption = new WeakEncryptionAlgorithm();
    return weakEncryption.encrypt(plainText);
  }
}

So what if you want to change the encryption algorithm? 

Instead, use dependency injection, and you can use any algorithm you want:


interface IEncryptionAlgorithm {
  encrypt(plainText: string): string;
}

class SimpleEncryptor {
  public encrypt(plainText: string, encryptionAlgorithm: IEncryptionAlgorithm): string {
    return encryptionAlgorithm.encrypt(plainText);
  }
}

Often ‘over-engineering’ is proper engineering

Believe me, I get the notion of over-engineering. I just told you to keep things simple. But sometimes, doing things “the right way” looks like over-engineering. Whenever you think you are over-engineering, stop and consider that, well, maybe you aren’t. Creating interfaces and coding against them can seem like over-engineering. I know it’s a fine line to walk, but planning ahead for something you know you will need is not wrong. And this leads me to…

Sometimes you are going to need it

I’ve never quite understood the YAGNI principle (“You aren’t gonna need it”). All too often, you find that, well, you know, you did end up needing it. And by then, implementing this thing you “weren’t going to need” has become such a nightmare that you dearly wish you had gone ahead an laid the groundwork for it. 

Maybe you hard-coded something (you weren’t going to need flexibility here, right?). Maybe you didn’t plan on ever needing seven taxes, or a different encryption algorithm. I see no harm in thinking “You know, eventually, we are going to need to deal with more than widgets here” and coding so that changes are easy when new cogs and sprockets inevitably come along.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles