开发者

Are Microsoft Code Contracts unsuitable for validating user input?

I've seen it written elsewhere on SO that while the Enterprise Library Validation Applicati开发者_开发问答on Block is geared towards validating user inputs, Code Contracts are meant to prevent programmer errors. Would you support this opinion? Why?


Yes.

Code contracts are meant to keep a strict programming interface, which only a developer can get right or wrong; a user shouldn't really be able to mess this up.

Validation is meant to validate the data; e.g. verifying data isn't null, or matches a regex.


Code contracts throw exceptions when they are violated. Invalid user input is not an exceptional condition so validation functions should generally not throw exceptions. That's why methods like TryParse were added to the Framework (the original Framework didn't have them, and it made validation cumbersome because of all the possible exceptions).


Code contracts are used to assert things that will always be true, and if they're not true, then there's a bug in the code. That means it can only apply to conditions that are controlled by code. So, you can't use them to state "the user will never supply an empty string", because that's outside of the control of the code. The static verifier will never be able to prove that statement - how can it know what the user will do?

What you can do is make statements like "Given a user input, the method will either return a non-empty string or throw an exception".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜