{"id":711,"date":"2018-04-03T14:11:34","date_gmt":"2018-04-03T14:11:34","guid":{"rendered":"http:\/\/cppdepend.com\/blog\/?p=711"},"modified":"2023-05-31T15:34:32","modified_gmt":"2023-05-31T15:34:32","slug":"perfecting-code-start-with-good-story","status":"publish","type":"post","link":"https:\/\/cppdepend.com\/blog\/perfecting-code-start-with-good-story\/","title":{"rendered":"Perfecting Code: Start with a Good Story"},"content":{"rendered":"<p>As software developers, we can write a lot of code each day. Each piece of code has its story, the code could be:<\/p>\n<ul>\n<li>Inspired by a web resource ( forum, tutorial, blog\u00a0post,&#8230;)<\/li>\n<li>Inspired by an open source project from Github, Sourceforge\u00a0or other.<\/li>\n<li>Copy\/Pasted from the project itself.<\/li>\n<li>developed\u00a0from scratch.<\/li>\n<\/ul>\n<p><!--more--><\/p>\n<p>And for each piece of code, the developer\u00a0does an analysis of the current problem to\u00a0resolve, its background and the opinions of his team could influence a lot its choices, and the way how the code is developed.<\/p>\n<p>After writing a code and committing it.\u00a0 be sure that it will introduce a debt that\u00a0the project maintainer and developers have to pay sooner or later.\u00a0 To minimize the debt and make the task easy for all the project developers, it&#8217;s better to acquire\u00a0some basic good habits to make the code clean from the beginning.<\/p>\n<p><strong>1 Naming<\/strong><\/p>\n<p>Sometimes we spent a lot of times just to understand the utility of a variable or a function because it&#8217;s named a,b or x. And if from the beginning it was named with a clear and significant name, its meaning will become obvious.<\/p>\n<p>Good a significant naming that follows a naming convention help:<\/p>\n<ul>\n<li>To reduce the effort needed to read and understand source code;<\/li>\n<li>To enable code reviews to focus on more important issues than arguing over syntax and naming standards.<\/li>\n<li>To enable code quality review tools to focus their reporting mainly on significant issues other than syntax and style preferences.<\/li>\n<\/ul>\n<p><strong>2 Visibility<\/strong><\/p>\n<p>Narrowing visibility is a good practice because doing so promotes encapsulation. Reduce the scope to a minimum, will help the user of your code. Indeed he will know which code could be used from outside a class.<\/p>\n<p>Making all the class methods public will confuse the user, and it will hide the class contract. And in this case, we need a documentation to know which methods could be used.<\/p>\n<p><strong>3 Parameters<\/strong><\/p>\n<p>A function that takes more than five parameters indicates one of two problems:<\/p>\n<ol>\n<li>The function is doing too much. It should be split into several smaller functions, each which have a smaller parameter set.<\/li>\n<li>There is another object hiding in there. You may need to create another object or data structure that includes these parameters.<\/li>\n<\/ol>\n<p>There are some good gains to be had by doing this:<\/p>\n<ul>\n<li>It makes your code easier to read.<\/li>\n<li>It&#8217;s more unit testable.<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p><a href=\"http:\/\/www.javadepend.com\/Blog\/wp-content\/uploads\/sqlite6.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-1935\" src=\"http:\/\/www.javadepend.com\/Blog\/wp-content\/uploads\/sqlite6.png\" alt=\"sqlite6\" width=\"404\" height=\"519\" \/><\/a><\/p>\n<p><strong>4 Size<\/strong><\/p>\n<p>Methods too big are not easy to maintain and understand.\u00a0 Here\u2019s some advice about the length of functions from the\u00a0<a href=\"https:\/\/www.kernel.org\/doc\/Documentation\/CodingStyle\">linux coding style web page<\/a>:<\/p>\n<pre>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>&nbsp;<\/p>\n<p><img decoding=\"async\" src=\"http:\/\/www.javadepend.com\/Blog\/wp-content\/uploads\/unreal44.png\" alt=\"unreal44\" \/><\/p>\n<p><strong>5 Number of\u00a0local variables<\/strong><\/p>\n<p>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 into smaller methods (unless\u00a0they are automatically generated by a tool).<\/p>\n<p><a href=\"http:\/\/www.javadepend.com\/Blog\/wp-content\/uploads\/sqlite7.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-1936\" src=\"http:\/\/www.javadepend.com\/Blog\/wp-content\/uploads\/sqlite7.png\" alt=\"sqlite7\" width=\"402\" height=\"546\" \/><\/a><\/p>\n<p><strong>6 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 where the result is 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\u00a0equal to 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, as there are no standard values.<\/p>\n<p>Let\u2019s search for possible functions to be refactored:<\/p>\n<p><a href=\"http:\/\/www.javadepend.com\/Blog\/wp-content\/uploads\/sqlite8.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-1937\" src=\"http:\/\/www.javadepend.com\/Blog\/wp-content\/uploads\/sqlite8.png\" alt=\"sqlite8\" width=\"435\" height=\"512\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p><strong>7 Formatting<\/strong><\/p>\n<p>Programming style and indentation can be defined as the way you follow to organize and document your source code. Code indentation is a part of style and it is more of aesthetic interest. If we follow a\u00a0proper style guide and indentation then a program can be just like a POEM. And the reader will be comfortable enough to SAIL through it and understand the meaning. As we know a proper code indentation will make it:<\/p>\n<ul>\n<li>Easier to read<\/li>\n<li>Easier to understand<\/li>\n<li>Easier to modify<\/li>\n<li>Easier to maintain<\/li>\n<li>Easier to enhance<\/li>\n<\/ul>\n<p>The purpose of code indentation and style is to make the program more readable and understandable. It saves lots of time while we revisit the code and use it. A style guide provides a road map which the developer should follow and implement in coding. So in a group of developers, all the code generated will be of consistent in nature and reusable by any coder\/developer.<\/p>\n<p><strong>8 Comments<\/strong><\/p>\n<p>Sometimes the code is not all commented and for other cases, it&#8217;s over-commented. Maybe you have already read this phrase: <em><strong>Good code is self-documenting.<\/strong><\/em><\/p>\n<p>Yes, it&#8217;s a good practice to let the code\u00a0clean to talk for himself and avoid the comments. but in the real world, it&#8217;s the not an easy task. In\u00a0some\u00a0cases, you need to clarify what the code does.<\/p>\n<p><strong>9\u00a0 Coupling<\/strong><\/p>\n<p>Low coupling is desirable because a change in one area of an application will require fewer changes throughout the entire application. In the long run, this could alleviate a lot of time, effort, and cost associated with modifying and adding new features to an application.<\/p>\n<p>Functions using many other functions\u00a0are very difficult to understand and maintain. It\u2019s recommended to minimize the efferent coupling of your functions.<\/p>\n<p>&nbsp;<\/p>\n<p><a href=\"http:\/\/www.javadepend.com\/Blog\/wp-content\/uploads\/sqlite10.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-1942\" src=\"http:\/\/www.javadepend.com\/Blog\/wp-content\/uploads\/sqlite10.png\" alt=\"sqlite10\" width=\"438\" height=\"521\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p><strong>Cohesion<\/strong><\/p>\n<p>The single responsibility principle states that a class should not have more than one reason to change. Such a class is said to be cohesive. A high LCOM value generally pinpoints a poorly cohesive class. There are several LCOM metrics. The LCOM takes its values in the range [0-1]. The LCOM HS (HS stands for Henderson-Sellers) takes its values in the range [0-2]. A LCOM HS value highest than 1 should be considered alarming. Here are \u00a0to compute LCOM metrics:<\/p>\n<blockquote><p>LCOM = 1 \u2013 (sum(MF)\/M*F)<br \/>\nLCOM HS = (M \u2013 sum(MF)\/F)(M-1)<\/p><\/blockquote>\n<p>Where:<\/p>\n<ul>\n<li>M is the number of methods in class (both static and instance methods are counted, it includes also constructors, properties getters\/setters, events add\/remove methods).<\/li>\n<li>F is the number of instance fields in the class.<\/li>\n<li>MF is the number of methods of the class accessing a particular instance field.<\/li>\n<li>Sum(MF) is the sum of MF over all instance fields of the class.<\/li>\n<\/ul>\n<p>The underlying idea behind these formulas can be stated as follow: a class is utterly cohesive if all its methods use all its\u00a0methods use all its instance fields, which means that sum(MF)=M*F and then LCOM = 0 and LCOMHS = 0.<\/p>\n<p>LCOMHS value higher than 1 should be considered alarming.<\/p>\n<p><a href=\"http:\/\/www.javadepend.com\/Blog\/wp-content\/uploads\/unreal36.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-1030\" src=\"http:\/\/www.javadepend.com\/Blog\/wp-content\/uploads\/unreal36.png\" alt=\"unreal36\" width=\"619\" height=\"496\" \/><\/a><\/p>\n<p><strong>Conclusion:<\/strong><\/p>\n<p>There are some basic habits that could make your code clean from the beginning, don&#8217;t wait for the refactoring to make your code clean. try to do it from the beginning.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>As software developers, we can write a lot of code each day. Each piece of code has its story, the code could be: Inspired by a web resource ( forum, tutorial, blog\u00a0post,&#8230;) Inspired by an open source project from Github, Sourceforge\u00a0or other. Copy\/Pasted from the project itself. developed\u00a0from scratch.<\/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":[],"class_list":["post-711","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts\/711","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=711"}],"version-history":[{"count":24,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts\/711\/revisions"}],"predecessor-version":[{"id":1469,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts\/711\/revisions\/1469"}],"wp:attachment":[{"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/media?parent=711"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/categories?post=711"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/tags?post=711"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}