Elegant FizzBuzz
Some claim that there are no elegant solutions to FizzBuzz. I think they are wrong.
On the Cursed Computer Iceberg Meme, there is a claim in the section “Bottom of the iceberg” that there are no elegant solutions to FizzBuzz, and it links to this article. To be fair, the article is more about how FizzBuzz is a bad question for interviews, and the author even recognizes that there might be cool/clever/elegant solutions.
However, I have yet to see one that would actually be better in the real world than the simple, obvious solution.
And I think they are 100% correct on that. For real world solutions, it’s often way better to do the obvious thing than trying to be clever, especially when you are working in teams.
Back to FizzBuzz. For an elegant implementation, we need a language that has a simple operator for string concatenation (which a lot of them do) and some sort of default/fallback mechanism to short-circuit if neither “Fizz” nor “Buzz” was triggered. That short-circuit evaluation has to behave in a way that the empty string ""
is considered falsy and even though our fallback is a number the resulting type should still be a string. “Luckily” for us there is a language that can do all that: bash
.
IMHO that’s probably the most elegant solution to FizzBuzz there is. It’s not too obscure, it’s symmetrical (that’s why Fizz
is also a concatenation and not an assignment), it’s short, and most important it’s still very readable and maintainable, especially for people who know Bash. The ${out:-$1}
part might be confusing to non-Bash programmers, but that’s actually a very common thing in Bash to do fallbacks for missing/empty values.
So even though there is no general “elegant solution” to FizzBuzz (that works in most languages), if the programming language is shitty enough, there might be one 🤐.
PS: If you want to give it a try, a for loop calling that function in Bash looks like that:
for; do
done
Update: I was wrong
I just read through the comments of the article and found this gem:
=
# (but I consider this as a bad solution)
I think this is even more elegant than my proposed solution. Maybe shorter lines, and more symmetry between the lines?
=
Probably a good point to stop.