Skip to content

Instantly share code, notes, and snippets.

@guillegette
Last active August 29, 2015 14:18
Show Gist options
  • Save guillegette/da63d24880334518af3d to your computer and use it in GitHub Desktop.
Save guillegette/da63d24880334518af3d to your computer and use it in GitHub Desktop.
Improved set function
/**
* Original
* Set name of the the item
*
* @param string $name
*/
public function setName($name = "")
{
if (empty($name)) {
throw new \Exception("Item name can't be empty");
} else {
$this->name = $name;
}
}
/**
* Improved
* The problem with the previous approach was that if $name is a boolean or soehting like " " the exception wouldn't be fired
* We need to add some extra checks on the varialbe $name
*
* @param string $name
*/
public function setName($name = "")
{
$name = trim($name);
if (empty($name) || !is_string($name)) {
throw new \Exception("Item must be a string and can't empty");
}
$this->name = $name;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment