开发者

Are Microsoft Code Contracts unsuitable for validating user input?

开发者 https://www.devze.com 2023-01-13 21:13 出处:网络
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 progra

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

精彩评论

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