Code Refactoring – Part 3

Making Conditions Easier to Read: There are many ways to do this, we will discuss on few out of them

1) Decompose Conditional: It means though conditions can be read easily even if they are complex in nature but can be difficult in future to read by another developer so break them in the form of method.

In first article, we have seen the below example

if((order.getTotal() > 99 && (stock.CheckStatus(order.getItem()) > order.getQuantity())) || _balance > 4000){
        Console.WriteLine(“Everything is fine.”);
}

and we have organised it by replacing the temporary variables.

This can be form as per below

if(checkOrderCustomerStatus()){
         Console.WriteLine(“Everything is fine.”);
}

public bool checkOrderCustomerStatus(){
     if((order.getTotal() > 99 && (stock.CheckStatus(order.getItem()) > order.getQuantity())) || _balance > 4000){
         return true;
     }
     return false;
}

2) Consolidate Conditional Expression: If you have code like below where you are checking multiple conditions and returning the common output then you can club those together.

if _balance > 0
return true;

if_isEmployee
return true;

Then what you can do, you can create a common method which will check these conditions and return the output.

Public bool Validate(){
  if(_balance > 0 || _isEmployee){
   return true;
  }
  else {
   return false;
  }
}

3)Consolidate Duplicate Conditional Fragments: It deals with the duplicate code, for example assume that you are performing some conditional checks, if condition meet then you are doing some calculation and the assigning the calculated value to a variable and then value you are passing to a function and same code you have return multiple time, then you can take out that code out and write only once.

Advertisements

#code-refactoring, #conditional-refactoring