{"id":859,"date":"2018-04-04T09:54:39","date_gmt":"2018-04-04T09:54:39","guid":{"rendered":"http:\/\/cppdepend.com\/blog\/?p=859"},"modified":"2018-04-06T14:01:07","modified_gmt":"2018-04-06T14:01:07","slug":"defensive-programming-with-new-c-standards","status":"publish","type":"post","link":"https:\/\/cppdepend.com\/blog\/defensive-programming-with-new-c-standards\/","title":{"rendered":"Defensive programming with new C++ standards"},"content":{"rendered":"<p><b>Defensive programming<\/b>\u00a0is a form of\u00a0defensive design\u00a0intended to ensure the continuing function of a piece of\u00a0software\u00a0under unforeseen circumstances. Defensive programming practices are often used where high availability, safety or security is needed.<\/p>\n<p>Defensive programming is an approach to improve software and source code, in terms of:<!--more--><\/p>\n<ul>\n<li>General quality \u2013 reducing the number of\u00a0software bugs\u00a0and problems.<\/li>\n<li>Making the source code comprehensible \u2013 the source code should be readable and understandable so it is approved in a\u00a0code audit.<\/li>\n<li>Making the software behave in a predictable manner despite unexpected inputs or user actions.<\/li>\n<\/ul>\n<p>The usual way to\u00a0adopt\u00a0 a defensive programming approach in C++\u00a0 is the use of assert facility:<\/p>\n<pre>    void test( int *p ) {\r\n        assert( p != 0 );\r\n        if (p == 0)\r\n            return;\r\n        \/\/ use p.\r\n    }<\/pre>\n<p>An assertion is code that\u2019s used during development\u2014usually a routine or macro\u2014that allows a program to check itself as it runs. When an assertion is true, that means everything is operating as expected. When it\u2019s false, that means it has detected an unexpected error in the code.<\/p>\n<p>Assertions are especially useful in large, complicated programs and in high-reliability programs. They enable programmers to more quickly flush out mismatched interface assumptions, errors that creep in when code is modified, and so on.<\/p>\n<p>An assertion usually takes two arguments: a boolean expression that describes the assumption that\u2019s supposed to be true and a message to display if it isn\u2019t.<\/p>\n<p>What do the new C++ standards provide as mechanisms to do a defensive programming?<\/p>\n<p><strong>C++11 and static assert<\/strong><\/p>\n<p>C++11 introduces a new way to test assertions at compile-time, using the new keyword static_assert, this feature is very useful to add conditions to the template parameters, as shown in this template class from Folly source code:<\/p>\n<p><a href=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/c3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-442\" src=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/c3.png\" alt=\"c3\" width=\"733\" height=\"213\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p><strong>C++17 and the [[nodiscard]] attribute<\/strong><\/p>\n<p>Functions declared with\u00a0<code class=\"highlighter-rouge\">[[nodiscard]]<\/code>\u00a0should not have their return values ignored by the caller. This can be useful if you want to ensure that callers check a return value.You can enforce the code contract for a function so that the caller won\u2019t skip the returned value.<\/p>\n<p>For example, if the return value of the function do_something is not used, the compiler will emit a warning.<\/p>\n<pre><code class=\"language-cpp\" data-lang=\"cpp\"><span class=\"p\">[[<\/span><span class=\"n\">nodiscard<\/span><span class=\"p\">]]<\/span> <span class=\"n\">error<\/span> <span class=\"n\">do_something<\/span> <span class=\"p\">(<\/span><span class=\"n\">thing<\/span><span class=\"o\">&amp;<\/span><span class=\"p\">);<\/span>\r\n\r\n\r\n<span class=\"n\">do_something<\/span><span class=\"p\">(<\/span><span class=\"n\">my_thing<\/span><span class=\"p\">);<\/span> <span class=\"c1\">\/\/ Warning: ignored return value<\/span><\/code><\/pre>\n<p><strong>C++20\u00a0and contracts<\/strong><\/p>\n<p>This is the big improvements to the defensive programming from the new standards. It will provide many facilities and features to design by contract.<\/p>\n<p>you can discover the proposal <a href=\"http:\/\/www.open-std.org\/jtc1\/sc22\/wg21\/docs\/papers\/2017\/p0542r0.html\">here<\/a>.<\/p>\n<p>Let&#8217;s first discover the terminology from the proposal of the contracts feature :<\/p>\n<pre>1. A\u00a0<i>precondition<\/i>\u00a0is a predicate that should hold upon entry into a function. It expresses a function's expectation on its arguments and\/or the state of objects that may be used by the function. Preconditions are expressed by\u00a0<tt>expects<\/tt>attributes (7.6.10).\r\n\r\n2. A\u00a0<i>postcondition<\/i>\u00a0is a predicate that should hold upon exit from a function. It expresses the conditions that a function should ensure for the return value and\/or the state of objects that may be used by the function. Postconditions are expressed by\u00a0<tt>ensures<\/tt>\u00a0attributes (7.6.11).\r\n\r\n3. An\u00a0<i>assertion<\/i>\u00a0is a predicate that should hold at its point in a function body. It expresses the conditions, on objects that accessible at its point in a body, that must be satisfied. Assertions are expressed by\u00a0<tt>assert<\/tt>\u00a0attributes (7.6.12).\r\n\r\n4. Preconditions, postoconditions, and assertions are collectively called\u00a0<i>contracts<\/i>. A contract shall have no observable effect in a correct program (a program where all contracts would be satisified, if they were evaluated).\r\n\r\n5. Contract attributes are followed by a\u00a0<i>conditional-expression<\/i>, which is a potentially evaluated expression (3.2). \r\n\r\n<\/pre>\n<p>And here&#8217;s an example of the use of this new feature:<\/p>\n<pre><b>\r\nvoid push(int x, queue &amp; q)\r\n  [[expects: !q.full()]]\r\n  [[ensures: !q.empty()]]\r\n{\r\n  \/\/...\r\n  [[assert: q.is_valid()]];\r\n  \/\/...\r\n}<\/b><\/pre>\n<p>The C++20 standard will bring the missing features for the defensive programming adopters, no need to use an external library or framework to design by contract.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Defensive programming\u00a0is a form of\u00a0defensive design\u00a0intended to ensure the continuing function of a piece of\u00a0software\u00a0under unforeseen circumstances. Defensive programming practices are often used where high availability, safety or security is needed. Defensive programming is an approach to improve software and source code, in terms of:<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[13],"class_list":["post-859","post","type-post","status-publish","format-standard","hentry","category-uncategorized","tag-cpp"],"_links":{"self":[{"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts\/859","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/comments?post=859"}],"version-history":[{"count":13,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts\/859\/revisions"}],"predecessor-version":[{"id":983,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts\/859\/revisions\/983"}],"wp:attachment":[{"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/media?parent=859"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/categories?post=859"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/tags?post=859"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}