I strongly agree with the 'contract' mataphor in API design, hence my interest in Spec# (that I've blogged about before).
To assist in this and to eliminate the tedium of writing argument checks, I've created 3 Resharper Live Templates. These check for
- null parameters for any object passed
- invalid parameters for any object passed
- null or empty check for any String passed.
These templates are called 'arg', 'argnull' and 'argempty' respectivly.
Resharper 1.5 doesn't allow importing or exporting of Live Templates from the GUI. They are however stored in an XML file at %userprofile%\Application Data\JetBrains\ReSharper\UserSettings.xml. Below is a chunk of XML that must be placed under the TemplateManager\Templates node. If you have any others, please let me know!
<Template text="if( $TYPE$$EXPRESSION$ )
 throw new ArgumentException( @"Cannot $ACTION$ as the value passed was invalid. Please provide a valid value.", @"$TYPE$" ) ;
" shortcut="arg" description="Throws an ArgumentException" kind="livetemplate" reformat="false" fileMask="" context="Everywhere" fileContext="CSharp" enabled="False" id="1723695683">
<Variables>
<Variable name="TYPE" expression="variableOfType("System.Object")" initialRange="0" />
<Variable name="EXPRESSION" expression="constant(" != 1")" initialRange="0" />
<Variable name="ACTION" expression="constant("PERFORM AN ACTION")" initialRange="0" />
</Variables>
</Template>
<Template text="if( $TYPE$ == null || $TYPE$.Length == 0 )
throw new ArgumentNullException( @"$TYPE$", @"Cannot $ACTION$ as the value passed was null or empty. Please provide a valid non null value." ) ;
" shortcut="argempty" description="Throws an ArgumentNullException when a string is null or empty" kind="livetemplate" reformat="true" fileMask="" context="Everywhere" fileContext="CSharp" enabled="False" id="1705884294">
<Variables>
<Variable name="TYPE" expression="variableOfType("System.String")" initialRange="0" />
<Variable name="ACTION" expression="constant("PERFORM AN ACTION")" initialRange="0" />
</Variables>
</Template>
<Template text="if( $TYPE$ == null )
throw new ArgumentNullException( @"$TYPE$", @"Cannot $ACTION$ as the value passed was null. Please provide a valid non-null value." ) ;
" shortcut="argnull" description="Throws an ArgumentNullException" kind="livetemplate" reformat="true" fileMask="" context="Everywhere" fileContext="CSharp" enabled="False" id="1497171628">
<Variables>
<Variable name="TYPE" expression="variableOfType("System.Object")" initialRange="0" />
<Variable name="ACTION" expression="constant("PERFORM AN ACTION")" initialRange="0" />
</Variables>
</Template>
No comments:
Post a Comment