Question

I'm following the Fail Fast principal. I'm wondering whether it's good practice to have an Assertion class in place in order to check my constructor paramater arguments.

For example:

public static class Assertions
{
    public static void ParamterIsNotNull(object subject, string paramName = "")
    {
        if (subject == null) throw new ArgumentNullException(paramName, "Paramter cannot be null");
    }
}

and in use:

public class Test
{
    public Test(object obj)
    {
        Assertions.ParamterIsNotNull(obj, "obj");
    }
}

Is this good practice to offload the exception throwing to another class, or is it better to throw the exception directly in the constructor?

Was it helpful?

Solution

From what I've read (at the end of the article) Martin says it is good to do both things - fast fail, providing the meaningful exception and "slow fail" - giving the user the abillity to let's say contact support and continue with the tasks that can be completed succesfully no matter the exception.

The Batch system example was very nice in this case - although 1 item from the batch may be failling, the user will most probably want the rest to be dealth with, that's why you throw an exception that is caught by the global handler (the global handler decides to continue with the next item and aggregates the error so it can show it to the user and send notice to the dev team).

This way both are completed - most of the users work is done, and the fast fail principle is fired as well.

So it depends on your concrete case - maybe if your class participates in other operations there will be more global class (or a caller class that uses it) that will be able to better decide if it can go on or not.

On the other hand - your class shouldn't be able to tell if the calling class can do some other work in case of failure so you need to throw your exception in the constructor, yes. This is what I think - YES :). So if your class represents an item of the batch - the caller will most probably catch the exception and continue. If it is some kind of entry point class - then you probably want to gracefully handle the exception (or not throw it at all), show the user an error message and provide details (log) for the dev team to be able to easilly tell where the problem was.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top