Avoid Specific Conditionals

 

From time to time, we all see awful programming. Today’s examples fall into this category. When I was a young programmer, I did this a few times. I’m pretty sure that it felt wrong writing code like this at the time, but I didn’t know any better, and anyway, we were under time pressure. Even the worst programming sins can be justified by time pressure, right?! ;-)

OK, here goes:

  if (client.CompanyName == "ABC Widgets Ltd")
  {
     // Display product subheader
  {

Or

  if (user.Username == "olaft")
  {
     // View a superset of data due to super-admin privileges.
  {

Pretty bad, right? However, unless we understand why code like this is damaging to a program, we will keep seeing such code.

In both these cases, we need custom behaviour for a specific client, user or other entity. Supplying this custom behaviour by setting up a conditional on the name of the entity is problematic. Sure, right now ‘ABC Widgets Ltd’ is the only client requiring a product subheader. However, later on, ‘XYZ Whatsits Ltd’ also wants the same subheader. Now we’ll need to make changes in our code to provide ‘XYZ Whatsits Ltd’ the same functionality:

  if (client.CompanyName == "ABC Widgets Ltd" || client.CompanyName == "XYZ Whatsits Ltd")
  {
     // Display product subheader
  }

Hmm, every time another client wants the product subheader, we must change the code, compile and redeploy the program! This approach to writing our software is inflexible.

What should happen instead?

We want to write our software so that its behaviour is extensible without us having to change code. Our code should be open to extension yet closed for modification—i.e. conform to the Open-Closed Principle.

Specifically, we want to rewrite these conditionals so we can reuse them, and we do not need to change the code when any client wants to view the product subheader:

  if (client.ShowProductSubheader)
  {
     // Display product subheader
  }

Similarly, we can make the second example generic:

  if (user.IsSuperAdmin)
  {
     // View a superset of data
  {

In conclusion, we ought to avoid hard-coding specific conditionals since they leave our code prone to frequent changes. Instead, program generic conditionals which do not require modifications when specific values change.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply