Emergence
Getting Clean via Emergent Design
What if by following some rules it waseasier to apply principles such as SRP and DIP? What if these rules facilitated the emergence of good designs?
A design is “simple” if it follows these rules:
- Runs all the tests
- Contains no duplication
- Expresses the intent of the programmer
- Minimizes the number of classes and methods
Simple Design Rule 1: Runs All the Tests
A system that is comprehensively tested and passes all of its tests all of the time is a testable system. Systems that aren’t testable aren’t verifiable. Arguably, a system that cannot be verified should never be deployed.
Fortunately, making our systems testable pushes us toward a design where our classes are small and single purpose. Whilst tight coupling makes it difficult to write tests.
Simple Design Rules 2: Refactoring
Once we have tests, we are empowered to keep our code and classes clean. We do this by incrementally refactoring the code. For each few lines of code we add, we pause and reflect on the new design. Did we just degrade it? If so, we clean it up and run our tests to demonstrate that we haven’t broken anything.
Simple Design Rules 3: No Duplication
Duplication is the primary enemy of a well-designed system. It represents additional work, additional risk, and additional unnecessary complexity.
Simple Design Rules 3: Expresiveness
In order to minimize the potential for defects as we introduce change, it’s critical for us to be able to understand what a system does. As systems become more complex, they take more and more time for a developer to understand, and there is an ever greater opportunity for a misunderstanding. Therefore, code should clearly express the intent of its author.
- You can express yourself by choosing good names.
- You can also express yourself by keeping your functions and classes small.
- You can also express yourself by using standard nomenclature. By using the standard pattern names, such as COMMAND or VISITOR, in the names of the classes that implement those patterns, you can succinctly describe your design to other developers.
Well-written unit tests are also expressive. A primary goal of tests is to act as documentation by example.
Minimal Classes and Methods
Even concepts as fundamental as elimination of duplication, code expressiveness, and the SRP can be taken too far. In an effort to make our classes and methods small, we might create too many tiny classes and methods. So this rule suggests that we also keep our function and class counts low.
Remember, however, that this rule is the lowest priority of the four rules of Simple Design. So, although it’s important to keep class and function count low, it’s more important to have tests, eliminate duplication, and express yourself.