Functions
Last updated
Last updated
Are you tired of rewriting the same code over and over again? Well functions solve that! Functions in programming are reusable blocks of code that perform a specific task. Think of the steps to make a burger: cook patty, sandwich patty between two buns, and add vegetables. Now when you want to implement this, however, you have to arduously map out every substep. Instead of just cooking the patty, you have to grind up the filling, heat up the pan, etc. When you code out all these steps, the original 3 steps become increasingly hard to makeout. When you want to modify your code like by adding another patty, you have to scour your code to duplicate the original sandwich patty instructions. With functions, you don’t have to do that. Instead you can group the substeps into a single line of code. This way code can be easily duplicated and read. Now when you want to add an extra patty all you have to do is repeat the sandwich meat function.
Let's see functions in action.
Take the sample code:
At first glance it is difficult to understand what the series of motor controls do. Modifying the code is made even more confusing. When we break down the code, we can notice a pattern: set power on, sleep, set power off, report step is done. Some of the steps are even repeated like steps 3 and 4.
The first step is to put these sets of commands into functions. Using functions are simple, first name a function
And then insert the code that represents that function.
Now that you have created a function, in order to you use you can simply insert the function’s block where the original code was.
Now repeat for steps 2, 3, and 4.
Now the code is much more readable! Remember to use functions when coding. Although they may seem unnecessary, they are vital in organizing more complex code. They will be used extensively in the advanced lessons to help break down more complicated sections.