When I write code I have this strange habit to start my methods with code that just throws exceptions like this
public WhateverType MethodName(CrazyObjectType crazyObject, string para2){
if(crazyObject == null){
throw new ArgumentNullException("crazyObject");
}
if(param2 == null){
throw new ArgumentNullException("param2");
}
if(para2.Lenght > 32){
throw new ArgumentOutOfBoundsException("para2");
}
...
}
Consider s开发者_StackOverflow中文版ome methods have 6 parameters, non of them is allowed to be null and some of them are strings that might not be empty or longer then some value. You can imagine that before I get to actual method logic I write quite some code + my class will be harder to read.
Is there any tool/VS plugin/Resharper plugin/annotation/code snippet for me to not to have to write all this repetitive code ?
Ideal solution would be some declarative annotation something like:
[NotNull("crazyObject, param2")] [StringLenght("para2", 0, 32)]
public WhateverType MethodName(CrazyObjectType crazyObject, string para2){
...
}
- some VS/Resharper plugin that would allow refractoring such parameters so when I rename/refractor some parameter annotation will be synchronized automatically ?
And my ideal image goes even further and I imagine that I can have GUI to automatize process so that I select method click somewhere, check some check boxes for parameters that should not be null and annotation will be generated for me.
Does something like this exist ?
Note: I guess I can always create code snipper that will generate the code but declarative approach and GUI generator would me much better.
EDIT: Saying "Consider some methods have 6 parameters" is just an example - I don't think I have many if any such methods. Instead I should have written "consider you have a lot of methods that throw some 3-4 ArgumentException
s".
EDIT2: Bad terminology. I realized that what I call "annotation" everywhere in this question and my comments should be probably called "attributes" in .NET if I remember it correctly from my .NET classes.
While it's not strictly declarative, I think you should probably look at Code Contracts.
For a bizarre and not-really-recommended way of making null argument testing cheaper, have a look at this blog post. That only covers null argument checking though - not other kinds of validity.
By the way, there's nothing strange about the first part of a method just performing argument validation. It's entirely reasonable.
I agree with Jon on using Code Contracts. Something else you might find interesting is Fluent Validation.
精彩评论