Remix.run Logo
ajuc 9 days ago

I like to make truth tables for understanding piles of ifs. Like there's 5 ifs with 5 different conditions - so I make 5 columns and 32 rows, and enumerate all the possible combinations of these 5 ifs and write what happens for each. And then what should happen.

Of course, the disadvantage is the exponential growth. 20 ifs means a million cases (usually less because the conditions aren't independent, but still).

Then I have a flat list of all possible cases, and I can reconstruct a minimal if tree if I really want to (or just keep it as a list of cases - much easier to understand that way, even if less efficient).

cma 9 days ago | parent [-]

Often you can check validity one time before everything else. 5 bools might only actually be valid in 7 possible combinations instead of 32. Convert in one place to a 7 element enum and handle with exhaustive switch statements everywhere else can sometimes be a lot cleaner.

Making invalid data unrepresentable simplifies so much code. It's not always possible but it is way underused. You can do some of it with object encapsulation too, but simple enums with exhaustive switch statements enforced by the compiler (so if it changes you have to go handle the new case everywhere) is often the better option.

ajuc 9 days ago | parent [-]

> Making invalid data unrepresentable simplifies so much code

That's the dream. Error handling is what crushes it :)

cma 7 days ago | parent [-]

Often invalid data it is still representable where you ingest it, but you can then do all the error handling there and convert to a representation where it isn't, instead of having all the code constantly sanity checking it. Not always possible but it can make a big improvement a lot of times.