Software design is hard. Although getting the software to work is essential, it is also important to keep in mind the design of the software.
The four rules of simple design is an excellent guide to designing software. Kent Beck discovered the rules while he was developing Extreme Programming. It was then later expanded on by great minds like Martin Fowler, Ron Jeffries, and Corey Haines. Here are the four rules:
- Passes Tests
- No Duplication
- Reveals Intent
- Fewest elements
The order is important. Passes tests is the most important rule to follow, while minimal is the least important. There is some debate on the ordering of rules 2 and 3, and there’re many who would say that both are really on the same level, since there’s a lot of overlap. I will briefly explain each rule in this blog post.
The first rule is simply that all tests should pass. If there’re failing tests, then they should be fixed before moving on. This rule also implies that there’re already quality tests in place. The reason why this rule is the most important is because it gives you the most confidence in making changes. If you have good tests in place, then you have the confidence that when you change the code, your tests will tell you if something breaks. Think about it. If you have a choice between code with tests and code with no tests, which one would you rather work with?
Another way to say no duplication is DRY – Do not Repeat Yourself. Duplication can sometimes be misunderstood. This rule does not mean you should always make sure you don’t repeat anything in your code. The problem with duplication is that if you have to make a change, then you have to make a change in multiple places. This makes your code more brittle and difficult to navigate. However, sometimes duplicated code can be helpful if it better explains the intent, which brings us to our next rule..
In the words of Martin Fowler, “Any fool can write code that a computer can understand. Good programmers write code that humans can understand”. Good code reveals intent; this means that you can understand what the code is doing. This rule overlaps with no duplication. If removing duplication helps reveal intent, then remove it; otherwise, leave the duplication alone.
This is the last rule. Fewest elements means you have the fewest possible classes and methods. It reminds me of a quote by Blaise Pascal, “I made this(letter) longer because I did not have the time to make it shorter”. It is often easier to write more code than less. Of course, it is important to not go too far. If having more classes better express your intent, then keep the classes.
The four rules of simple design serve as a guide on designing software. I recommend keeping these rules in mind while refactoring. It is tempting to get the code working and move on, but by following these rules, you will create code that is adaptable and more readable.