When I’m writing a function in a utility module to be used again, I tend to leave lots of comments at the top of functions and some simple input checks to throw up a message in the debugger if a function is used inappropriately, w/o simply using a throw command.
What’s the best methodology of handling such situations? What functionality is easiest to use for this in C#?
In my CS classes a decade ago, we would simply use an assert(…) command in C++ and let the program bomb out if something was used incorrectly.
Now that I’m using C# I’ve used two methods, throwing up a MessageBox.Show(‘…’) to clarify why a function is returning prematurely or a Console.WriteLine(‘…’) to have it explained only in the debug console.
I’m currently leaning toward writing a custom ErrorMessage function that would check the build type and possibly a #define master toggle before displaying anything and probably saving to a .log file if I’m in a beta environment.
What’s the best method to use in such utility modules?
If the method is being called with invalid arguments then it should throw an ArgumentException, or an exception derived from it. If the method is being called that cannot be called currently due to the state of the object then it should throw an InvalidOperationException.
Other people calling your library will not thank you for doing things in a non-standard or a non-obvious manner. Such as showing message boxes. Especially if they are calling your library from a web site or a windows service that can’t display UI. And outputting to the debug window is far too likely to get missed.