Skip to content

Is shorter code better

Rachel Moser edited this page Nov 14, 2021 · 1 revision

So I see folks ask about code length pretty often, wondering whether shorter code is better. Or wondering if their code is too long.

I try to do at least one Codewars problem a day (a Codewars exercise a day keeps the doctor away) and after submitting I often see really concise solutions get voted as a "best practice" or "clever" on the platform. And I used to beat myself up for not coming up with something as concise.

I just finished the exercise called Inside Out Strings on Codewars and noticed that one of their top solutions is a one liner. My solution is 40 lines. I won't claim my approach is the best or fastest. But I find my approach more readable. I'm struggling to reason my way through that one liner. I can't imagine trying to debug it. 😬

Here is the Codewars exercise if you are curious.

And the top rated solution as well as mine in a replit (Figured I'd share the code here to avoid spoilers).

But long story short:

Don't sweat the code length. Aim to get it working first. Remember that other people might read your code so it is worth making it readable. And if it makes sense, make it more concise. But it is possible to overdo that. There's some sweet middle ground that you'll find with practice.