Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sitecore - Assert.IsNotNull

I've seen few sample sitecore applications which uses the code below within the business logics:

 Database database = Factory.GetDatabase(itemUri.DatabaseName);
 Assert.IsNotNull(database, itemUri.DatabaseName);
 return database.GetItem(attribute);

Could someone please clarify if this is a sitecore convention. I've only used Assert for unit testing scenarios but not within logic.

Thanks.

like image 906
Nil Pun Avatar asked Mar 09 '13 00:03

Nil Pun


2 Answers

I found this article which addresses most of your question. There are a couple of important points:

  • The .NET Assert is not the same as the Sitecore Assert. At a minimum, the Sitecore Assert is a good deal more verbose.
  • It is considered best practice in Sitecore to use Asserts to check method inputs. (And you will find these Asserts consistently in Sitecore's code and the code in the Sitecore community (I can't tell you how annoying Field is null can be.))

I think it is also important to note that many of the examples I seem to be finding in the Sitecore blogs are cases where an exception would happen anyway. So, if ArgumentIsNotNull were to be omitted, for example, that would result in a NullObjectException, so an Assert actually cleans things up a bit. In your case, if the Database is unavailable, that would also cause a problem. An Assert makes it so that cause of the error is clear.

like image 57
cwallenpoole Avatar answered Sep 22 '22 09:09

cwallenpoole


It is a convention that can be seen heviliy used in the sitecore.dll's. It is used to throw an exception if that condition is not met.

For example if you look at Assert.IsTrue, if the condition is not met the system will throw a "InvalidOperationException"

De-compiling the a method from the Search API I found this.

  Assert.IsTrue(local_0 != null, "SearchConfiguration is missing");

Then if we de-compile IsTrue, it gives us

   [AssertionMethod]
public static void IsTrue([AssertionCondition(AssertionConditionType.IS_TRUE)] bool condition, string message)
{
  if (!condition)
    throw new InvalidOperationException(message);
}

To Answer your other question you can use this in your application code, as you can see its just another way of throwing an exception if a condition is not met.

The confusion comes with the use of the word assert, which as you said is usually seen in context of unit tests in a traditional c# .NET solution. As long as you know what the Sitecore assert is doing behind the scenes, its up to you if you want to use it or not.

like image 20
Isuru Fonseka Avatar answered Sep 24 '22 09:09

Isuru Fonseka