Skip to main content
Engineering LibreTexts

2.4: Do I Need to Decompose a Bit

  • Page ID
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)


    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:

    1. Any function/method should do one thing. Once it has accomplished this one task it should end.
    2. 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.
    3. 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.

    This page titled 2.4: Do I Need to Decompose a Bit is shared under a CC BY-SA license and was authored, remixed, and/or curated by Patrick McClanahan.

    • Was this article helpful?