Defensive programming framework for .NET Framework
github.com
github.com
http://www.postsharp.net/blog/post/Validating-parameters-fie...
BTW small typo in the comments of your second set of example code: "thorws"
An invalid argument parameter is certainly an exception. Human readable exceptions are a much better solution than the alternatives, such as return codes or returning null. What other solution would you propose? The only thing that could improve this even more is if the parameter named itself were visible, i.e. "buffer cannot be null" rather than "Value cannot be null"
Diving by 0 should yield exception for instance. Why not null? or odd when even numbers are expected? ...
I think the problem with all this is that you really want a type system that can do most of the validation job not at runtime, but at compile time.
Often OO languages force developers into some weird patterns (ex: value object) in order to mimic functional or algebraic types, at run time.
Contract programming with static predicates can help as well, I don't know if C# supports this.
[0]: https://github.com/Microsoft/CodeContracts
[1]: https://docs.microsoft.com/en-us/dotnet/framework/debug-trac...
However in reality it's easier to "defend" against bad input with ArgumentExceptions. Especially if input is a basic string or int, which can be null, negative etc.
I guess it's basically defending your method from errors in the caller method, while also keeping it flexible for the caller, by allow simpler unsafe types like strings.
Not sure if I like it or not.