How often should we be defining and using our own functions



We learn here that functions are the primary way that we define abstractions in programming. How do we decide when to write a section of code as a function?


The quick answer is that we should almost always be looking for opportunities to divide our programs into functions. This helps our programs to be more compact, readable, and manageable.

Choosing how to divide our programs into functions requires that we be thoughtful; the key is to find the right level of generality. For instance, don’t write multiple functions like add2toNumber(x), add7toNumber(x), etc. Instead define a function like increment(x,n) which will add n to x. This is a silly example of course but it is meant to highlight the importance of finding the bigger problem that we’re solving – we’re not adding 2 or 7 to a number; we’re incrementing a number.

Searching for the bigger problem that you’re solving with some code will guide you in defining functions and will also make sure that you’re not defining unnecessarily many.