I'm terribly tired of checking all my arguments for null, and throwing ArgumenutNullExceptions when they are.
As I understand it, C# 4.0 enables some design by contract constructs. Will it be possible to specify that a method will not accept null arguments in C# 4.0?
Also, is there anything I can do in the meantime (maybe an attribute?) to avoid this monotonous task of checking for null and throwing?
It prescribes that software designers should define formal, precise and verifiable interface specifications for software components, which extend the ordinary definition of abstract data types with preconditions, postconditions and invariants.
Contract-based design is an approach where the design process is seen as a successive assembly of components where a component is represented in terms of assumptions about its environment and guarantees about its behavior.
A contract specifies in a precise and checkable way interfaces for software components. These software components are typically functions and methods, that have to fulfil preconditions, postconditions, and invariants.
The benefits of Design by Contract include the following: A better understanding of the object-oriented method and, more generally, of software construction. A systematic approach to building bug-free object-oriented systems. An effective framework for debugging, testing and, more generally, quality assurance.
You can create a NotNull<T>
generic class that helps, but there are some side effects. See Robert Nystrom's blog post.
Rick Brewster describes a good solution for concise, declarative style parameter checking in this post,
http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/
Avoids use of reflection (drawback of DbC) and creates no overhead for non-exceptional code path.
Like how he uses extension methods to allow what appears to be instance method calls on null objects. Very clever bit of coding IMO.
If you are sold on DbC, Google Spec# and PostSharp.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With