Writing Function Code To Be More Readable

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.

function myFunction($intNum1, $intNum2){
 // function does something
}

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.

function myFunction($intNum1,$intNum2){
 if($intNum1 > 0 && $intNum1 < 1000){
  if($intNum2 > 0 && $intNum2 < 1000){
   // do something with the numbers.
   return $value;
  }else{
   return false;
  }
 }else{
  return false;
 }
}

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.

function myFunction($intNum1,$intNum2){
 // check parameter 1
 if($intNum1 < 0 && $intNum1 > 1000){
  return false;
 }
 // check parameter 2
 if($intNum2 < 0 && $intNum2 > 1000){
  return false;
 }
 // do something with the numbers.
 return $value;
}

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.
CAPTCHA
3 + 11 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.