Found during code review – Sitecore Settings

Any resemblance to the really existing code is coincidental and has not been the author’s idea.

TL;DR

In my opinion when you use Sitecore.Configuration.Settings, you should

  • Use default value where possible
  • Use existing methods to read bool, int, long, or timespan settings.
  • Name the settings uniquely, at least ‘ModuleName.SettingName’; otherwise, you can overwrite settings.
  • Spend a little time and learn basics about Sitecore settings or more time, and read about more advanced scenarios.

Below you can see a few examples that I found during code review.I removed all unnecessary code for clarity

How to get boolean value?

The goal for this small piece of code was to return boolean setting. The method body is the following:

var debug = Sitecore.Configuration.Settings.GetSetting("Debug");

return string.IsNullOrEmpty(debug) ||
 !debug.Equals("true", StringComparison.InvariantCultureIgnoreCase)

// How to improve this code?
  • Probably 99% of settings has a default value, if you use a method with a default value then check if the setting is null or empty is not required
  • Sitecore provides a method GetBoolSetting. If you will use the GetBoolSetting method than setting will be automatically converted to the bool type.
// Improved code is more straightforward.
 
return Sitecore.Configuration.Settings.GetBoolSetting("Debug", false);

How to get other types?

I also found the following cases where users write their conversion method and not using the existing one. The full namespace ‘Sitecore.Configuration.Settings’ was removed for clarity.

 result = Convert.ToInt32(Settings.GetSetting(key));

// Can be converted to
 Settings.GetIntSetting()
 result = Convert.ToInt64(Settings.GetSetting(key));

// Can be converted to
Settings.GetLongSetting()
return GetElapsedTime(Settings.GetSetting("ElapsedTimeWhenIdle"));

// Can be converted to
Settings.GetTimeSpanSetting()

There is also Settings.GetDoubleSetting and if you want go deeper, you can even read enum from Sitecore settings.

My advice for you

You may think these are just settings — a small, non-essential part of the whole code. But the way you read them may indicate your approach to the entire application and attention to detail.

I highly recommend that you familiarize yourself with this old but as it turns out unknown posts; and explore Sitecore.Settings by intellisense and dotPeek.

1 comment

Leave a comment

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