Going back to the basics today. I personally worked on several programs where the authors have just wrapped all the code in a single function and it has worked! An example, suppose you are working on an ASP.NET website - just stuff everything into the page life cycle Page Load function!
But I am a firm believer in creating functions to segregate your code since it has the following advantages:
But I am a firm believer in creating functions to segregate your code since it has the following advantages:
- Problem solving: They allow us to conceive of our program as a bunch of sub-steps. (Each sub-step can be its own function. When any program seems too hard, just break the overall program into sub-steps!). [1]
- Code reuse: They allow us to reuse code instead of rewriting it. [1] This will also reduce the length of your code file.
- Garbage collection: Functions allow us to keep our variable namespace clean (local variables only "live" as long as the function does). In other words, function_1 can use a variable called i, and function_2 can also use a variable called i and there is no confusion. Each variable i only exists when the computer is executing the given function. [1]
- Unit testing: Functions allow us to test small parts of our program in isolation from the rest. [1] This is fantastic for Unit Testing. So is dependency inversion.
- Maintainability: It makes it easy to maintain the code since the length of your file is small. And further, if you make changes to the function the new code is automatically propagated to every where the function is called. On the other hand, if you have not created functions, you would have to change the code everywhere either by searching for it or waiting till your program crashes :).
Image source: Wikipedia |
When should you create functions?
- Duplicated code: When the same code repeats in several places. This was and still is a thumb rule.
- Long methods: All other things being equal, a shorter method is easier to read, easier to understand, and easier to troubleshoot. Refactor long methods into smaller methods if you can. [2]
- Single responsibility principle: If a method has more than one responsibility it can lead to a violation of SRP. [3]
References:
1. http://www.cs.utah.edu/~germain/PPS/Topics/functions.html
2. http://blog.codinghorror.com/code-smells/
3. http://programmers.stackexchange.com/questions/275646/is-the-single-responsibility-principle-applicable-to-functions