Coding best practices: Difference between revisions

Content deleted Content added
mNo edit summary
CA-CMT (talk | contribs)
Link suggestions feature: 2 links added.
 
(8 intermediate revisions by 8 users not shown)
Line 2:
{{multiple issues|
{{more footnotes|date=July 2012}}
{{Tone|date=MarchApril 2008}}
}}
 
'''Coding best practices''' or '''programming best practices''' are a set of informal, sometimes personal, rules (''[[best practice]]s'') that many [[software developer]]s, in [[computer programming]] follow to improve [[software quality]].<ref name="McConnell 2004 p. ">{{cite book |last=McConnell |first=Steve |author-link=Steve McConnell |title=Code Complete |publisher=Microsoft Press |publication-place=Redmond, Wash. |year=2004 |isbn=978-0-7356-9125-4 |oclc=61315783 |page={{page needed|date=November 2023}}}}</ref> Many computer programs require being robust and reliable for long periods of time,<ref>{{cite book|title=Software Engineering|edition=Seventh|last=Sommerville|first=Ian|year=2004|publisher=Pearson|isbn=0-321-21026-3|page=38}}</ref> so any rules need to facilitate both initial development and subsequent maintenance of [[source code]] by people other than the original authors.
 
In the [[ninety–ninety rule]], Tom Cargill is credited with an explanation as toexplains why programming projects often run late: <!-- these do add to 180%, and are meant to (=late project). See linked Ninety-ninety rule --> "The first 90% of the code accounts fortakes the first 90% of the development time. The remaininglast 10% oftakes the code accounts for the otheranother 90% of the development time."<ref name="Bentley1985">{{cite journal|last=Bentley|first=Jon|year=1985|title=Programming pearls: Bumper-Sticker Computer Science|journal=Communications of the ACM|volume=28|issue=9|pages=896–901|issn=0001-0782|doi=10.1145/4284.315122|s2cid=5832776|doi-access=free}}</ref> Any guidance which can redress this lack of foresight is worth considering.
 
The size of a project or program has a significant effect on error rates, [[programmer productivity]], and the amount of management needed.<ref>{{cite book|title=Code Complete|url=https://archive.org/details/codecomplete0000mcco|url-access=registration|edition=Second|last=McConnell|first=Steve|year=2004|publisher=Microsoft Press|isbn=0-7356-1967-0|pages=[https://archive.org/details/codecomplete0000mcco/page/649 649–659]}}</ref>
Line 68:
===Architecture===
{{Main|Software architecture}}
Hoare points out: "there are two ways of constructing a software design: one way is to make it so simple that there are ''obviously'' no deficiencies; the other way is to make it so complicated that there are no ''obvious'' deficiencies. The first method is far more difficult."<ref>{{cite journal|last=Hoare|first=C.A.R|title=The Emperor's Old Clothes|journal=Communications of the ACM|volume=24|issue=2|pages=75–83|publisher=ACM|date=1981|doi=10.1145/358549.358561|s2cid=97895|url=https://zoo.cs.yale.edu/classes/cs422/2011/bib/hoare81emperor.pdf|accessdate=25 Nov 2019|doi-access=free}}</ref> (Emphasis as in the original.)
 
Software architecture is concerned with deciding what has to be done and which program component is going to do it (how something is done is left to the detailed design phase below). This is particularly important when a software system contains more than one program since it effectively defines the interface between these various programs. It should include some consideration of any user interfaces as well, without going into excessive detail.
Line 78:
===Design===
{{Main|Software design}}
The primary purpose of design is to fill in the details which have been glossed over in the architectural design. The intention is that the design should be detailed enough to provide a good guide for actual coding, including details of any particular algorithms to be used. For example, at the architectural level, it may have been noted that some data has to be sorted, while at the design level, it is necessary to decide which [[sorting algorithm]] is to be used. As a further example, if an object-oriented approach is being used, then the details of the objects must be determined (attributes and methods).
 
===Choice of programming language(s)===
Line 100:
 
===Commenting===
Due to time restrictions or enthusiastic programmers who want immediate results for their code, commenting of code often takes a back seat. Programmers working as a team have found it better to leave comments behind since coding usually follows cycles, or more than one person may work on a particular module. However, some commenting can decrease the cost of [[knowledge transfer]] between developers working on the same module.
 
In the early days of computing, one commenting practice was to leave a brief description of the following:
Line 127:
 
===Keep the code simple===
The code that a programmer writes should be simple. Complicated logic for achieving a simple thing should be kept to a minimum since the code might be modified by another programmer in the future. The logic one programmer implemented may not make perfect sense to another. So, always keep the code as simple as possible.<ref>{{cite web |author=Multiple (wiki) |title=Best practices |url=http://docforge.com/wiki/Best_practices |accessdate=2012-11-13 |work=Docforge}}</ref> Sometimes, a developer or project manager will decide to employ more complex code for performance.
 
'''For example,''' consider these equivalent lines of C code:{{efn|Since true and false are not defined in regular C code, assume that the "stdbool.h" library has been included.}}
 
<syntaxhighlight lang="c">
if (hours < 24 && minutes < 60 && seconds < 60)
{
return true;
}
else
{
return false;
}
</syntaxhighlight>
 
and
 
<syntaxhighlight lang="c">
if (hours < 24 && minutes < 60 && seconds < 60)
return true;
else
return false;
</syntaxhighlight>
 
and
 
<syntaxhighlight lang="c">
switch (hours < 24 && minutes < 60 && seconds < 60){
case true:
return true;
break;
case false:
return false;
break;
default:
return false;
}
</syntaxhighlight>
 
and<syntaxhighlight lang="c">
return hours < 24 && minutes < 60 && seconds < 60 ? true : false;
</syntaxhighlight>and
 
<syntaxhighlight lang="c">
return hours < 24 && minutes < 60 && seconds < 60;
</syntaxhighlight>
 
The first approach, which is much more commonly used{{dubious|date=December 2017}}, is considerably larger than the fifth. In particular, it consumes 5 times more screen vertical space (lines), and 97 characters versus 52 (though editing tools may reduce the difference in actual typing). It is arguable, however, which is "simpler". The first has an explicit if/then else, with an explicit return value obviously connected with each; even a novice programmer should have no difficulty understanding it. The second merely discards the braces, cutting the "vertical" size in half with little change in conceptual complexity. In most languages, the "return" statements could also be appended to the prior lines, bringing the "vertical" size to only one more line than the fourth form.
 
The third takes advantage of the C ''switch'' keyword, this is sometimes done for performance, but in some cases, such as this, it makes the code more complex with little to no increase in performance.
 
The fourth and fifth forms obviously minimize the size, but they may increase the complexity: The fourth block requires knowledge of more advanced programming topics, notably [[Ternary operation|ternary operators]], while the fifth block leaves the "true" and "false" values implicit, and intermixes the notions of "condition" and "return value". It is likely obvious to most programmers, but a novice might not immediately understand that the result of evaluating a condition is actually a value (of type Boolean or its equivalent in whatever language), and thus can be manipulated or returned. In more realistic examples, the fifth form could have problems due to [[operator precedence]], perhaps returning an unexpected type, where the prior forms would, in some languages, report an error. Thus, "simplicity" is not merely a matter of length, but of logical and conceptual structure; making code shorter may make it less or more complex, but in some cases may be at the cost of performance.
 
For large, long lived programs using verbose alternatives could contribute to [[Software bloat|bloat]].{{dubious|date=December 2017}}
 
Compactness can allow coders to view more code per page, reducing scrolling gestures and keystrokes. Given how many times code might be viewed in the process of writing and maintaining, it might amount to a significant savings in programmer keystrokes in the life of the code. This might not seem significant to a student first learning to program but, when producing and maintaining large programs the reduction of how many lines of code there are allows for more of the code to fit on screen, minor code simplification may improve productivity{{dubious|date=December 2017}}, and also lessen finger, wrist and eye strain, which are common medical issues suffered by production coders and information workers.<ref>{{cite web|title=Repetitive Strain Injury|url=http://web.eecs.umich.edu/~cscott/rsi.html|accessdate=30 October 2016}}</ref>
 
Terser coding speeds compilation very slightly, as fewer symbols need to be processed. Furthermore, the third approach may allow similar lines of code to be more easily compared, particularly when many such constructs can appear on one screen at the same time.
 
Finally, very terse layouts may better utilize modern wide-screen computer displays, depending on monitor layout and setup. In the past, screens were limited to 40 or 80 characters (such limits originated far earlier: manuscripts, printed books, and even scrolls, have for millennia used quite short lines (see for example [[Gutenberg Bible]]). Modern screens can easily display 200 or more characters, allowing extremely long lines. Most modern coding styles and standards do not take up that entire width. Thus, if using one window as wide as the screen, a great deal of available space is wasted. On the other hand, with multiple windows, or using an IDE or other tool with various information in side panes, the available width for code is in the range familiar from earlier systems.
 
It is also worth noting that the human visual system is greatly affected by line length; very long lines slightly increase reading speed, but reduce comprehension [https://blog.codinghorror.com/text-columns-how-long-is-too-long/ Text Columns: How Long is Too Long?] and add to eye-tracking errors. Some studies suggest that longer lines fare better online than in print [http://www.humanfactors.com/newsletters/optimal_line_length.asp Human Factors International], but this still only goes up to about 10 inches, and mainly for raw speed of reading prose.
 
===Portability===
Line 237 ⟶ 176:
# Customize deployment: Newer software products such as APIs, micro-services, etc. require specific considerations for successful deployment.<ref>{{Cite web|url=https://airbrake.io/blog/software-development/speed-up-deployment-match-demand|title=Tools You Need to Speed Up Deployment to Match Demand|date=February 3, 2017}}</ref><ref>{{Cite web|url=https://www.linux.com/news/devops-and-art-secure-application-deployment/|title=DevOps and the Art of Secure Application Deployment|first=Amber|last=Ankerholz|date=September 14, 2016}}</ref><ref>{{Cite web|url=https://aws.amazon.com/blogs/architecture/organizing-software-deployments-to-match-failure-conditions/|title=Organizing Software Deployments to Match Failure Conditions|date=May 5, 2014|website=Amazon Web Services}}</ref>
# Reduce risk from other development phases: If other activities such as testing and configuration management are wrong, deployment surely will fail.<ref>{{Cite web|url=https://www.theserverside.com/news/1364556/Best-Practices-for-Risk-Free-Deployment|title=Best Practices for Risk-Free Deployment|website=TheServerSide.com}}</ref><ref>{{Cite web|url=http://www.drdobbs.com/effective-software-deployment/184415760|title=Effective Software Deployment|first=Scott|last=Ambler|website=Dr. Dobb's}}</ref>
# Consider the influence each stakeholder has: Organizational, social, governmental considerations.<ref>{{cite web|url=http://searchitoperations.techtarget.com/tip/Enterprise-application-deployment-The-humanity-of-software-implementation|url-status=dead|archive-url=https://web.archive.org/web/20160821101511/http://searchitoperations.techtarget.com/tip/Enterprise-application-deployment-The-humanity-of-software-implementation|archive-date=2016-08-21|title=Enterprise application deployment: The humanity of software implementation}}</ref><ref>{{Cite web|url=https://18f.gsa.gov/2014/05/14/hacking-bureaucracy-improving-hiring-and-software/|archive-url=https://web.archive.org/web/20150118055134/https://18f.gsa.gov/2014/05/14/hacking-bureaucracy-improving-hiring-and-software/|url-status=dead|archive-date=January 18, 2015|title=Hacking bureaucracy: improving hiring and software deployment &#124; 18F: Digital service delivery|website=18f.gsa.gov|date=14 May 2014}}</ref><ref>{{Cite web|url=https://intact-tech.com/why-a-bad-software-deployment-is-worse-than-doing-nothing/|title=A Bad Software Deployment Is Worse Than Doing Nothing|date=June 1, 2016|website=Intact Technology |last1=Horning |first1=Brian }}</ref>
 
==See also==