Knowledge and Responsibility

A mantra for software design

Knowledge and Responsibility

A mantra is a memorable phrase you repeat to yourself for guidance. 'Focus and simplicity' was one of Steve Jobs's. I love how he distilled his thought process into those two words. It made me wonder if I could come up with one that’ll influence its thinker to craft code that’s flexible, more robust, and easier to understand. I like to separate my code such that each bit has a single responsibility and knows as little as possible about the others. 'Knowledge and responsibility' is the mantra I extracted from this approach.

Responsibility is about how you separate your concerns. This concept speaks to cohesion. The Single Responsibility Principle is used to do so. In a nutshell, it says you should separate your code such that each bit serves the needs of a single actor. An actor (from UML) is the role played by an entity (human or computer) at a particular moment.

When a barista makes coffee, they can be seen as a 'coffee maker' actor. When they clean the coffee machine, they can be seen as a ‘coffee-machine cleaner’. If you were to develop the software of the coffee machine, you’d have a module for each of these actors. Not one for a barista. Nor none at all. After establishing modules, figure out how to make each one know as little as possible.

Knowledge is about source-code dependencies. This concept speaks to coupling. A bit of code knows about another if it depends on it. This can be risky because the more code knows, the more fragile it becomes. If module A depends on module B, it can be affected by changes to B. Such changes could break A. If A also depends on C and D, even more things can affect it! A should, therefore, know about as little as possible. You may also discover the less code knows, the easier it's to understand.

The Stable Dependencies Principle helps me to determine if a module may know about another. It says modules may not depend on less stable ones. It can also guide you to clean source-code architecture, with layers and a prominent boundary that separates business rules from input/output (I/O) code. There's more to be said about stability. For now, note it's something you’ll need in your repertoire if you’d like to master making code know less.

There you have it! Knowledge and responsibility. A mantra that can help you to write cleaner code with high cohesion and low coupling.