Lesson 5
Writing Reusable and Self-explanatory Programs
Chapter 4: Refactoring
Designing algorithms in a modular fashion
We have talked about refactoring existing codes to be modular, and at a good level of abstraction. You can sort of see this as a ‘bottom up’ approach to making your code modular. Write your code first, and then try to tidy it up.
But perhaps you should also consider designing your algorithms in such a modular fashion right from the start? Think of this as a ‘top down’ approach to structuring your code in a modular fashion before even coding it.
So, rather than one big piece of pseudocode, you now have lots of little pieces of pseudocode that can be pieced together like a jigsaw. Or you can have multiple smaller flowcharts, each flowchart representing a function. And if a flowchart gets a bit big and unwieldy, it might be a signal that you should consider breaking down the problem further.
This approach of thinking about your algorithm by breaking the problem into smaller chunks might make it less overwhelming for you to develop your solution.
You can think about the overall problem at a higher level (e.g. “generate prime numbers up to a maximum”, “check if a number is prime”, “check whether a number is divisible by x”), focussing on how different components/modules/functions fit together, and then ‘drill down’ to a lower level for the specific subproblems.
Ideally, each of your function should just focus on doing just one thing, rather than trying to accomplish everything. Think of each function as a team member being an expert in doing one thing, and if a team member seems to be overworked and juggling too many things at once, then perhaps you should start delegating the work to another new team member. Let the former can focus on what he or she is best at.
At a higher-level, you become a manager who tries to put team members together to achieve your goal as a team. So delegate each small task, and divide and conquer!
Of course, this is not always easy or possible to think fully ahead of time about all possible scenarios. Also, software requirements always change. Sometimes you can only see or figure out patterns after you have implemented your code. This is perfectly fine. ‘Top-down’ and ‘bottom-up’ approaches go hand in hand. As you gain more experience, you will start to instinctively know the best way to structure your program.
You will be trying to refactor your robot project later in the chapter, combining both a top-down redesign, and a bottom-up analysis of your existing implementation.