A Wish.....

  • Thread starter Thread starter Peter Kenyon
  • Start date Start date
P

Peter Kenyon

Hi,

I see that it's possible to apply attributes to function parameters.
Wouldn't it be great if the compilers could use these to generate
borderplate code, such as parameter checking.
Eg instead of typing

void MyFunction(string param1, int param2)
{
if(param1 == null)
throw new ArgumentNullException("param1");
if(param2 < 0)
throw new ArgumentOutOfBoundsException("param2");
if(param2 > 99)
throw new ArgumentOutOfBoundsException("param2");

// ......
}

you could simply type:

void MyFunction([NotNull] string param1, [Min(0), Max(99)] int param2)
{
// ......
}

Not only would this save a lot of time, it would also be less error-prone
(no chance of leaving out a validation check) and more self-documenting.

Just my 2 cents worth :-)

Peter
 
Peter Kenyon said:
Hi,

I see that it's possible to apply attributes to function parameters.
Wouldn't it be great if the compilers could use these to generate
borderplate code, such as parameter checking.
Eg instead of typing

This is indeed possible, using an interception-based AOP framework.
Basically, you inherit your objects from ContextBoundObject. This allows you
to ensure that all calls to the object have to cross a context boundary, and
your code can be placed in the call sink, allowing it to "listen" to the
calls made to the object. In this code you can probe the called method for
it's attributes, compare these against the passed-in methods and respond
(e.g. by throwing an exception).

Have a look at http://www.codeproject.com/csharp/AOPSimplestScenario.asp

There is a 30% performance hit with this approach and since your objects
have to inherit from ContextBoundObject, you can't use it for most existing
classes.
void MyFunction(string param1, int param2)
{
if(param1 == null)
throw new ArgumentNullException("param1");
if(param2 < 0)
throw new ArgumentOutOfBoundsException("param2");
if(param2 > 99)
throw new ArgumentOutOfBoundsException("param2");

// ......
}

you could simply type:

void MyFunction([NotNull] string param1, [Min(0), Max(99)] int param2)
{
// ......
}

Not only would this save a lot of time, it would also be less error-prone
(no chance of leaving out a validation check) and more self-documenting.

Just my 2 cents worth :-)

Peter
 
Back
Top