Functions in programming: a conceptual overview
What are functions?
Functions are modules or sections of code designed for a specific purpose or task. Simply put, they are essentially a mini-program within a program.
To better understand this, lets imagine an example:
As you hopefully know, whether it be digital or analog, a clock ticks indefinitely; the time is always augmenting throughout the day, forever adding a second, then resetting after 24 hours.
If you were to write a program modeling the behavior of a clock, it would be a hassle to manually add on each and every second that occurs throughout the day.
This is what we have functions. When we need to perform an action multiple times in a program, we use functions.
Therefore, with more specificity, functions allow you to perform a series of operations repeatedly without the hassle of writing them out all over again. They make it easy to reuse code when necessary, as we will see with the clock example.
For the clock example, a declared function could add the value of 1 to the timer count followed by a delay of 1000 milliseconds; then, the function could be called in a loop that would repeat a given number of times, thereby allowing you to avoid the hassle of writing each individual second - not that you would ever contemplate doing that to model a clock anyway, but the idea holds true. Programming without functions can be cumbersome, which leads me to the various benefits of using functions in your programs.
Benefits of using functions:
As you may have guessed, there are many benefits to using functions within your programs:
For one, they help you to stay organized; instead of one giant block of code, functions allow you to operate in modules of code, thereby allowing you to test various aspects of the code separately. For this reason, it is easier to conceptualize a program that contains functions against one that does not.
Along the same lines: functions are written separate from the main body of code, which makes debugging much easier, as you will come to observe when writing your own programs.
Because sections of code as functions can be performed and “called” many times, the whole program will be more compact and less cumbersome.
Lastly, if you need to recycle a piece of code, functions simplify the process by making it easy to remember which aspect of your program was responsible for what.
Check out my video on functions here!