Code Change Complexity
Recently, I’ve been using algorithmic complexity as a metaphor for change complexity.
Usually, when people talk about complexity in code, they are talking about cyclomatic complexity in classes and methods, but the fact of the matter is that there are other forms of complexity that are worth noting - particularly the complexity of refactorings. To me, it’s an illuminating perspective.
Algorithmic complexity is given in “big-oh” notation. An algorithm of order O(1) does its work in constant time. For instance, hash tables have O(1) lookup in the typical case. If you are using a data structure that requires a linear search, we notate it as O(n). The lookup is linear in the number of elements in the data structure.
How do we apply the metaphor to code change? Well, the first thing to notice is that the best case for a code base is for our changes to be O( 1 ). That is, we only have to change one class/file in order to make a change. If our code has good characteristics - if it obeys the Open/Closed and Single Responsibility principles, we can approach that ideal. If, on the other hand, we make bad design choices, like littering every class in our entire application with SQL calls, a particular change like switching database technology might be closer to O( n ). Clearly, we don’t want our code to have that sort of problem.
Are there any O( n2 ) changes that you can make to a code base? I don’t know. I know that in bad code, dependencies can grow supra linearly. Each class or file can end up being dependent on many other classes or files. If we do the work of extracting subsystems and similar architectural refactoring, we end up having to revisit the same abstractions many times. But our n in O( nk ) is typically less than n - the number of entities in the code base.
I’m not sure how far this metaphor goes, but I do know that one thing that helps me is to look at various design decisions that people make in code bases and label them as O( 1 ) or O( n ) depending upon how much it would cost to change them. It seems to be a good practice.
Join the conversation on Hacker News: https://news.ycombinator.com/item?id=7465759