C # exception exception, protection

Today I discussed the reorganization of 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 number 1 was better for the following reasons:

  • # 1 is simpler than # 2 in the sense that it does not require knowledge of the Util library, just basic knowledge of C #
  • # 1 will not remove resharper's ability to rename the string passed to the ArgumentNullException constructor.
  • # 2 will increase the dependencies for the code (should have access to the dll containing the dll)
  • stacktrace will not be the same for # 2, as it would for # 1

My questions are: Is my intuition correct? Could the fact that we throw an exception from another assembly not become a problem in some scenarios?

+4
source share
2 answers

In this particular case, you should not use Guard in any way. You must use Code Contracts.

 Contract.Requires(myArgument != null); 
+2
source

You can also benefit from # 2 in standardizing exception handling to some extent in several projects; abstraction also allows you to improve the library for the last time and redistribute it, for example. for example, an error log.

+2
source

All Articles