I have found some common code patterns/refactoring patterns while doing code reviewing in my current day job. And one of them involves switch blocks. After reading nate’s blog here about switch blocks, I thought to share something similar. Following is an example code, where switch-case is used to configure some variables based on the value of $api_name.swicth($api_name) { case 'flickr': $class = 'Phlickr'; $subalbum = false; $auth = 'redirect'; break; case 'photobucket': $class = 'PBAPI'; $subalbum = true; $auth = 'redirect'; break; case 'smugmug': $class = 'PHPSmug'; $subalbum = false; $auth = 'direct'; break; // //}This is a good-looking handsome piece of code, no doubt about that. But the following is a definite smarter one,$api_settings = array( 'flickr' => array( 'class' => 'Phlickr', 'subalbum' => false, 'auth' => 'redirect' ), 'photobucket' => array( 'class' => 'PBAPI', 'subalbum' => false, 'auth' => 'redirect' ), 'smugmug' => array( 'class' => 'PHPSmug', 'subalbum' => false, 'auth' => 'direct' ), // );if(isset($api_settings[$api_key])) { extract($settings[$api_key]); }Design wise it is more flexible - you can just add an array in the $api_settings when a new api gets added to the list, it is slicker and handy when you have quite a few apis in your list. And performance wise, certainly hashes are faster than multiple conditional statements.Another way to avoid dumb switch-cases/conditional statements can be using the dynamic features of PHP (+ some conventions). Let’s have a look at the following code that uses switch-case to determine the method to execute,switch($type) { case 'users': $count = $this->__countUsers(); break; case 'projects': $count = $this->__countPojects(); case 'galleries': $count = $this->__countGalleries(); case 'tags': $count = $this->__countTags(); default: $count = 0;}We can convert it to something like this,$count = 0;$method = '__count'.ucwords($type);if (method_exists($this, $method)) { $count = $this->$method();}We have reduced lines of code. And is not it much prettier? And now if we need to add a new type there, we can just add a method following the same convention.Get rid of all your dumb conditionals… use PHP’s dynamic features ;)
