{"id":153,"date":"2024-04-25T18:30:10","date_gmt":"2024-04-25T18:30:10","guid":{"rendered":"https:\/\/permutationcity.co.uk\/bp\/?p=153"},"modified":"2024-04-26T15:45:29","modified_gmt":"2024-04-26T15:45:29","slug":"the-power-of-10","status":"publish","type":"post","link":"https:\/\/permutationcity.co.uk\/bp\/2024\/04\/25\/the-power-of-10\/","title":{"rendered":"The Power of 10"},"content":{"rendered":"\n<p>I originally came across the\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/The_Power_of_10:_Rules_for_Developing_Safety-Critical_Code\">The Power of 10<\/a>\nby watching the video\n<a href=\"https:\/\/www.youtube.com\/watch?v=GWYhtksrmhE\">how NASA writes space-proof code<\/a>.\nThese are a set of rules to produce code that can be reviewed and statically analysed.\nAs they&#8217;ve come from the space industry you can understand why they want to be <em>really<\/em> sure what their code does.\nYou can&#8217;t send someone up to turn it off and on again.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"the-rules\">The rules<\/h2>\n\n\n\n<p>The creator of the rules, <a href=\"https:\/\/en.wikipedia.org\/wiki\/Gerard_J._Holzmann\">Gerand Holzmann<\/a>, admits:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>&#8230;the rules I will propose are somewhat strict &#8211; some might say even draconian.\nThe trade-off, though, should be clear.<\/p>\n<\/blockquote>\n\n\n\n<p>Here we go:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Avoid complex flow constructs, such as goto and recursion.<\/li>\n\n\n\n<li>All loops must have fixed bounds. This prevents runaway code.<\/li>\n\n\n\n<li>Avoid heap memory allocation.<\/li>\n\n\n\n<li>Restrict functions to a single printed page.<\/li>\n\n\n\n<li>Use a minimum of two runtime assertions per function.<\/li>\n\n\n\n<li>Restrict the scope of data to the smallest possible.<\/li>\n\n\n\n<li>Check the return value of all non-void functions, or cast to void to indicate the return value is useless.<\/li>\n\n\n\n<li>Use the preprocessor sparingly.<\/li>\n\n\n\n<li>Limit pointer use to a single dereference, and do not use function pointers.<\/li>\n\n\n\n<li>Compile with all possible warnings active; all warnings should then be addressed before release of the software.<\/li>\n<\/ol>\n\n\n\n<p>While that is strict, it&#8217;s not actually all bad.\nSome of it makes sense in everyday code whether you&#8217;re writing safety critical systems or not.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"flow-control\">Flow control<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Avoid complex flow constructs, such as goto and recursion.<\/li>\n<\/ol>\n\n\n\n<p>Back in the day people only had if-statements and goto-statements. It&#8217;s really easy to make confusing code with gotos. In my first year of university they told us never to touch them. I have used them as a stepping stone when I was reverse engineering assembly code back in to C. I&#8217;ve seen them inside automatically generated parser code and they can indeed be confusing. They are a fundamental internal component of all other flow control but there is almost always going to be a better way to do things than a direct goto-statement. I&#8217;m okay with a blanket ban.<\/p>\n\n\n\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Recursion_(computer_science)\">Recursion<\/a> would be harder to do without. It&#8217;s not something that necessarily comes up often but sometimes it&#8217;s really useful. Some problems are even described in a recursive manner so it&#8217;s a very direct replacement. On the other hand seeing a recursive function accidentally blow up the stack because of a bug isn&#8217;t uncommon. Actually, even more common would be a function that&#8217;s indirectly recursive, one where <code>foo()<\/code> calls <code>bar()<\/code> and <code>bar()<\/code> calls <code>foo()<\/code> or something more complicated. That&#8217;s not mentioned here but could lead to the same sort of problems. Maybe they&#8217;d ban it all. You can always re-write something in a non-recursive way but it&#8217;s nice to have the option of recursion.<\/p>\n\n\n\n<ol class=\"wp-block-list\" start=\"2\">\n<li>All loops must have fixed bounds. This prevents runaway code.<\/li>\n<\/ol>\n\n\n\n<p>All loops having a fixed upper bound is a bit different. Of course some loops will already have a fixed upper bound. If you&#8217;re looping through an array often the size of the array is the upper bound. However if you&#8217;re looping through a string the end condition might be finding the null terminator. If you&#8217;ve used null-terminated strings before then you&#8217;ve probably experienced a string that hasn&#8217;t been terminated. Often that&#8217;s because most of the string was copied but someone forgot to account for the <code>+ 1<\/code> needed for the null terminator. If your string processing loop <em>also<\/em> has a fixed upper bound, perhaps the maximum expected size of any string, then the loop is still going to stop. The code is broken but at least it&#8217;s not stuck in an infinite loop. One for the space industry.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"memory-allocation\">Memory allocation<\/h2>\n\n\n\n<ol class=\"wp-block-list\" start=\"3\">\n<li>Avoid heap memory allocation.<\/li>\n<\/ol>\n\n\n\n<p>Avoiding memory allocation avoids a host of potential bugs:\nno running out of memory, no dangling pointers, no heap fragmentation.\nThese rules were designed to use with C so they don&#8217;t have garbage collection to fall back on and\nthat has a different set of potential issues.\nOn the other hand without memory allocation and with a fixed stack size\nthere are definite limits on what can be done.\nSo far I&#8217;ve been in computing environment where I don&#8217;t have to worry about this but\nany constrained system might benefit restricted allocation.<\/p>\n\n\n\n<p>For different reasons games often go down a similar path. Games might allocate fixed numbers of objects early on and reuse them throughout. While these system are used for less serious purposes they are performance critical and might push the bounds of even extensive hardware.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"functions\">Functions<\/h2>\n\n\n\n<ol class=\"wp-block-list\" start=\"4\">\n<li>Restrict functions to a single printed page.<\/li>\n<\/ol>\n\n\n\n<p>I&#8217;ve talked about the benefits of seeing things\n<a href=\"https:\/\/permutationcity.co.uk\/bp\/2024\/01\/18\/in-one-glance\/\">in one glance<\/a>\nand apparently NASA agrees with me.\nWe even landed on a similar size limit for functions, 70 for me and 60 for them.\nI planned it around screen size but they were thinking about the printed page.\nA smaller function is easier to understand and test so you can be sure of it&#8217;s behaviour.<\/p>\n\n\n\n<ol class=\"wp-block-list\" start=\"5\">\n<li>Use a minimum of two runtime assertions per function.<\/li>\n<\/ol>\n\n\n\n<p>This has been simplified a bit from it&#8217;s original statement. It was originally &#8220;&#8230;average to a minimum of two assertions per function.&#8221; This could be used to check that the data is in an expected form before the function and has been correctly transformed after the function. <\/p>\n\n\n\n<p>It&#8217;s good if you can write code that can only be used properly. You can use an object reference for a function parameter rather than an object pointer to shows that only a real object should be passed in. However <a href=\"https:\/\/permutationcity.co.uk\/bp\/2024\/01\/31\/we-all-make-mistakes\/\">we all make mistakes<\/a> and asserts can catch those.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"restrict-access\">Restrict access<\/h2>\n\n\n\n<ol class=\"wp-block-list\" start=\"6\">\n<li>Restrict the scope of data to the smallest possible.<\/li>\n<\/ol>\n\n\n\n<p>I tend to restrict the scope of data.\nProtecting class variables behind <code>private<\/code>, declaring static variables inside the cpp file or within a function.\nThis might not necessarily be the smallest possible scope.\nSometimes it feels like there is too much going on in a class and it would be good to tighten it further.\nThat&#8217;s probably an indication I should have broken the class into separate parts.\nThis relates to the classes <a href=\"https:\/\/en.wikipedia.org\/wiki\/Cohesion_(computer_science)\">cohesion<\/a>\nwhich is on my list to post about.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"check-return-values\">Check return values<\/h2>\n\n\n\n<ol class=\"wp-block-list\" start=\"7\">\n<li>Check the return value of all non-void functions, or cast to void to indicate the return value is useless.<\/li>\n<\/ol>\n\n\n\n<p>This isn&#8217;t about checking the return values when you wanted the return value.\nIt&#8217;s about dealing with the return values when you didn&#8217;t want the return value.\nWhen you call <a href=\"https:\/\/en.cppreference.com\/w\/c\/io\/fprintf\"><code>printf<\/code><\/a> it returns a value.\nYou can cast this value to <code>(void)<\/code> to show readers of the code that you know about this but <em>don&#8217;t care<\/em>.\nIn modern C++ you can use <a href=\"https:\/\/en.cppreference.com\/w\/cpp\/utility\/tuple\/ignore\"><code>std::ignore<\/code><\/a> instead.<\/p>\n\n\n\n<p>I feel conflicted about this.\nPart of me likes having to explicitly show the reader that the return value is know but unwanted.\nIt feels like coding should be very deliberate.\nHowever part of me rebels at the extra code that would have to be strewn everywhere.\nHaving <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/csharp\/fundamentals\/functional\/discards\">discard variables<\/a>\nwould make it more compact.<\/p>\n\n\n\n<p>It often indicates that we&#8217;re not dealing with <a href=\"https:\/\/en.wikipedia.org\/wiki\/Pure_function\">pure functions<\/a>.\nCertainly in the <code>printf<\/code> case we assume that the function is successful.\nIt just happens to return the number of characters printed.\nIt could return void and provide a separate function if we really wanted to know the number of characters.\nThat would be less efficient but cleaner.<\/p>\n\n\n\n<p>I&#8217;m not planning to start checking all my return values but\nI will try to use the <a href=\"https:\/\/en.cppreference.com\/w\/cpp\/language\/attributes\/nodiscard\"><code>nodiscard<\/code><\/a>\nattribute to force the behaviour where it makes sense.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"limit-preprocessor\">Limit preprocessor<\/h2>\n\n\n\n<ol class=\"wp-block-list\" start=\"8\">\n<li>Use the preprocessor sparingly.<\/li>\n<\/ol>\n\n\n\n<p>Apparently NASA limits the preprocessor to file includes and simple conditional macros because:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>The C preprocessor is a powerful obfuscation tool that can destroy code clarity and\nbefuddle many text-based checkers.<\/p>\n<\/blockquote>\n\n\n\n<p>This seems very true and clever preprocessor use can be synonymous with complicated code.<\/p>\n\n\n\n<p>Another objection is around flags that are used to control the build process.\nIf you have 10 build flags then you effectively have 2^10 build targets.\nHow do you go about testing all of those?<\/p>\n\n\n\n<p>I have been caught out before by code that was behind a build flag.\nIf a build flag has disabled a section of code then the compiler doesn&#8217;t get to see it at all.\nIt won&#8217;t get checked for build errors.\nIt can be safer to keep code behind an if-statement where the if-expression is always false.\nThe code is checked at build time and the optimiser should remove it from the binary.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"simple-pointers\">Simple pointers<\/h2>\n\n\n\n<ol class=\"wp-block-list\" start=\"9\">\n<li>Limit pointer use to a single dereference, and do not use function pointers.<\/li>\n<\/ol>\n\n\n\n<p>A single dereference of a pointer isn&#8217;t too difficult a limitation.\nYou are allowed to build more complicated chains but you&#8217;ll have to mix it up with intermediate structures.<\/p>\n\n\n\n<p>Not using function pointers, and presumably things like lambdas, is a big drawback.\nThese are really powerful in reducing the amount of code that needs to be written.\nApparently they can really make it difficult for static analysis.\nI suspect a lot of my use cases aren&#8217;t <em>that<\/em> difficult.\nProviding a comparison function to a sort algorithm sounds possible to analyse.\nHowever the general case could get very complicated.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"address-warnings\">Address warnings<\/h2>\n\n\n\n<ol class=\"wp-block-list\" start=\"10\">\n<li>Compile with all possible warnings active; all warnings should then be addressed before release of the software.<\/li>\n<\/ol>\n\n\n\n<p>This can be a difficult one to get started in the middle of a project. However once it&#8217;s achieved it does feel good and is beneficial. In particular once the code is warning free any <em>new<\/em> warnings are obvious. Warnings often are useful but <a href=\"https:\/\/permutationcity.co.uk\/bp\/2024\/03\/26\/when-to-warn\/\">can get buried<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">On balance<\/h2>\n\n\n\n<p>I think about half of that makes sense for day to day programming. Given these are meant to be strict, even draconian, rules that&#8217;s surprising. The one I&#8217;m going to keep thinking about is checking return values. How to be deliberate about discard values without complicating the code.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I originally came across the The Power of 10 by watching the video how NASA writes space-proof code. These are a set of rules to produce code that can be reviewed and statically analysed. As they&#8217;ve come from the space industry you can understand why they want to be really sure what their code does. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[8,24],"class_list":["post-153","post","type-post","status-publish","format-standard","hentry","category-general","tag-standards","tag-videos"],"_links":{"self":[{"href":"https:\/\/permutationcity.co.uk\/bp\/wp-json\/wp\/v2\/posts\/153","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/permutationcity.co.uk\/bp\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/permutationcity.co.uk\/bp\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/permutationcity.co.uk\/bp\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/permutationcity.co.uk\/bp\/wp-json\/wp\/v2\/comments?post=153"}],"version-history":[{"count":3,"href":"https:\/\/permutationcity.co.uk\/bp\/wp-json\/wp\/v2\/posts\/153\/revisions"}],"predecessor-version":[{"id":192,"href":"https:\/\/permutationcity.co.uk\/bp\/wp-json\/wp\/v2\/posts\/153\/revisions\/192"}],"wp:attachment":[{"href":"https:\/\/permutationcity.co.uk\/bp\/wp-json\/wp\/v2\/media?parent=153"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/permutationcity.co.uk\/bp\/wp-json\/wp\/v2\/categories?post=153"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/permutationcity.co.uk\/bp\/wp-json\/wp\/v2\/tags?post=153"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}