I have a private static readonly field in my class:
public class MyClass
{
// ISSUE #1 -- requires unproven: path != null
private static readonly DirectoryInfo MyDirectory =
new DirectoryInfo(Settings.Default.MyDirectoryPath);
protected virtual void SomeMethod()
{
if (MyDirectory.Exists)
{
// ISSUE #2 -- requires unproven: !string.IsNullOrEmpty(path)
var catalog = new DirectoryCatalog(MyDirectory.FullName);
}
}
}
For issue #1 I used a null coalescing operator to default to some magic string and that fixed it, but I don’t really like that solution. I was hoping there was a better solution.
For issue #2 the only thing I can think of is using a Contract.Assumes because if I attempt to use Contract.Requires(MyDirectory.Exists || !String.IsNullOrEmpty(MyDirectory.FullName)); it complains about visibility (private field used in a requires on a protected method).
Issue #1 is a result of
Settings.Default.MyDirectoryPathbeing code generated by Visual Studio without any contracts on the property. This issue is not limited to null strings. Many API’s now have contracts that require say aTimeSpanto be non-negative but using a setting directly in the API will generate a Code Contracts warning.A way to solve this issue is to wrap the setting in a method that has a contract. E.g.:
Notice how the
Contract.Assumereally performs validation of your setting (which can’t be verified by Code Contracts because it is controlled by an external configuration file). Had it been aTimeSpanthat is expected to be non-negative you can either useContract.Assumeto do the validation resulting in aContractExceptionor some other method using your own exception instead.Adding this extra layer is somewhat tedious but because the setting is defined outside the application it needs to be run-time validated at some point just as you have to validate interactive user input.
Issue #2 is probably because
DirectoryInfodoesn’t have any contracts defined. The easist way is to useContract.Assume. This will make a statement about what you believe is the expected behavior ofDirectoryInfobut a run-time check will still be in place to ensure that your belief is correct (provided that you keep the checks in your code).