.NET Code Contracts
As a developer, you want to guarantee that your code can only be used in the intended way and give proper results. Enforcing such constraints on interface usage with basic language constructs can be very problematic.
Type checking may be not detailed enough – it guarantees that function parameters and the return value will have particular types, but cannot impose other qualities.
Comments act like guidelines – they cannot be taken as a guarantee of any sort. The Developer is free to ignore them, and they are out of reach of automated validators.
Unit tests are great to guarantee that example scenarios work as desired, but cannot express general constraints nor check input that was not prepared upfront. Runtime assertions clutter the code and can slow it down or even introduce bugs because of the side effects.
This talk explains how to overcome these problems in .NET with Code Contracts. They are language-agnostic way to guarantee that your code is both used in a proper way (validation of inputs) and gives meaningful results (assertions on returned values and class invariants). Code Contracts are highly configurable (behaviour may differ during development, tests and on production). They can be used to fail unit tests, throw exceptions, generate additional documentation or provide hints for static analyzers.
Adam Gołębiowski is a Software Developer at NewVoiceMedia in the Payment Card Industry team.
His passion for C# programming goes back over 7 years where he started with hobbyist game development on the Unity engine. Adam spent the last 3 years working at LTE R&D division of Nokia, succeeding in the development of a static code analyzer and IDE for the TTCN-3 language. Since early high school, Adam was an administrator and contributor of theModders.org – a discussion board focused on hobbyist game and mod development.
He is a dedicated clean coder, security geek and addicted dreamer. He is also interested in writing, graphic and user experience design.
You can check out his homepage at avallach.ovh.