mandag den 25. november 2013

To assert or not to assert, thats a good question

It's no secret among people that work with me, that I really don't like the way Sitecore is misusing the Assert word.

The problem is, that Sitecore's Assert class, and the standard .NET Debug.Assert works fundamentally different, which can become a big problem, if people starts to learn the way Sitecore uses it, and then later on gets to work with other things than Sitecore.

So, when you in Sitecore have a function, that takes a parameter, and validates it like this:

public string IsItemMediaItem(Item item)
{
    Assert.ArgumentNotNull(item);

    return item.Paths.IsMediaItem;
}

I know this is a bad example, but it illustrates the problem, which is, that now we are using Assert to validate input parameters, which works just fine... in Sitecore.

Now lets say that the same code was written without Sitecore (Ignore the classes is called the same):

public string IsItemMediaItem(Item item)
{
    Debug.Assert(item != null);

    return item.Paths.IsMediaItem;
}

Now the problem starts to show, since normal .NET Assert only gets executed in Debug builds, so when you build your code as a Release build, the Debug.Assert line is removed, which now means your code no longer validates it's input!

It gets worse, once you start using this with input from clients, since you should always validate this.

That's why I always recommend people to do input validation this way, since that doesn't give them and other people bad habits.

This, on the other hand, is the "right" way to it:

public string IsItemMediaItem(Item item)
{
    if (item == null)
    {
        throw new ArgumentNullException("item", "item must not be null");
    }

    return item.Paths.IsMediaItem;
}

This works every time, on every system.

So Sitecore, if you read this, please mark your entire Assert class as obsolete, and start teaching people how to do real input validation, instead of something that will make them write bad code everywhere else.

Ingen kommentarer:

Send en kommentar