Functions and Methods

Functions or Methods allow the programmer to take a bit of logic and encapsulate it to allow it to be easily used. When we build a function, thought should be made towards the reuse of the encapsulated logic.

Doesn't reuse and generalization make the resulting code somewhat larger? Usually it does, but at what cost? For one, improved maintainability of the code. Additionally, the overall code base becomes smaller since several versions of the code are replaced with a one slightly larger one.

OK, so the value of functions can be seen. How do we go about deciding what should be made into a function and what shouldn't? Let's ask the following questions. If any of the answers is yes, it is a candidate. If several are yes, it is a good candidate.

OK, how well did your target code meet the criteria? If none of the questions came up yes, you might still want to write a function. I won't stop you. But if you do, take reuse into account.

How to write functions

Remember the recipe example? We start by deciding what our function should do. Let's start with something simple, like a list of names we want to sort.


Fatal error: Uncaught Error: Class 'format' not found in /home/abentley/www/pages/pgm101/methods.html:53 Stack trace: #0 /home/abentley/_framework/library/framework.php(126): include() #1 /home/abentley/_framework/library/framework.php(60): FRAMEWORK::include_file() #2 /home/abentley/_framework/library/framework.php(1466): FRAMEWORK::respond() #3 /home/abentley/public_html/index.php(4): include_once('/home/abentley/...') #4 {main} thrown in /home/abentley/www/pages/pgm101/methods.html on line 53