Friday, February 26, 2010

math-like programming

i couldn't prove it at the time, but i had a feeling that i knew what i was doing....
i think i better understand now why it helps to keep a piece of code running correctly with unit tests while modifying it. it's like a mathematical equation. you can use substitutions and properties of operators and functions to modify the expressions, but only if you maintain equality at every step. maintaining that equality requires an understanding of the underlying math objects, and knowing which way to transform the expressions requires skill and creativity. but the hardest part is to lay down the governing equations to begin with -- to state the paradoxically precise abstraction of reality.
inasmuch as a computer language is an alternate grammar for discrete math, it is to be expected that to manipulate an existing expression while maintaining correctness is easier than to derive an algorithm from scratch (or from incorrect code). sometimes i have correct code that i still want to modify, for example, to generalize or to optimize. i need to think like a compiler and make my modifications in smaller steps, each maintaining correctness with respect to the unit tests, rather than try to leap at once to a large rewrite. faster, easier, and clearer thinking, often with solutions that present themselves along the way.
for example, can i move that assignment from the beginning to the end of the loop? i want to eliminate that variable; first i'll make it redundant. i think these two expressions are equivalent, so i'll put in an assert to test that before replacing the old one. now i have a better way to refactor and i know why to do it.

No comments: