Best coding practices
   HOME

TheInfoList



OR:

Coding best practices or programming best practices are a set of informal rules (''
best practice A best practice is a method or technique that has been generally accepted as superior to other known alternatives because it often produces results that are superior to those achieved by other means or because it has become a standard way of doing ...
s'') that many software developers in
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
follow to improve software quality. Many computer programs remain in use for long periods of time, so any rules need to facilitate both initial development and subsequent maintenance and enhancement of
source code In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the w ...
by people other than the original authors. In the ninety-ninety rule, Tom Cargill is credited with an explanation as to why programming projects often run late: "The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time." 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.


Software quality

As listed below, there are many attributes associated with good software. Some of these can be mutually contradictory (e.g. being very fast versus performing extensive error checking), and different customers and participants may have different priorities. Weinberg provides an example of how different goals can have a dramatic effect on both effort required and efficiency. Furthermore, he notes that programmers will generally aim to achieve any explicit goals which may be set, probably at the expense of any other quality attributes. Sommerville has identified four generalized attributes which are not concerned with what a program does, but how well the program does it: *
Maintainability In engineering, maintainability is the ease with which a product can be maintained to: * correct defects or their cause, * Repair or replace faulty or worn-out components without having to replace still working parts, * prevent unexpected working ...
*
Dependability In systems engineering, dependability is a measure of a system's availability, reliability, maintainability, and in some cases, other characteristics such as durability, safety and security. In real-time computing, dependability is the ability to ...
* Efficiency * Usability Weinberg has identified four targets which a good program should meet: * Does a program meet its
specification A specification often refers to a set of documented requirements to be satisfied by a material, design, product, or service. A specification is often a type of technical standard. There are different types of technical or engineering specificati ...
("correct output for each possible input")? * Is the program produced on schedule (and within budget)? * How adaptable is the program to cope with changing requirements? * Is the program efficient enough for the environment in which it is used? Hoare has identified seventeen objectives related to software quality, including: * Clear definition of purpose. *
Simplicity Simplicity is the state or quality of being simple. Something easy to understand or explain seems simple, in contrast to something complicated. Alternatively, as Herbert A. Simon suggests, something is simple or complex depending on the way we ...
of use. * Ruggedness (difficult to misuse, kind to errors). * Early availability (delivered on time when needed). * Reliability. * Extensibility in the light of experience. * Brevity. * Efficiency (fast enough for the purpose to which it is put). * Minimum cost to develop. * Conformity to any relevant standards. * Clear, accurate and precise user documents.


Prerequisites

Before coding starts, it is important to ensure that all necessary prerequisites have been completed (or have at least progressed far enough to provide a solid foundation for coding). If the various prerequisites are not satisfied, then the software is likely to be unsatisfactory, even if it is completed. From Meek & Heath: "What happens before one gets to the coding stage is often of crucial importance to the success of the project." The prerequisites outlined below cover such matters as: * how is development structured? (life cycle) * what is the software meant to do? (requirements) * the overall structure of the software system (architecture) * more detailed design of individual components (design) * choice of programming language(s) For small simple projects involving only one person, it may be feasible to combine architecture with design and adopt a very simple life cycle.


Life cycle

A software development methodology is a framework that is used to structure, plan, and control the life cycle of a software product. Common methodologies include
waterfall A waterfall is a point in a river or stream where water flows over a vertical drop or a series of steep drops. Waterfalls also occur where meltwater drops over the edge of a tabular iceberg or ice shelf. Waterfalls can be formed in severa ...
,
prototyping A prototype is an early sample, model, or release of a product built to test a concept or process. It is a term used in a variety of contexts, including semantics, design, electronics, and software programming. A prototype is generally used to ...
,
iterative and incremental development Iterative and incremental development is any combination of both iterative design or iterative method and incremental build model for development. Usage of the term began in software development, with a long-standing combination of the two terms ...
, spiral development, agile software development,
rapid application development Rapid application development (RAD), also called rapid application building (RAB), is both a general term for adaptive software development approaches, and the name for James Martin's method of rapid development. In general, RAD approaches to ...
, and
extreme programming Extreme programming (XP) is a software development methodology intended to improve software quality and responsiveness to changing customer requirements. As a type of agile software development,"Human Centred Technology Workshop 2006 ", 2006, P ...
. The waterfall model is a sequential development approach; in particular, it assumes that the requirements can be completely defined at the start of a project. However, McConnell quotes three studies that indicate that, on average, requirements change by around 25% during a project. The other methodologies mentioned above all attempt to reduce the impact of such requirement changes, often by some form of step-wise, incremental, or iterative approach. Different methodologies may be appropriate for different development environments.


Requirements

McConnell states: "The first prerequisite you need to fulfill before beginning construction is a clear statement of the problem the system is supposed to solve." Meek and Heath emphasise that a clear, complete, precise, and unambiguous written specification is the target to aim for. Note that it may not be possible to achieve this target, and the target is likely to change anyway (as mentioned in the previous section). Sommerville distinguishes between less detailed user requirements and more detailed system requirements. He also distinguishes between functional requirements (e.g. update a record) and non-functional requirements (e.g. response time must be less than 1 second).


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." 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. Any non-functional system requirements (response time, reliability, maintainability, etc.) need to be considered at this stage. The software architecture is also of interest to various stakeholders (sponsors, end-users, etc.) since it gives them a chance to check that their requirements can be met.


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)

Mayer states: "No programming language is perfect. There is not even a single best language; there are only languages well suited or perhaps poorly suited for particular purposes. Understanding the problem and associated programming requirements is necessary for choosing the language best suited for the solution." From Meek & Heath: "The essence of the art of choosing a language is to start with the problem, decide what its requirements are, and their relative importance since it will probably be impossible to satisfy them all equally well. The available languages should then be measured against the list of requirements, and the most suitable (or least unsatisfactory) chosen." It is possible that different programming languages may be appropriate for different aspects of the problem. If the languages or their compilers permit, it may be feasible to mix routines written in different languages within the same program. Even if there is no choice as to which programming language is to be used, McConnell provides some advice: "Every programming language has strengths and weaknesses. Be aware of the specific strengths and weaknesses of the language you're using."


Coding standards

This section is also really a prerequisite to coding, as McConnell points out: "Establish programming conventions before you begin programming. It's nearly impossible to change code to match them later." As listed near the end of
Coding conventions Coding conventions are a set of guidelines for a specific programming language that recommend programming style, practices, and methods for each aspect of a program written in that language. These conventions usually cover file organization, in ...
, there are different conventions for different programming languages, so it may be counterproductive to apply the same conventions across different languages. It is important to note that there is no one particular coding convention for any programming language. Every organization has a custom coding standard for each type of software project. It is, therefore, imperative that the programmer chooses or makes up a particular set of coding guidelines before the software project commences. Some coding conventions are generic, which may not apply for every software project written with a particular programming language. The use of coding conventions is particularly important when a project involves more than one programmer (there have been projects with thousands of programmers). It is much easier for a programmer to read code written by someone else if all code follows the same conventions. For some examples of bad coding conventions, Roedy Green provides a lengthy (tongue-in-cheek) article on how to produce unmaintainable code.


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: # Name of the module # Purpose of the Module # Description of the Module # Original Author # Modifications # Authors who modified code with a description on why it was modified. The "description of the module" should be as brief as possible but without sacrificing clarity and comprehensiveness. However, the last two items have largely been obsoleted by the advent of
revision control system Revision Control System (RCS) is an early implementation of a version control system (VCS). It is a set of UNIX commands that allow multiple users to develop and maintain program code or documents. With RCS, users can make their own revisions of ...
s. Modifications and their authorship can be reliably tracked by using such tools rather than by using comments. Also, if complicated logic is being used, it is a good practice to leave a comment "block" near that part so that another programmer can understand what exactly is happening.
Unit testing In computer programming, unit testing is a software testing method by which individual units of source code—sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures&md ...
can be another way to show how code is intended to be used.


Naming conventions

Use of proper naming conventions is considered good practice. Sometimes programmers tend to use X1, Y1, etc. as variables and forget to replace them with meaningful ones, causing confusion. It is usually considered good practice to use descriptive names. Example: A variable for taking in weight as a parameter for a truck can be named TrkWeight or TruckWeightKilograms, with TruckWeightKilograms being the preferable one since it is instantly recognisable. See
CamelCase Camel case (sometimes stylized as camelCase or CamelCase, also known as camel caps or more formally as medial capitals) is the practice of writing phrases without spaces or punctuation. The format indicates the separation of words with a single ...
naming of variables.


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. For example, consider these equivalent lines of C code: if (hours < 24 && minutes < 60 && seconds < 60) else and if (hours < 24 && minutes < 60 && seconds < 60) return true; else return false; and switch (hours < 24 && minutes < 60 && seconds < 60) and return hours < 24 && minutes < 60 && seconds < 60; The 1st approach, which is much more commonly used, is considerably larger than the 4th. 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 2nd 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 4th form. The fourth form obviously minimizes the size but may increase the complexity: It 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 4th form could have problems due to
operator precedence In mathematics and computer programming, the order of operations (or operator precedence) is a collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given mathematical expression. For exampl ...
, 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. For large, long lived programs using verbose alternatives could contribute to bloat. 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, and also lessen finger, wrist and eye strain, which are common medical issues suffered by production coders and information workers. Terser coding speeds compilation very slightly, as fewer symbols need to be processed. Furthermore, the 3rd 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 The Gutenberg Bible (also known as the 42-line Bible, the Mazarin Bible or the B42) was the earliest major book printed using mass-produced movable metal type in Europe. It marked the start of the " Gutenberg Revolution" and the age of printed ...
). 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 comprehensio
Text Columns: How Long is Too Long?
and add to eye-tracking errors. Some studies suggest that longer lines fare better online than in prin
Human Factors International
but this still only goes up to about 10 inches, and mainly for raw speed of reading prose.


Portability

Program code should not contain "hard-coded" (literal) values referring to environmental parameters, such as absolute file paths, file names, user names, host names, IP addresses, and URLs, UDP/TCP ports. Otherwise, the application will not run on a host that has a different design than anticipated. A careful programmer can parametrize such variables and configure them for the hosting environment outside of the application proper (for example, in property files, on an application server, or even in a database). Compare the mantra of a "single point of definition" (SPOD). As an extension, resources such as XML files should also contain variables rather than literal values, otherwise, the application will not be portable to another environment without editing the XML files. For example, with J2EE applications running in an application server, such environmental parameters can be defined in the scope of the JVM, and the application should get the values from there.


Scalability

Design code with scalability as a design goal because very often in software projects, new features are always added to a project which becomes bigger. Therefore, the facility to add new features to a software code base becomes an invaluable method in writing software.


Reusability

Re-use is a very important design goal in software development. Re-use cuts development costs and also reduces the time for development if the components or modules which are reused are already tested. Very often, software projects start with an existing baseline that contains the project in its prior version and depending on the project, many of existing software modules and components are reused, which reduces development and testing time, therefore, increasing the probability of delivering a software project on schedule.


Construction guidelines in brief

A general overview of all of the above: # Know what the code block must perform # Maintain naming conventions which are uniform throughout. # Indicate a brief description of what a variable is for (reference to commenting) # Correct errors as they occur. # Keep your code simple # Design code with scalability and reuse in mind.


Code development


Code building

A best practice for building code involves daily builds and testing, or better still continuous integration, or even
continuous delivery Continuous delivery (CD) is a software engineering approach in which teams produce software in short cycles, ensuring that the software can be reliably released at any time and, following a pipeline through a "production-like environment", withou ...
.


Testing

Testing is an integral part of software development that needs to be planned. It is also important that testing is done proactively; meaning that test cases are planned before coding starts, and test cases are developed while the application is being designed and coded.


Debugging the code and correcting errors

Programmers tend to write the complete code and then begin debugging and checking for errors. Though this approach can save time in smaller projects, bigger and more complex ones tend to have too many variables and functions that need attention. Therefore, it is good to debug every module once you are done and not the entire program. This saves time in the long run so that one does not end up wasting a lot of time on figuring out what is wrong.
Unit test In computer programming, unit testing is a software testing method by which individual units of source code—sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures&md ...
s for individual modules and/or
functional test Functional testing is a quality assurance (QA) processPrasad, Dr. K.V.K.K. (2008) ''ISTQB Certification Study Guide'', Wiley, , p. vi and a type of black-box testing that bases its test cases on the specifications of the software component und ...
s for web services and web applications can help with this.


Deployment

Deployment is the final stage of releasing an application for users. Some best practices are: # Keep the installation structure simple: Files and directories should be kept to a minimum. Don’t install anything that’s never going to be used. # Keep only what is needed: The
software configuration management In software engineering, software configuration management (SCM or S/W CM) is the task of tracking and controlling changes in the software, part of the larger cross-disciplinary field of configuration management. SCM practices include revision ...
activities must make sure this is enforced. Unused resources (old or failed versions of files, source code, interfaces, etc.) must be archived somewhere else to keep newer builds lean. # Keep everything updated: The software configuration management activities must make sure this is enforced. For delta-based deployments, make sure the versions of the resources that are already deployed are the latest before deploying the deltas. If not sure, perform a deployment from scratch (delete everything first and then re-deploy). # Adopt a multi-stage strategy: Depending on the size of the project, sometimes more deployments are needed. # Have a roll back strategy: There must be a way to roll-back to a previous (working) version. # Rely on automation for repeatable processes: There's far too much room for human error, deployments should not be manual. Use a tool that is native to each operating system or, use a scripting language for cross-platform deployments. # Re-create the real deployment environment: Consider everything (routers, firewalls, web servers, web browsers, file systems, etc.) # Do not change deployment procedures and scripts on-the-fly and, document such changes: Wait for a new iteration and record such changes appropriately. # Customize deployment: Newer software products such as APIs, micro-services, etc. require specific considerations for successful deployment. # Reduce risk from other development phases: If other activities such as testing and configuration management are wrong, deployment surely will fail. # Consider the influence each stakeholder has: Organizational, social, governmental considerations.


See also

*
Best practice A best practice is a method or technique that has been generally accepted as superior to other known alternatives because it often produces results that are superior to those achieved by other means or because it has become a standard way of doing ...
*
List of tools for static code analysis This is a list of notable tools for static program analysis (program analysis is a synonym for code analysis). Static code analysis tools Languages Ada * * * * * * * * * * * C, C++ * * * * * * * * * * * * ...
* Motor Industry Software Reliability Association (MISRA) *
Software Assurance Software assurance (SwA) is defined as "the level of confidence that software is free from vulnerabilities, either intentionally designed into the software or accidentally inserted at any time during its lifecycle, and that the software functions ...
* Software quality *
List of software development philosophies This is a list of approaches, styles, methodologies, philosophies in software development and engineering. It also contains programming paradigms, software development methodologies, software development processes, and single practices, principl ...
*
The Cathedral and the Bazaar ''The Cathedral and the Bazaar: Musings on Linux and Open Source by an Accidental Revolutionary'' (abbreviated ''CatB'') is an essay, and later a book, by Eric S. Raymond on software engineering methods, based on his observations of the Linux ...
- book comparing top-down vs. bottom-up open-source software * Davis 201 Principles of Software Development * Where's the Theory for Software Engineering? * ''Don't Make Me Think'' (Principles of intuitive navigation and information design)


References

;General *
Enhancing the Development Life Cycle to Product Secure Software, V2.0 Oct. 2008
describes the security principles and practices that software developers, testers, and integrators can adopt to achieve the twin objectives of producing more secure software-intensive systems, and verifying the security of the software they produce. * {{cite web , url=http://www.ibm.com/developerworks/aix/library/au-hook_duttaC.html , title=Best practices for programming in C , first1=Shiv , last1=Dutta , first2=Gary , last2=Hook , date=June 26, 2003 , work=developerWorks , publisher= IBM , accessdate=January 21, 2010 , url-status=dead , archiveurl=https://web.archive.org/web/20090713030558/http://www.ibm.com/developerworks/aix/library/au-hook_duttaC.html , archivedate=July 13, 2009


External links

* Paul Burden, co-author of the MISRA C Coding Standards and PRQA's representative on the MISRA C working group for more than 10 years discusses a common coding standard fallacy
"we don't need a coding standard!, we just need to catch bugs!"
Software development process Computer programming