Programming

How to plan & design a custom function

  
  • Favourite
Average Star Rating is 3.4 from the Total 8 Ratings


In any programming language when planning & designing a custom function then some important factors must be considered.

This could be true for any programming language, but here I will be using PHP programming language to demonstrate what I mean.

Factors to be considered:

  1. Does this function do any calculations and returns value of the result?
  2. Will this function only be used to display some text messages from within? But will not return anything.
  3. Does this function’s responsibility is to check for something and confirm it by returning true or false only?
  4. Does this function only do one particular job?
  5. Can I reuse this function in another part of my program?
  6. Can this function be plugged, unplugged, moved, added to another script / or another project without effecting the existing code?
  7. Does this function required parameters?
  8. Will this function return any value, if so then what return type will that be?
  9. If this function does not have any positive value to return or fails then what is it’s default return type? Undefined, null, void or shall I use Boolean false?
  10. Does this function had to depend on another custom function to do it’s job?
  11. Will this function return just one value or will have to return multiple values such an arrays on success?
  12. Does this function has to depend on global variable (eg database connection object) or external class/ library?

 

Now, let's explore bit more of above points:

Factor 1 :

Example 1: This function will do the calculation and return the result.

<?php 
function add_numbers($x,$y){
   return ($x + $y);
}
echo add_numbers(10,10);
?>

 

Example 2: This function will show a message based on a condition but will not return anything.

<?php
function find_age_group($age){
   if($age < 13 ){
       echo "Child";
   } else if ($age < 18) {
       echo "Teenage";
   } else {
       echo "Adult";
   }
}
$age = 18;;
find_age_group($age);
?>

 

Example 3: This function's responsibility is to check for something and return true or false.

<?php
function challenge_21($dob){
   $age = date_diff(date_create($dob), date_create(date("Y-m-d")))->y;
   if($age >= 21){
       return true ;
   } else {
       return false;
   }
}

$dob = "10-01-2097";
if(challenge_21($dob)){
   echo "You have passed challenge 21 test !";
} else {
   echo "You have not passed challenge 21 test !";
}
?>

 

Analysis: Application of factors to our above three examples :

 

Example 1: Factor 1, 3, 4, 5, 6, 7, 8 are valid but not factor 2.

Example 2: Factor 2, 3, 4, 5, 6, 7 are valid but not factor 1.

Example 3: Factor 3, 4, 5, 6, 7, 8 are valid but not factor 1 & 2.

 

For factor 9, it is better to return false if the function does not have any positive value to return or fails, different programming languages use different default return type, JavaScript uses undefined, php uses null and some other programming languages use void, but planning to use a consistent Boolean false could help track it better, or an exception handling could be done. Consider following example.

<?php

# Most frequently drawn Powerball numbers for the past 10 years.

$numbers = array(20,37,2,31,35,42);

if($winning_number=check_number($numbers)){
   echo "Lucky Number is : $winning_number";
} else {
   echo "Sorry you did not win this time!";

}

function check_number($number_arr){
    $lucky_number = 35;
    $len = count($number_arr);
    for($i=0; $i<$len; $i++){
        if($lucky_number == $number_arr[$i]){
            return $lucky_number;
        } 
    }
    return false;
}
?>

 

In our above example if I ignore return false on line 22 then php will return null by default, which also implies nothingness, but I have planned to return false, I can keep this consistency throughout other languages so I know I have returned false on fail and hence can track it it better without thinking too much, we can also use exception but that is for another discussion or another tutorial.

For factor 10, it is better to avoid our custom function to be directly dependent on another custom function. Rather plan this on the function call by calling them orderly. Let's consider this example:

<?php

$quantity = 1;
$price = 100;
$total_amount = get_total($quantity,$price);
echo "£$total_amount (Price + 20% VAT)";

function get_total($quantity, $price){
    $total_amount = $quantity * $price;
    $total_amount = add_vat($total_amount,20);
    return $total_amount;
}

function add_vat($total_amount,$percentage){
   $percentage = $percentage /100;
    return $total_amount + ($total_amount * $percentage );
}

?>

This time our get_total() custom function using another custom function called add_vat() to add the VAT bit, this case get_total() function is taking extra responsibility. This case, get_total() function has dependency and we cannot use get_total() function if we just wanted to calculate total without VAT. Now consider second example :

<?php
$quantity = 1;
$price = 100;
$total_amount = get_total($quantity,$price);
$total_amount = add_vat($total_amount,20);
echo $total_amount;

function get_total($quantity, $price){
    return ($quantity * $price);
}

function add_vat($total_amount,$percentage){
   $percentage = $percentage /100;
   return $total_amount + ($total_amount * $percentage );
}

In our second example, both the custom functions are independent and dynamic. They both are performing just one and only task, hence these two functions are reusable and can be called separately. To get our expected outcome we just have to call them in particular order one after another! These two functions also dynamic as no parameters are fixed and they know what to do with the value of the passing parameter! They will always produce the same output for a given set of input. 

See my another tutorial on simple php based Shopping Cart where I have applied some of these techniques. 


Be the first to make a comment!