2015-05-01

Do not mess your code!

PHP is great language that gives us flexibility. PHP has weak typing. On the other side, many programmers abuse it. They create little monsters and spaghetti code.


In this post I will show you, on simple example, how you should prevent yourself from ambiguous return value.


Base principle: You should always return the same type.


My favorite example:


/**
* @return mixed
*/
public function getProductList()
{
   $resultArray = $this->products->get();


   return empty($resultArray) ? $resultArray : null;
}


What’s wrong with it? Return value is ambiguous. In next step in your code, after calling this method you must check what method returned to you.

if ($return === null) {
   //do something...
} else {
   //do something...
}


In this example you have two statements to check. More clear is this code:


/**
* @return array
*/
public function getProductList()
{
   $resultArray = $this->products->get();


   return $resultArray;
}

In above example, you always gets the same type of result. On the other hand, you may use designed pattern, but this is the other solution, not described in this post.

Brak komentarzy:

Prześlij komentarz