I've just started using Code Contracts with .NET and I had a guard clause like this
if (!file.Exists(path)) throw FileNotFoundException();
and replaced it with
Contract.Requires(File.Exists(path));
I'm not sure this is correct, because the contract will be dealing with an I/O concern, but not sure if this is a problem or not.
Basically the question is: Is there any problem in using Contracts to ensure I/O concerns (or external/non-unit concerns)?
Whether a file exists is normally a pre-condition, you'd use Contract.Requires(). Enabling contract verification is optional and not normally turned on in the Release build. Which makes your test disappear.
Frankly, you shouldn't write code like this. Any attempt to use the file will generate an exception, it will be more informative than your version. It includes the name of the file that could not be found. More to the point, File.Exists() is unreliable on a multi-tasking operating system. The thread could be pre-empted right after the Exists() call and another thread in another process could delete the file. And you'll have a heisenbug on your hands: you'll get a FileNotFound exception, even though you tested that it existed.
My call: just delete the statement. It causes more problems than it solves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With