Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design by contract/C# 4.0/avoiding ArgumentNullException

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?

like image 826
core Avatar asked Jan 12 '09 00:01

core


People also ask

What is Design by Contract C#?

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.

What is contract based design?

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.

What are contracts in C?

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.

Why is Design by Contract useful?

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.


2 Answers

You can create a NotNull<T> generic class that helps, but there are some side effects. See Robert Nystrom's blog post.

like image 172
orip Avatar answered Oct 05 '22 06:10

orip


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.

like image 32
Matt Randle Avatar answered Oct 05 '22 06:10

Matt Randle