What Shape Should My Code Take? (using FizzBuzz)
Sometime back in my early days of programming, I learned to enjoy a truth table.
Fizzbuzz seems to beg for a simple truth table - the values 'should_fizz', and 'should_buzz' form up a simple tuple of booleans, and the choices are
- True, False - fizz
- False, True - buzz
- True, True - fizzbuzz
- False, False - string of the number
This expresses rather neatly in Python, is efficient and pythonic, and handles negative cases neatly also:
But here's the rub:
One of the "normal" changes is to add a rule that multiples of 7 say 'woof' even if they are also divisible by 3 or 5. That's a peculiar rule, but let's consider it for a moment.
If I am going to add another term to the set, I have to edit the match line and every case line. I will have to add new cases for all the possible truth values in my new 3-tuple table. That's not so much fun.
The changes to my test suite are, at least, minimal.
The best expression in our codebase may not be the one that does the tidiest job of expressing our algorithm using well-considered and idiomatic means.
Perhaps the best algorithmic expression is the one that lets us make the next change easily without sacrificing any functionality or performance (in case performance matters).
The if/else version, while being less appealing to the table-loving otter, will expand much more gracefully.
An LLM can convert the structure of sufficiently small and tidy algorithms (functions, for instance) into different equivalent forms that pass the same tests, and can do so in mere seconds.
From here, all that is necessary is to add one more if statement. That's so trivial, I won't bother illustrating it here.
This leaves us with a few interesting takeaways:
- Expressing requirements as tests will support refactoring.
- The "best" expression is the one that makes the next change easy.
- You may not know in advance which kinds of changes to expect, so it's nice to be able to restructure your code at the last minute, before adding a new feature.
- Don't be overly precious when writing the first version. Don't try to anticipate all future uses. It will likely have to be reworked when an inelegant change appears.
Comments
Post a Comment