Skip to content

Instantly share code, notes, and snippets.

@Cygon
Last active October 26, 2017 14:44
Show Gist options
  • Save Cygon/7a34c4336d9c07c35cde4680c88c6ca2 to your computer and use it in GitHub Desktop.
Save Cygon/7a34c4336d9c07c35cde4680c88c6ca2 to your computer and use it in GitHub Desktop.
Document Conditions with Local Variables

Document Conditions with Local Variables

When many factors weigh into a condition, the condition statement can become unreadable, especially if combined with a poor line wrapping technique. This is a very basic technique that achieve much better readability when writing conditions.

DO NOT: Write complex conditions directly in if statements

As an example, take this if statement that checks whether a procedural texture showing a diagram can be reused or whether a new one needs to be created:

if((this.cachedFadeChart == null) || (width != this.cachedWidth)
   || (height != this.cachedHeight) || (materialEvent.LeftAlpha != this.cachedLeftalpha)
   || (materialEvent.RightAlpha != this.cachedRightAlpha)) {
  this.cachedFadeChart = new Texture2D(width, height, TextureFormat.ARGB32, false);
  // ...
}

The readability is very poor.

Skimming over the code, the reader needs to completely parse the conditions, deliberate over what common aspect connects them, possibly even read inside the if statement to understand what is being tested here.

DO: Use local variables to name the condition being checked

A simple tweak will greatly improve readability:

bool newTextureNeeded = (
  (this.cachedFadeChart == null) ||
  (width != this.cachedWidth) ||
  (height != this.cachedHeight) ||
  (materialEvent.LeftAlpha != this.cachedLeftAlpha) ||
  (materialEvent.RightAlpha != this.cachedRightAlpha)
);

if(newTextureNeeded) {
  this.cachedFadeChart = new Texture2D(width, height, TextureFormat.ARGB32, false);
  // ...
}

The local boolean variable can be easily optimized away by modern compilers.

Debugging becomes easier as the boolean can be checked and even used in conditional breakpoints.

Most importantly, a reader skimming the code can immediately see the purpose of the if statement - in this case, if the method decided that a new texture is needed, create a new texture. What is the purpose of all those comparisons? Seeing the boolean right in front of them, the reader sees that they decide whether a new texture is needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment