Refactoring Day 16 : Encapsulate Conditional


Sometimes when doing a number of different checks within a conditional the intent of what you are testing for gets lost in the conditional. In these instances I like to extract the conditional into an easy to read property, or method depending if there is parameters to pass or not. Here is an example of what the code might look like before:

   1: public class RemoteControl
   2: {
   3:     private string[] Functions { get; set; }
   4:     private string Name { get; set; }
   5:     private int CreatedYear { get; set; }
   6:  
   7:     public string PerformCoolFunction(string buttonPressed)
   8:     {
   9:         // Determine if we are controlling some extra function
  10:         // that requires special conditions
  11:         if (Functions.Length > 1 && Name == "RCA" && CreatedYear > DateTime.Now.Year - 2)
  12:             return "doSomething";
  13:     }
  14: }

After we apply the refactoring, you can see the code reads much easier and conveys intent:

   1: public class RemoteControl
   2: {
   3:     private string[] Functions { get; set; }
   4:     private string Name { get; set; }
   5:     private int CreatedYear { get; set; }
   6:  
   7:     private bool HasExtraFunctions
   8:     {
   9:         get { return Functions.Length > 1 && Name == "RCA" && CreatedYear > DateTime.Now.Year - 2; }
  10:     }
  11:  
  12:     public string PerformCoolFunction(string buttonPressed)
  13:     {
  14:         // Determine if we are controlling some extra function
  15:         // that requires special conditions
  16:         if (HasExtraFunctions)
  17:             return "doSomething";
  18:     }
  19: }

This is part of the 31 Days of Refactoring series. For a full list of Refactorings please see the original introductory post.

Refactoring Day 15 : Remove Duplication