Context Transference

Context Transference

Friday 30 May 2025

One of the hardest refactorings to get right is the balance between extract and inlining of functions.

Often people struggle to understand why sometimes when they “do the right thing” and extract a function, their code quality feels like it decreases - this is actually one of my biggest criticisms of Clean Code as a book - it’s rife with low quality method extraction.

I think that feeling comes from the weight of “context transference”.

Context transference is the amount of information you have to pass between boundaries, and method extraction where 100% of the callers context needs to be transferred for the new function to be meaningful is a poor refactor. You don’t reduce any cognitive load - it’s a failure of encapsulation.

In object oriented languages this is a more common problem because the context is often scoped to a class, so it’s implicit which parts of state are used in any given function, and as a result this transfer of context is equally implicit.

While it might sound like object scoped state is actually a solution to this problem, it isn’t, because the transfer of context is actually the amount of information the programmer has to mentally track during code reading, not the information a computer has to track (because functions exist purely for the programmer) - it’s a design time concern and rarely a significant runtime one.

Extraction refactorings should operate on a strict subset of the context of the parent function to be meaningful and not detrimental to reading code, as a general rule.

(Standard disclosure: generalisations include exceptions by default, I’m sure there are many cases where this doesn’t apply)