4 ms·
Logic tables are a secret weapon when refactoring spaghetti code. You take all the conditions relevant to the part you're refactoring. You refactor common par
by ajuc 6y ago
Logic tables are a secret weapon when refactoring spaghetti code.
You take all the conditions relevant to the part you're refactoring.
You refactor common parts of the conditions (so if one if has (x>3 & y<2) and another if has (x>3 and y>10) you get (x>3), (y<2), (y>10).
You put that into a table, write all possible values that can happen (sounds like combinatoric explosion but it's usually not, because many of them depend on each other and lots of combinations cannot happen or aren't relevant to the result) - then rewrite the whole thing looking at the table.
x>3 | y<2 | y>10 | effect
F | F | F | ...
T | F | F | ...
F | T | F | ...
T | T | F | ...
F | F | T | ...
T | F | T | ...
Another form is
x | y | effect
<3 | <2 | ...
>=3 | <2 | ...
<3 | 2...10 | ...
>=3 | 2...10 | ...
<3 | >10 | ...
>=3 | >10 | ...
Usually if the code is old enough there's redundant branches, checking conditions that can't happen, duplicated code "just in case", etc.
With the table you can look at it and see input-output and refactor it without worrying about changing behaviour.
For simple cases it's overkill, but with big enough mess it's a life-saver.
- ethanwillis 6y agoThe real secret weapon is to take the truth table and use a karnaugh map to reduce it to just the necessary states in a structured way.
- haddr 6y agoThis
- ajuc 6y agoIt's usually not a truth table, the "effect" column is stuff like "call f1 then f2" or "call f2 then f1 then f2 again". You can transform it into a truth table by pulling these into input variables "f1ShouldBeCalledFirst", "f2ShouldBeCalledFirst" etc, or by using separate table for each binary decision, but that was overkill for my needs and it caused combinatorial explosion. YMMV.
- deleted 6y ago[deleted]