{"id":24,"date":"2016-11-24T14:06:27","date_gmt":"2016-11-24T14:06:27","guid":{"rendered":"http:\/\/cppdepend.com\/wordpress\/?p=24"},"modified":"2016-11-24T14:22:16","modified_gmt":"2016-11-24T14:22:16","slug":"learn-basic-c-coding-rules-from-open-source-projects","status":"publish","type":"post","link":"https:\/\/cppdepend.com\/blog\/learn-basic-c-coding-rules-from-open-source-projects\/","title":{"rendered":"Learn basic &#8220;C&#8221; coding rules from open source projects"},"content":{"rendered":"<p><span style=\"color: #000000;\">Every project has its own style guide: a set of conventions about how to write code for that\u00a0project.\u00a0<\/span>Some managers choose a basic coding rules, others prefer very advanced ones and for many projects there is no coding rules, and each developer uses his own style.<\/p>\n<p>It is much easier to understand a large codebase when all the source code is in a consistent style.<img decoding=\"async\" class=\"mceWPmore mceItemNoResize\" title=\"More...\" src=\"http:\/\/javadepend.com\/Blog\/wp-includes\/js\/tinymce\/plugins\/wordpress\/img\/trans.gif\" alt=\"\" \/><\/p>\n<p>Many resources exist talking about the better coding rules to adopt, we can learn good coding rules from:<\/p>\n<ul style=\"color: #555555;\">\n<li>Reading a book or a magazine.<\/li>\n<li>Web sites.<\/li>\n<li>From a collegue.<\/li>\n<li>Doing a training.<\/li>\n<\/ul>\n<p>Another more interesting approach is to study a known and\u00a0mature\u00a0open source project to discover how developers implement their source code. In\u00a0the &#8220;C&#8221; World, the <a href=\"https:\/\/github.com\/torvalds\/linux\">Linux kernel<\/a>\u00a0could be\u00a0a good candidate.<\/p>\n<p>For the beginner or even the intermediate C developers, the Linux kernel is maybe not easy to go inside, however the goal is not necessarily to contribute to its source code but to explore how it&#8217;s implemented.<\/p>\n<p>Let&#8217; take as example a function implementation from the Linux source code<\/p>\n<p><a href=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux11.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-176\" src=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux11.png\" alt=\"linux11\" width=\"550\" height=\"344\" \/><\/a><\/p>\n<p>The code looks very clean, indeed the function<\/p>\n<ul>\n<li>Has\u00a0only few lines of code.<\/li>\n<li>The signature is well defined.<\/li>\n<li>It&#8217;s well commented.<\/li>\n<li>It&#8217;s well indented.<\/li>\n<li>The variable names are very clear.<\/li>\n<\/ul>\n<p>The same \u00a0function could be implemented by another developer like this<\/p>\n<p><a href=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux12.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-177\" src=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux12.png\" alt=\"linux12\" width=\"711\" height=\"273\" \/><\/a><\/p>\n<p>The coding style has a big impact in the source code readability, investing some hours to train developers, and doing periodically a code review is always good to make the code easy to maintain and evolve.<\/p>\n<p>Let&#8217;s go inside the linux kernel source code using <a href=\"http:\/\/www.cppdepend.com\">CppDepend <\/a>and discover some basic coding rules adopted by their developers.<\/p>\n<p><strong>Modularity<\/strong><\/p>\n<p style=\"color: #555555;\">Modularity is a software design technique that increases the extent to which software is composed from separate parts , you can manage and maintain modular code easily.<\/p>\n<p style=\"color: #555555;\">For procedural language like C where no logical artifacts like namespace, component or class does not exist, we can modularize by using directories and files.<\/p>\n<p style=\"color: #555555;\">Here are some possible scenarios :<\/p>\n<ul>\n<li>Put all the souce files in one directory<\/li>\n<li>Isolate files related to a module or a sub module \u00a0into a specific directory.<\/li>\n<\/ul>\n<p>In case of the Linux kernel, directories and sub directories are used to modularize the kernel source code.<\/p>\n<p><a href=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux15.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-191\" src=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux15.png\" alt=\"linux15\" width=\"348\" height=\"322\" \/><\/a><\/p>\n<p><strong>Encapsulation<\/strong><\/p>\n<p style=\"color: #555555;\">Encapsulation \u00a0is the hiding of functions and data which are internal to an implementation. \u00a0In C, encapsulation is performed by using the key word static . These entities are called file-scope functions and variables.<\/p>\n<p style=\"color: #555555;\">Let&#8217;s search for all static functions by executing the following CQLinq query<\/p>\n<p style=\"color: #555555; text-align: left;\"><a href=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux17.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-192\" src=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux17.png\" alt=\"linux17\" width=\"383\" height=\"38\" \/><\/a><\/p>\n<p>We can use the Metric view to\u00a0have a good idea how many functions are concerned. In the Metric View, the code base is represented through a Treemap. Treemapping is a method for displaying tree-structured data by using nested rectangles. The tree structure used in a CppDepend treemap is the usual code hierarchy:<\/p>\n<ul>\n<li>Projects contains directories.<\/li>\n<li>Directories\u00a0contains files.<\/li>\n<li>Files\u00a0contains struects, functions\u00a0and variables.<\/li>\n<\/ul>\n<p>The treemap view provides a useful way to represent the result of a CQLinq request, so we can visually see the types concerned by the request.<\/p>\n<p style=\"color: #555555;\"><a href=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-170\" src=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux2.png\" alt=\"linux2\" width=\"771\" height=\"383\" \/><\/a><\/p>\n<p style=\"color: #555555;\">As we can observe many functions are declared as static.<\/p>\n<p style=\"color: #555555;\">Let&#8217;s search now for the static fields:<\/p>\n<p style=\"color: #555555;\"><a href=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-179\" src=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux3.png\" alt=\"linux3\" width=\"370\" height=\"473\" \/><\/a><\/p>\n<p style=\"color: #555555;\">The same remark as functions, many variables are declared as static.<\/p>\n<p style=\"color: #555555;\">In the Linux kernel source code the encapsulation is used whenever the functions and variables must be private to the file scope.<\/p>\n<p style=\"color: #555555;\"><strong>Use structs to store your data model<\/strong><\/p>\n<p style=\"color: #555555;\">In C programing the functions uses variables to acheive their treatments, theses variables could be:<\/p>\n<ul>\n<li>Static variables.<\/li>\n<li>Global variables.<\/li>\n<li>Local variables<\/li>\n<li>Variables from structs.<\/li>\n<\/ul>\n<p>Each project has it&#8217;s data model which could be used by many source files, using global variables is a solution but not the good one, using structs to group data is more recommended.<\/p>\n<p>Let&#8217;s search for global variables with a primitive type:<\/p>\n<p style=\"color: #555555;\"><a href=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux4.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-180\" src=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux4.png\" alt=\"linux4\" width=\"357\" height=\"469\" \/><\/a><\/p>\n<p style=\"color: #555555;\">only very few variables are concerned, and maybe we can group some of them into structs, like (elfcorehdr_addr and\u00a0elfcorehdr_size) or (pm_freezing and pm_nosig_freezing).<\/p>\n<p style=\"color: #555555;\"><strong>Let function be short and sweet<\/strong><\/p>\n<p style=\"color: #555555;\">Here&#8217;s from the <a href=\"https:\/\/www.kernel.org\/doc\/Documentation\/CodingStyle\">linux coding style web page<\/a>, an\u00a0advice about the length of functions:<\/p>\n<pre style=\"color: #000000;\">Functions should be short and sweet, and do just one thing.  They should\r\nfit on one or two screenfuls of text (the ISO\/ANSI screen size is 80x24,\r\nas we all know), and do one thing and do that well.\r\n\r\nThe maximum length of a function is inversely proportional to the\r\ncomplexity and indentation level of that function.  So, if you have a\r\nconceptually simple function that is just one long (but simple)\r\ncase-statement, where you have to do lots of small things for a lot of\r\ndifferent cases, it's OK to have a longer function.<\/pre>\n<p style=\"color: #555555;\">\u00a0Let&#8217;s search for functions where the number of lines of code is more than 30<\/p>\n<p style=\"color: #555555;\"><a href=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux14.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-188\" src=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux14.png\" alt=\"linux14\" width=\"383\" height=\"466\" \/><\/a><\/p>\n<p style=\"color: #555555;\">Only few methods has more than 30 lines of code.<\/p>\n<p style=\"color: #555555;\"><strong>Function Number of parameters<\/strong><\/p>\n<p style=\"color: #555555;\">Functions\u00a0where NbParameters &gt; 8\u00a0might be painful to call \u00a0and might degrade performance. Another alternative is to provide \u00a0a structure dedicated to handle arguments passing.<\/p>\n<p style=\"color: #555555;\"><a href=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux7.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-182\" src=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux7.png\" alt=\"linux7\" width=\"356\" height=\"352\" \/><\/a><\/p>\n<p style=\"color: #555555;\">only 2 methods has more than 8 parameters.<\/p>\n<p style=\"color: #555555;\"><strong>Number of\u00a0local variables<\/strong><\/p>\n<p style=\"color: #555555;\"><span style=\"color: #333333;\">Methods where NbVariables is higher than 8 are hard to understand and maintain. Methods where NbVariables is higher than 15 are extremely complex and should be split in smaller methods (except if they are automatically generated by a tool).<\/span><\/p>\n<p style=\"color: #555555;\"><a href=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux9.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-183\" src=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux9.png\" alt=\"linux9\" width=\"352\" height=\"413\" \/><\/a><\/p>\n<p style=\"color: #555555;\">only 5 functions has more than 15 local variables.<\/p>\n<p><strong>Avoid defining complex functions<\/strong><\/p>\n<p>Many metrics exist to detect complex functions, NBLinesOfCode,Number of parameters and number of local variables are the basic ones.<\/p>\n<p>There are other interesting metrics to detect complex functions:<\/p>\n<ul>\n<li>Cyclomatic complexity is a popular procedural software metric equal to the number of decisions that can be taken in a procedure.<\/li>\n<li>Nesting Depth\u00a0is a metric defined on methods that is relative to the maximum depth\u00a0of the more nested scope in a method body.<\/li>\n<li>Max Nested loop is\u00a0equals the maximum level of loop nesting in a function.<\/li>\n<\/ul>\n<p>The max value tolerated for these metrics depends more on the team choices, there&#8217;s no standard values.<\/p>\n<p>Let&#8217;s search for functions candidate to be refactored:<\/p>\n<p><a href=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux8.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-184\" src=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux8.png\" alt=\"linux8\" width=\"350\" height=\"468\" \/><\/a><\/p>\n<p>only very few functions could be considered as complex.<\/p>\n<p><strong>Naming convention<\/strong><\/p>\n<p>There&#8217;s no standard for the naming convention, each project managers could choose what they think it&#8217;s better, however what&#8217;s very important is to respect the chosen convention to have an homegenous naming.<\/p>\n<p>For example in case of Linux, the structs must began with a lower case, and we can check if it&#8217;s true for the whole kernel source code, let&#8217;s execute the following query:<\/p>\n<p><a href=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux5.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-185\" src=\"http:\/\/www.codergears.com\/Blog\/wp-content\/uploads\/linux5.png\" alt=\"linux5\" width=\"355\" height=\"397\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p>Only 4 structs began with &#8220;_&#8221; instead of a lower case letter.<\/p>\n<p><strong>\u00a0Indentation<\/strong><\/p>\n<p>The indentation is very useful to make the code easy to read,\u00a0h<span style=\"color: #555555;\">ere&#8217;s from the\u00a0<\/span><a href=\"https:\/\/www.kernel.org\/doc\/Documentation\/CodingStyle\">linux coding style web page<\/a>\u00a0 the motivations behind the indentation:<\/p>\n<pre style=\"color: #000000;\">Rationale: The whole idea behind indentation is to clearly define where\r\na block of control starts and ends.  Especially when you've been looking\r\nat your screen for 20 straight hours, you'll find it a lot easier to see\r\nhow the indentation works if you have large indentations.\r\n\r\nNow, some people will claim that having 8-character indentations makes\r\nthe code move too far to the right, and makes it hard to read on a\r\n80-character terminal screen.  The answer to that is that if you need\r\nmore than 3 levels of indentation, you're screwed anyway, and should fix\r\nyour program.<\/pre>\n<p><strong>\u00a0Conclusion<\/strong><\/p>\n<p>Exploring some known open source projects is always good to elevate your programming skills, no need to download and build the project, you can just discover the code from GitHub for example.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Every project has its own style guide: a set of conventions about how to write code for that\u00a0project.\u00a0Some managers choose a basic coding rules, others prefer very advanced ones and for many projects there is no coding rules, and each developer uses his own style. It is much easier to understand a large codebase when &hellip; <a href=\"https:\/\/cppdepend.com\/blog\/learn-basic-c-coding-rules-from-open-source-projects\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Learn basic &#8220;C&#8221; coding rules from open source projects&#8221;<\/span><\/a><\/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":[7,17,18,19],"class_list":["post-24","post","type-post","status-publish","format-standard","hentry","category-uncategorized","tag-c","tag-coding-rules","tag-cppdepend","tag-open-source"],"_links":{"self":[{"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts\/24","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=24"}],"version-history":[{"count":1,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts\/24\/revisions"}],"predecessor-version":[{"id":25,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts\/24\/revisions\/25"}],"wp:attachment":[{"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/media?parent=24"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/categories?post=24"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/tags?post=24"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}