Writing Function Code To Be More Readable

1st October 2008 - 3 minutes read time

Last month I started writing functions in a particular way, which has made my life as a programmer much easier on more than one occasion. No matter how many comments or verbose parameter names you put in you can end up writing code that you will get lost in. The reason is simple. Lets say you had a function that took in a couple of parameters.

  1. function myFunction($intNum1, $intNum2){
  2. // function does something
  3. }

Normal practice is to check the parameters to make sure that they are what you expected them to be before continuing on with the rest of the function. Let's say that we only want the numbers to be in a range. If they are not in the range the function should return false. Many programmers might start of writing something like this.

  1. function myFunction($intNum1,$intNum2){
  2. if($intNum1 > 0 && $intNum1 < 1000){
  3. if($intNum2 > 0 && $intNum2 < 1000){
  4. // do something with the numbers.
  5. return $value;
  6. }else{
  7. return false;
  8. }
  9. }else{
  10. return false;
  11. }
  12. }

This code will still produce the desired effect of checking to see that the numbers are within a range, but there is a simpler and more elegant way of doing this. For example, what if you wanted to add a third parameter, or a fourth? Having nested if statements is hard enough, but when you get to four levels things get a bit silly.

Here is the same code, but refactored in a way that allows for better readability and maintenance. Notice that the if statement logic has been reversed.

  1. function myFunction($intNum1,$intNum2){
  2. // check parameter 1
  3. if($intNum1 < 0 && $intNum1 > 1000){
  4. return false;
  5. }
  6. // check parameter 2
  7. if($intNum2 < 0 && $intNum2 > 1000){
  8. return false;
  9. }
  10. // do something with the numbers.
  11. return $value;
  12. }

This way, we get past all of the logic checking before getting down to what we want the function to do, and it is readable. Also, if you wanted to add another parameter you would just add another if statement to check that parameter. There if no juggling of nested statements or complicated syntax.

The above function also doesn't take into account the fact that the parameters might not be numbers, additional checking can be added at the top of the function to account for this.

I have posted this in the general category because I have used this technique in at least 3 different languages since I started doing it in PHP. All of the code written here is in generic PHP like syntax, but the idea stands. Hopefully, you should get something out of this as well.

Add new comment

The content of this field is kept private and will not be shown publicly.