Salvo Davide Rapisarda

Italian developer thinks.

Function Parameter Constraint

As a developer every day I find myself in situations where I have to write different methods for purposes of any kind.  Generally, I write methods that take into one or more input parameters and return a particular result

Problems arise when my colleagues use the methods that I write. In particular, the biggest problems occur when they are specified in input values that are not valid for the execution of method.

Ok. I know that I can test each parameter before the execution of the real first instruction but it's a very frustration for a developer like me.

I think that can be nicely to have a mode for define at syntax level a constraint for a parameter of a method.

Something like :

<BetweenContraint(i,0,100)> _
Public Function TakeIntegerBetween0And100(ByVal i As Integer)

There is already something like this or I invented the wheel?

I know only looking for on Google or with a comment of some blog reader.

Comments

Brooke Vigola said:

You want to search for the Term: Design By Contract

en.wikipedia.org/.../Design_by_contract

VB.net nor C# have this. I've seen some stuff over at code project that you might want to look at, I don't think much of it is up to date.

# June 25, 2008 10:47 PM

Matt Hidinger said:

Hi Salvatore,

While I find this idea interesting, I don't think attributes would be able to would solve the problem. Since attributes are late-bound and typically discoverable via reflection, the parameter could not be validated until run-time.

Typically, the solution to this problem is to use XML documentation on top of the method:

/// <param name="i">An integer between 0 and 100</param>

This will provide intellisense support for anyone calling the method, but will obvioulsy not verify that the data passed is valid.

The typical solution to this isn't a perfect one, but in your example, I would throw an ArgumentOutOfRangeException("i", "Please enter an integer between 0 and 100");

# June 25, 2008 11:49 PM

Blackat.NET said:

Thanks to Matt and Brooke for response.

For Matt:

I know the solution of ArgumentOutOfRangeException with but I am very lazy programmer and I bored to throw Exceptio.

For Brooke:

Ok. Thanks for the tips.

# June 26, 2008 3:10 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)