Always Separate Stable And Unstable Code
Recently we discovered a general truth – stable things should not depend on volatile things. If they do, then they too will become unstable by association.
Why does this matter in programming?
Say we are working with a messy legacy software system where high-level business logic is intermingled with data access code. The business logic hardly ever changes—it is stable. Conversely, the data access code is modified often to reflect changes to the database schema—it’s volatile. Since data access and business logic are united, business logic code is also affected whenever we modify data access logic. Business logic has become volatile by being closely associated with the unstable data access code.
We have a system where we must make more changes than we would like. And fewer changes are better.
OK, what might be a better system configuration?
It would be one where we affect fewer lines of code whenever we make a change.
Let’s consider two different 1,000 line systems:
System 1 is the one we have been considering all along. Business logic and data access logic are inseparably joined. Let’s assume changes always affect 10% of code in this system. Also, 80% of changes are to volatile data access code and 20% to stable business logic.
Under these conditions, how many lines of code do we modify for the average requirements changes? (For the sake of simplicity, I am assuming that we are adding no new code):
Lines changed: 1,000 lines * 10% = 100 lines.
In System 1, the average code change is 100 lines.
In another system, System 2, Business logic is separated from data access logic. There exists a one-way dependency from data access logic onto business logic. So, data access logic could be affected when we alter business logic, yet business logic is isolated from data access logic changes.
Data access logic modification: 500 lines * 10% = 50 lines
Business logic change: 1,000 lines * 10% = 100 lines
(Simplifying Assumption: Business logic change always affects data access logic)
System 2 average number of lines changed: 20% * 100 lines + 80% * 50 lines = 60 lines
In System 2, the average code change is 60 lines.
In this simplified model, System 2 experiences only 60 lines changed on average, while System 1 is much more volatile with 100 lines of code changing.
Stable code should not depend on or be mixed up with unstable code.
Always separate high-level stable and low-level unstable code.
We have just derived the rationale for the Dependency Inversion Principle.