处理文件时代码约定使用模式
我刚刚开始在 .NET 中使用代码合约,我有一个像这样的保护条款,
if (!file.Exists(path)) throw FileNotFoundException();
并将其替换为
Contract.Requires(File.Exists(path));
我不确定这是否正确,因为合约将处理 I/O 问题,但不确定这是否正确是不是有问题。
基本上问题是:使用合约来确保 I/O 问题(或外部/非单元问题)是否存在任何问题?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
文件是否存在通常是一个前提条件,您可以使用 Contract.Requires()。启用合同验证是可选的,并且通常不会在发布版本中打开。这会让你的测试消失。
坦率地说,你不应该编写这样的代码。任何使用该文件的尝试都会生成异常,它将比您的版本提供更多信息。它包括无法找到的文件的名称。更重要的是,File.Exists() 在多任务操作系统上是不可靠的。该线程可以在 Exists() 调用之后立即被抢占,并且另一个进程中的另一个线程可以删除该文件。您将遇到一个 heisenbug:您将收到 FileNotFound 异常,即使您测试了它的存在。
我的建议是:删除该语句即可。它造成的问题多于它解决的问题。
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.