Surprising logic in Sitecore.MainUtil.GetBool()

This is a tale about the surprising logic in Sitecore.MainUtil.GetBool(), and an interesting interaction between it and Checkbox fields on an item. Let me start with the question, what’s wrong with this?

Well, there’s a few things to unpack…

Okay, so, the CanIndex field is a boolean field – so a checkbox in Sitecore. That’s fine, but the way checkbox fields work is a bit strange. A True value is a string “1”, and a False value is an empty string “”. Remember that last part.

You could say that the mistake is not properly getting the field as a typed CheckboxField, but honestly, just getting the value as a string is pretty common, as it is much more brief.

Then there is the GetBool() method. This accepts a string, and returns True or False. It also accepts a “default value”, presumably to be used if a value can’t be parsed as true or false… except… what is an empty string parsed as?

I found I had a problem that the above code – line 47 – never evaluated as true. The block of the if…then statement never happen, irrespective of whether the checkbox for CanIndex was true or not.

Intrigued, I inspected the implementation.

Right, let’s unpack that (and refactor for simplicity):

  • If the value is empty, return defaultValue (which may be true or false)
  • else if the value is “yes” return True
  • else if the value is “true” return True
  • else if the value is “1” return True
  • otherwise, return false.

So… if the checkbox is empty, GetBool() will receive an empty string… which means it returns the defaultValue … which could be True or False.

In other words, if the Checkbox is checked (“1”) GetBool() returns true (4th bullet point).
But if the Checkbox is unchecked (“”) GetBool() returns the defaultValue – which is set to true.

This method call can only ever return True. If the defaultValue was false, then it would behave as you would expect; it would return false for non-1/true/yes values.

One might ask what the point of a defaultValue is at all; might a logic of “If it’s not 1, ‘true’, or ‘yes’, return false” might be safer?

Interestingly, that buggy line has been in the solution for 7 years (we didn’t initially write it), and nobody realised that the <meta> tag for robots wasn’t ever rendered. And don’t get me started on why we have a checkbox for NoFollow, but it isn’t ever rendered at all….

Surprising logic in Sitecore.MainUtil.GetBool()

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.