Best way to assert precondition and post condition of arguments and values ​​in .NET?

I have been thinking about contract design lately, and I was wondering what people think is the best way to state the precondition and post-condition of values ​​in .NET? those. confirmation of the argument values ​​to the method.

Some people recommend Debug.Assert, while others talk about using an if statement plus throwing an exception. What are the pros and cons of each?

What frameworks are available to you to recommend?

+4
source share
5 answers

Ultimately, we will use Code Contracts when .NET 4.0 is shipped. However, in our production code, we had great success with the Security class along with the common way of throwing exceptions.

See my post on this for more details.

+3
source

Another option is Spe # .

Spe # is an extension of the object-oriented language C #. It extends the type system to include non-empty types and checked exceptions. It provides contracts for methods in the form of pre- and post-conventions, as well as invariants of objects.

+3
source

I prefer exceptions due to statements, because if it should be like that, and it isn’t, I want to know about it so that I can fix it, and the coverage that we get in debug mode is nowhere near real use or reach, so just using Debug.Assert is not enough.

Using statements means that you will not add bloat to your release code, but that means you can find out when and why these contracts will break if you catch them in the debug build.

Using exceptions means that you find that the contract is terminated whenever it happens, is debugged or released, but it also means that your version of the assembly contains more checks and code.

You can use the inbetween approach and use Trace to track the pre and post conditions for some application log that you could use to debug problems. However, you will need a way to collect log data to find out what problems your users are facing. It is also possible to comb this with exceptions, so you get exceptions for more serious problems.

The way I see it is that if the contract is worth it to justify, then it is worth throwing an exception when it breaks. I think a little up to the opinion and the target application. If you make exceptions, you probably want some form of incident reporting system to provide crash reports when the exceptions raised remain unhandled.

+1
source

You could take a look at the cursory structure at http://conditions.codeplex.com/ Its open source and free.

+1
source

Spe # is a way to do this, which is a superset of C #. Now you have Code Contracts ", which is the language version of Spe #, so now you can enter into code contracts in VB.NET, for example.

0
source

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


All Articles