Stop Playing Code Golf At Work

Michael Faber
Geek Culture
Published in
3 min readJan 19, 2022

Shorter code is not better code.

Golf Club and Golf Ball

What is Code Golf?

From Wikipedia,

Code golf is a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code that solves a certain problem.

Recreational? That’s fine — all in good fun. But it can become a problem when you see it in professional, production settings.

Why is it bad?

Let’s say you’ve just been asked to add a feature to an existing project.

It’s mostly someone else’s code you’re looking at. They might be too busy with their own task to sit down with you and give you a run down of it. They might have left your organization. It might even be your own code, but it’s been a long time since you’ve touched it.

You’re looking at a TypeScript function you need to make a change to:

function GetNumberCategory(a: number): number {
return a < 0 ? a%2 === 0 ? 3 : 1 : a%2 === 0 ? 4 : 2;
}

It’s going to take a minute to wrap your head around what that’s even doing. That code has poor readability, and poor scalability. What does a mean? What do the numbers returned represent? Maybe you’re an intern, or a newer programmer, and you’ve never encountered a ternary operator before.

It would have been a lot easier for a developer new to the project (or returning to it after a long time) to understand the function and make a change to it if it looked like this instead:

function GetNumberCategory(somethingId: number): number {
let isEven = somethingId%2 === 0;
// 0 is considered positive because [business requirement]
let isPositive = somethingId >= 0;
if (!isEven && !isPositive) {
return 1; // odd and negative
}
if (!isEven && isPositive) {
return 2; // odd and positive
}
if (isEven && !isPositive) {
return 3; // even and negative
}
if (isEven && isPositive) {
return 4; // even and positive
}
}

That function is much longer to accomplish the same thing. But it’s absolutely worth it. It’s trivial to see that that’s easier to initially understand and make changes to.

How simple will it be for another developer to understand this code and make changes to it in the future?

should be on the forefront of your mind as you write code.

In this specific case, there is no significant or concerning loss of performance. It’s just syntactic sugar.

I advise that you don’t swing too far into the camp of readability and scalability that you begin sacrificing performance. Yes, a linear search through a sorted array is going to be easier to initially understand than a binary search, but the performance difference is too significant.

Conclusion

Writing code that is readable and scalable is a top priority, but don’t sacrifice performance for readability and scalability.

Just for fun — this is a snippet of GolfScript code from the Code Golf Wikipedia page:

;''
6666,-2%{2+.2/@*\/10.3??2*+}*
`1000<~\;

Can you guess what it does?

--

--