All about Sitecore.Diagnostics.Assert statements in Sitecore
Sitecore has a fundemental Assert(Sitecore.Diagnostics.Assert) which defers from the traditional .NET Debug.Assert. In general assertion are basically used to ensure the code or the condition is correct during the development and exception handling makes sure your code copes in unpredictable circumstances.
When to use Assertion and when to use an exception in Sitecore?
- Assertion can be used to check something that should never happen and exceptions are used to check something that might happen.
- use exceptions when checking parameters passed to public or protected methods and constructors
- use exceptions to address problems that might occur
- use exceptions when interacting with the user or when you expect the client code to recover from an exceptional situation
- use assertions when checking pre-conditions, post-conditions and invariants of private/internal code
- use assertions to provide feedback to yourself or your developer team
- use assertions to state things that you (supposedly) know to be true
- use assertions while creating the Sitecore module, adding some Sitecore UI module, logging the specific condition that casued the exception.
Asserting your code is a fast way of checking that conditions are met in a function before executing it. Below is a simple example of ArgumentNotNull Assert method.
void Page_Load(object sender, System.EventArgs e)
private void DoSomething(Item item)
Sitecore.Diagnostics.Assert.ArgumentNotNull(item, "item"); // Assertion
The example above throws an ArgumentNullException if the item parameter is null, and it even formats the exception message like this:
Value cannot be null.
Parameter name: item
Exploring Different types of Sitecore Assert Statements
Sitecore contains various assert statements which are used to throw different types of execption. Below are some of the popular assert methods :-
- AreEqual –The first method is AreEqaul which is used to compare two values for equality. It can compare strings, boolean, integers.
- ArgumentCondition, ArgumentNotNull, ArgumentNotNullOrEmpty – This method ensures that the argument passeed is not null or empty based on the method used.
- CanRunApplication – This is the best method available if you need to check security permissions. It returns an AccessDeniedException if the user does not have permission to access the application.
- HasAccess – It returns an AccessDeniedException if the condition fails.
- IsEditing – This is another useful method to detrmine if something is being edited. It returns EditingNotAllowedException if not in editing mode.
- IsFalse, IsNotNull, IsNotNullOrEmpty, IsNull and IsTrue – return an InvalidOperationException if the condition is not met. You have to format the exception message yourself.
- ReflectionObjectCreated- returns an UnknownTypeException if the condition is not met.
- Required – returns an RequiredObjectIsNullException when condition is not met.