Nunit: Phasing out the Guard class

Created on 24 Sep 2018  ·  4Comments  ·  Source: nunit/nunit

ReSharper and (in recent years) Visual Studio suggest inserting ArgumentNullException and similar argument checks. It's such muscle memory that I've introduced them by accident to the codebase several times.

Throwing directly is more idiomatic C# from the standpoint of flow control analysis. The C# compiler understands that you don't need to return a value or initialize a variable before usage or break from a switch case if you use throw rather than Guard. ReSharper's null flow check is the same way.

Also, with C# 7.0, throw expressions can be convenient. For example, the syntax _foo = foo ?? throw new ArgumentNullException(nameof(Foo));.

What are other pros or cons of allowing contributors and ourselves to throw exceptions directly instead of using Guard?

Most helpful comment

I personally like the guard class - but I agree theres a discoverabilty issue. I would normally suggest it to regular contributors, but not mention it to one-off contributors. I don’t think this is an area we particularly need consistency, is it? I’m happy to see it when it’s there, but not worried when it’s not.

I’m fairly apathetic to the outcome of this issue, either way is fine for me 😊

All 4 comments

The main pro for using the Guard class is ease of use, if I'm remembering correctly. In a C#-aware IDE, it's no longer the easiest option for me or new contributors. Do we need consistency, all one way or all the other way? Consistency pits what's easiest for some of us against (potentially) what's easiest for others of us.

I personally like the guard class - but I agree theres a discoverabilty issue. I would normally suggest it to regular contributors, but not mention it to one-off contributors. I don’t think this is an area we particularly need consistency, is it? I’m happy to see it when it’s there, but not worried when it’s not.

I’m fairly apathetic to the outcome of this issue, either way is fine for me 😊

I am also somewhat apathetic about it. It does provide consistency and correct usage of exception constructors (I've seen the message and parameter name backwards a few times), but it does also add an extra method to the callstack. Plus, as you say, the new C# syntax makes it much easier.

I'm not sure we need a wholesale purge, but I'm fine with not requiring it.

Thanks all, sounds good!

Was this page helpful?
0 / 5 - 0 ratings