Introduce Explaining Variable

Introduce explaining variable is useful when there is an expression that is either complicated or difficult to read. Simply create a variable with a name that explains the purpose of the expression and store the result in the variable.

Simple Example

Let’s consider a very simple example where a developer is calculating the area of a circle. The programmer wrote the following correct code:

C#
if (HttpContext.Current.Request.Request.Browser.Browser.IndexOf("IE", StringComparison.OrdinalIgnoreCase) > 0 && HttpContext.Current.Request.Request.Browser.Platform.IndexOf("MAC", StringComparison.OrdinalIgnoreCase) > 0) {
  // this is IE on a MAC
  ClutchPearls();
}

The code is not very complex, but it is very difficult to read. The expressions in the if statement are long and it takes a little time to figure out what is going on.

To make this code even more clear, simply introduce variables for each expression and name the variables so that they explain the purpose of each expression.

C#
bool isIE = HttpContext.Current.Request.Request.Browser.Browser.IndexOf("IE", StringComparison.OrdinalIgnoreCase) > 0;
bool isMacOs = HttpContext.Current.Request.Request.Browser.Platform.IndexOf("MAC", StringComparison.OrdinalIgnoreCase) > 0;

if (isIE && isMacOs) {
  // this is IE on a MAC
  ClutchPearls();
}

The if statement is now extremely clear. Another way to approach this refactoring would be to use extract method and write each expression as a method. In that scenario the result would look like:

C#
private static bool isIE(HttpBrowserCapabilities browser) { 
  return browser.Browser.IndexOf("IE", StringComparison.OrdinalIgnoreCase) > 0;
}

private static bool isMacOs(HttpBrowserCapabilities browser) {
  return browser.Platform.IndexOf("MAC", StringComparison.OrdinalIgnoreCase) > 0;
}


if (isIE(HttpContext.Current.Request.Request.Browser) && isMacOs(HttpContext.Current.Request.Request.Browser)) {
  // this is IE on a MAC
  ClutchPearls();
}

The choice is up to you. If you introduce an explaining variable, it will be useful only in one method. If you extract methods, the methods are available throughout the entire class (and possibly to other classes depending on visibility and other factors). If you opt to extract methods, make sure you program defensively in the new methods to account for null objects and other conditions.

References

  • Fowler, M. et al. Refactoring: Improving the Design of Existing Code. Pearson Education, 2012. Web. Addison-Wesley Object Technology Series.
Scroll to Top