How to find a balance between perfect and good enough code?

Warning. The post contains cats images.

What is the “perfect” code?

Source: https://www.pexels.com/pl-pl/zdjecie/zdjecie-szary-i-bialy-pregowany-kotek-siedzacy-na-kanapie-2194261

We can use no rules to measure code and say, “It’s perfect” or “It’s not”. As always, it depends.

When evaluating your code, it’s always tough to be objective. Imagine you’ve just written a new method:

public function isAuthorized()
{
    if ($this->user === null) {
        return false;
    } else {
        return true;
    }
}

It works, you’re satisfied, the tests are green, and the client is happy. Do we need more? Not really. We can continue our work and create more code.

On the other hand, we know it’s not a perfect code. Let’s make some modifications:

public function isAuthorized(): bool
{
    if ($this->user === null) {
        return false;
    }

    return true;
}

Looks better? Yes. Does it still work? Yes. Do we need more? No, it’s enough.

What is the “good enough” code?

Here we are. The modifications you’ve made are enough. You can now say the code is good enough. It works; the tests are green, there is no regression, and the client is happy.

Source: https://www.pexels.com/pl-pl/zdjecie/ujecie-z-niskiego-kata-pregowanego-kota-208984

Is there a space to make more refactoring? Yes, but it’s unneeded. We’re looking for a balance between perfect enough code. We’ve found it, I think.

Let’s compare the code we’ve modified

The original code we started with, the “bad” code:

public function isAuthorized()
{
    if ($this->user === null) {
        return false;
    } else {
        return true;
    }
}

The “good enough” code:

public function isAuthorized(): bool
{
    if ($this->user === null) {
        return false;
    }

    return true;
}

What else can we do?

In the presented example, there is not much more, but there is one more thing worth refactoring:

public function isAuthorized(): bool
{
    return $this->user !== null;
}

Looks better? Yes. Does it still work? Yes. Is that required? No.

Why it’s not required? The main goal was to find a balance between perfect and good enough code. I’m not saying the refactoring cannot be done. We’re just happy with what we did (balance has been found).