To optimize code, reduce state, coupling, complexity, and code, in that order. Reducing state makes the program easier to reason about (e.g. pure functions are easy to test). Be willing to add more coupling if that means less state, more complex if it decreases coupling, and duplication if it makes code less complex.
See also:
Links to this note
-
Novice Software Engineers Tend to Optimize Code by Decreasing Duplication
Software engineers early in their career tend to optimize code by decreasing duplication and applying the DRY (don’t repeat yourself) principle. However, this is not always the most valuable contribution, just the easiest optimization to spot. Over optimizing for decreasing duplication can lead to increased complexity of the program and more coupling which are more important concerns than duplication. One should optimize for reducing state, coupling, complexity, and then code.