refactor by partial evaluation

Some time ago I read an article on proggit that made an analogy between compression and clean design. Basically if you see a lot of repetition then you factor out that structure and re-use it the same way a compression algorithm takes out common patterns and re-uses them to more compactly represent some blob of data. Sometimes though it is not the structure or the common patterns that make things hard to understand but instead it is too much generality and indirection. So how do you solve that problem?

In those instances I like to pretend I’m a partial evaluator and start inlining constants and pieces that were designed to be reusable but are only ever instantiated to a single value. More often than not this turns out to be the right thing because the original author was designing for a use-case that never came to pass and instead just added too many layers of indirection. After I get rid of the indirection the end result often times ends up being much cleaner and shorter because the overall structure is no longer obfuscated by the extra parameters and layers of indirection. Combined with the compression analogy this usually leads to pretty optimal code structure and design.