3 ms·
Am I the only one that dislikes ArgumentExceptions - especially if I'm consuming a library (without source.) IMO - exceptions should be for exceptional situati
by GiorgioG 9y ago
Am I the only one that dislikes ArgumentExceptions - especially if I'm consuming a library (without source.) IMO - exceptions should be for exceptional situations, not invalid input handling.
- maccio92 9y agoexception - something excepted; an instance or case not conforming to the general rule. 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"
- nostalgeek 9y ago> Am I the only one that dislikes ArgumentExceptions - especially if I'm consuming a library (without source.) IMO - exceptions should be for exceptional situations, not invalid input handling. 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.
- usea 9y agoC# does have a feature called Code Contracts [0][1]. I haven't used them, and in my experience they aren't super popular. They look like mostly convenience for specifying when to throw, rather than as an alternative to throwing. There is some static capability, but I'm not sure what the extent of it is. [0]: https://github.com/Microsoft/CodeContracts https://github.com/Microsoft/CodeContracts [1]: https://docs.microsoft.com/en-us/dotnet/framework/debug-trace-profile/code-contracts https://docs.microsoft.com/en-us/dotnet/framework/debug-trac...
- gitgud 9y agoIdeally these cases would be caught at compile time, by using a rigid set of types. 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.