Using code templates when working with files

I was just starting to use Code Contracts with .NET, and I had a security offer like this

if (!file.Exists(path)) throw FileNotFoundException(); 

and replaced it with

 Contract.Requires(File.Exists(path)); 

I am not sure if this is correct because the contract will deal with the I / O problem, but not sure if this is a problem or not.

Basically the question arises: is there any problem when using Contracts to provide I / O problems (or external / non-proprietary problems)?

+4
source share
2 answers

If the file exists, it is usually a prerequisite, you should use Contract.Requires (). Enabling contract validation is optional and is usually not included in the Release assembly. Because of what your test disappears.

Honestly, you should not write such code. Any attempt to use the file throws an exception, it will be more informative than your version. It contains the name of a file that cannot be found. Moreover, File.Exists () is unreliable in a multitasking operating system. A thread can be pre-skipped right after calling Exists (), and another thread in another process can delete the file. And you will have a heisenbug on hand: you will get a FileNotFound exception, even if you tested its existence.

My call: just delete the statement. This causes more problems than it solves.

+6
source
  • If you do not know if the file exists, do not use exceptions.
  • If the file must exist, but cannot be in some exceptional cases, use exceptions.
  • If you are sure that it is a programming error that the file does not exist, use Contract.Ensures.
+3
source

Source: https://habr.com/ru/post/1314724/


All Articles