Are Microsoft Code Contracts unsuitable for validating user input?

227 Views Asked by At

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

3

There are 3 best solutions below

1
On BEST ANSWER

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.

0
On

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).

0
On

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".