Decomposition is the concept of breaking code up into small chunks of code in order to make them more easily understood. When you open up some source code to find a 300-line function and huge, nested blocks of code it is a bit overwhelming. In an ideal coding world, each function or method should accomplish a single task. If a subtasks is of significant complexity it should be broken into multiple functions or methods. Let's say somebody asks you what a function or method your coded does and your answer is something like, “First it does this, then it does that; then, if one thing is true, it does A; otherwise, it does B,” you should probably have separate helper methods for This, That, One-thing, A and B.
Decomposition does not have a specific set of rules, by is guided by the code you are writing. You will find programmers who say that a function should not be longer than a page of printed code. That can be a good guide, but you can definitely find a quarter-page of code that is badly in need of decomposition.
For this class, we will focus on a few ideas:
- Any function/method should do one thing. Once it has accomplished this one task it should end.
- Once you have written a function/method and have decided it accomplishes its task, do NOT go back later and add something else to it just because it makes your life easier.
- Look for standard library functions and class methods that already do what you are wanting to do - you may find that the problem has already been solved.