(Implicitly) Creating Bugs

October 28, 2007 § Leave a comment

How to (eventually) shoot yourself in the foot.

A personal pet peeve of mine is when people write code to solve a problem by using indirect information.  Take the following real life (but obfuscated) example:

// if we are running product A, then hide ui component if (IsFeatureXEnabled()) { HideUIComponentWhichIsUnrelatedtoFeatureX(); }

The ‘if’ statement assumes that the ‘UI Component’ will always, only be available to ‘product A’, because ‘Feature X’ is only available in ‘product A’.  The problem becomes obvious when you ask the questions "What if we enable ‘Feature X’ for product B, but want to show ‘UI Component’?"; "What if ‘Feature X’ is removed?"  If either of these changes occurred, this code may not function as originally intended.  The bug may become obvious and the fix easy to implement, but it never needed to happen.  It is always best to use explicit, rather than implicit expressions to invoke behavior.

Here is one way you could correct the above code:

// determine if we need to hide ui component if (ShouldHideUIComponent()) { HideUIComponentWhichIsUnrelatedtoFeatureX(); }

In the above example, the dependency on the presence of ‘Feature X’ has moved to a method dedicated to answering the question ‘Should UI Component be hidden’.

Where Am I?

You are currently browsing the Implementation category at Journeyman.