Don’t ignore Sitecore Diagnostics Assert
Another useful feature from Sitecore framework that is not being used by most of the developers. If you want to write clean code for checking many condition then you must use Assert class. Assert class is in Sitecore.Kernel.dll and namespace is Sitecore.Diagnostics.
For example: If you are developing a custom processor and overriding ProcessCore method then parameter args can’t be null. So, we must check for null. If condition is met then continue otherwise an exception is thrown.
protected override void ProcessCore([NotNull] IdentityProvidersArgs args)
{
if (args == null)
{
throw new Exception("args can't be null");
}
//your logic
}
The above piece of code will work but you can write less and more clean code to achieve the same functionality.
protected override void ProcessCore([NotNull] IdentityProvidersArgs args)
{
Assert.ArgumentNotNull(args, " args can't be null");
//your logic
}
Other benefit of this code is that the exception thrown by this code is Sitecore exceptions and appear in the Sitecore log.
Other useful methods are available in Assert class is listed below:
Assert.AreEqual
AreEqual method compares two values. Below are the overloaded methods for AreEqual
Assert.CanRunApplication
This method takes applicaton name as parameter and check the current user can run the application or not.
Assert.HasAccess
This method used to check the context user access.
Assert.ResultNotNull
This method returns a value after validating the object passed in is not null. For validation it calls Assert.ArgumentNotNullOrEmpty
Assert.Required
This method used for null exception check.
Assert.IsEditing
Before editing any item, you can call this method to determine that context item is editable or not.
Please share your feedback on this article.