Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing exception in c#, guard

Tags:

c#

exception

I had a discussion today about refactoring this (#1)

public void MyFunc(object myArgument)
{
    if(myArgument == null)
        throw new ArgumentNullException("myArgument");
....

With this (#2)

//inside a shared assembly in a class called Guard
public static void AgainstArgumentNull(object obj, string message)
{
    if (obj == null)
        throw new ArgumentNullException(message);
}

public void MyFunc(object myArgument)
{
    Guard.AgainstArgumentNull(myArgument, "myArgument");
....

My intuition was that #1 was better for the following reasons:

  1. #1 is simpler than #2 in the sense that it requires no knowledge of Util library, just basic c# knowledge
  2. #1 will not remove the resharper ability to rename the string passed to ArgumentNullException constructor.
  3. #2 will increase the dependencies for the code (must have access to the dll containing the dll)
  4. The stacktrace will not be the same for #2 as it would be for #1

My questions here are: Is my intuition correct? Could the fact that we are throwing the exception from another assembly not become trouble in some scenarios?

like image 605
Casper Leon Nielsen Avatar asked Oct 10 '22 10:10

Casper Leon Nielsen


1 Answers

You can also benefit from #2 in standardizing your exception handling to some degree across multiple projects; the abstraction also enables the library to be enhanced at a latter time and redistributed e.g. error logging for instance.

like image 104
gangelo Avatar answered Oct 20 '22 07:10

gangelo