Refactoring 2: Extract Method

The ‘Extract Method’ is one of the most common refactorings you will ever do. It is also one you will frequently see implemented on the Refactor tool menu on various IDE’s.

What this method basically does is to take a group of related code and convert it to a function with a appropriate name that easily explains the purpose of the code. You can also use ‘Extract Method’ if one of your methods is too long or requires copious amount of comments to explain its purpose.
(more…)

Read More

Refactoring 1: Consolidating Conditional Expressions

As said in the previous post, I’m kick-starting the refactoring series with the ‘Consolidate Conditional Expression’ pattern. Bear in mind that the examples that will be given are deliberately made simple to keep the refactoring ideas in focus. So lets start with our first pattern.

Consolidate Conditional Expressions
Many times you see a group of conditionals where the returned values are the same. To make the code cleaner you can group the conditionals together using the ‘&&’ or the ‘||’ operators and then extract the code into a separate function. This also has the added benefit that you can reuse the extracted method in other places where the required conditional goes. Before using this pattern make sure that the grouped conditionals do not have any side-effects; i.e they do not change any variables.

A simple example is shown below:

Before refactoring:

class Security {
 
	private $_isHttps = true;
	private $_isAdmin = true;
	private $_totalLoginsPerDay = 19;
	.
	.
	.
 
	public function can_upload_file()
	{
		if($this->_isHttps == false) return 0;
		if($this->_isAdmin == false) return 0;
		if($this->_totalLoginsPerDay > 100) return 0;
 
		return 1;	
	}
}
 
$login = new Security();
echo $login->can_upload_file();

After refactoring:

class Security {
 
	private $_isHttps = true;
	private $_isAdmin = true;
	private $_totalLoginsPerDay = 199;
	.
	.
	.
 
	public function can_upload_file()
	{
		return $this->check_security_status();
	}
 
	private function check_security_status()
	{
		if($this->_isHttps == false || 
		   $this->_isAdmin == false || 
		   $this->_totalLoginsPerDay > 100)
			return 0;
		else
			return 1;
	}
}
 
$login = new Security();
echo $login->can_upload_file();

Read More

Refactoring: An introduction for PHP programmers

In the coming year I’ll be starting a series on Refactoring. Refactoring is one of those programming ideas besides Design Patterns and Unit Testing which has made an order of magnitude improvement in my productivity. Although refactoring may not be a ‘Silver Bullet’ for your programming woes, it is a good tool to add to your mental toolbox.

Refactoring is a process of changing code to make it more understandable and structured without changing the code functionality or introducing additional bugs. Informally it is known as ‘cleaning up code’. Refactoring is based on the tenet that the written code is more important to the human reader than it is to the machine. Many programmers write code with the idea that once the program is complete and working the code will not be touched again. But this seldom happens. Features need to be added, bug issues need to be fixed. This may happen tomorrow or months from now; wherein you need to really remember what a particular function did. Comments in the code may be useful, but not much if the code written is not differentiable from the half eaten spaghetti bowl sitting beside.

Code refactoring is not to be confused with code optimization. Code optimization is a completely different ball game, where the goal is to run the program as fast as possible by using as few CPU cycles as you can. The focus during optimization is to speed up the program, if it impedes code understandability then so be it. On the contrary refactoring may at times make your program slower, albeit most of the times by a small factor. A sample code adapted from the wonderful book is shown below:

// Before refactoring 
if($receiptDate < SUMMER_START || $receiptDate > SUMMER_END)
    $charge = $quantity * $winter_rate + $winter_service_charge;
else
    $charge = $quantity * $summer_rate;
/* After refactoring. The statements in the conditionals   
    have been refactored to functions. */ 
if(notSummer($receiptDate))
    $charge = winterCharge($quantity);
else
    $charge = summerCharge($quantity);

Many people refactor the code after the programming part is complete, many refactor as they go along. The important part is to test your code after refactoring. Unit tests are an indispensable part of this. Keep this maxim in mind – Always Test After Refactoring.

I’m planning to post one refactoring pattern every week or two. Although I could condense all the patterns in a lengthy post and be done with, I will resist that temptation. I want you to savour each pattern slowly so that you could remember and understand each of them like the back of your hand. There are more than fifty patterns catalogued by Fowler and others so it will help if we take it slowly. Most people after seeing the complete list of patterns become overwhelmed and confused and only remember a small percentage of them. Many patterns I’ll be posting will be self explanatory so I’ll do away with elaborate explanation. Refactoring is a habit and like all good programming habits it transcends the shifting landscape of technologies and languages.

Read More