Complete Code Quality Guide

Measuring the quality of code

Just like quality assurance is done in manufacturing, testing code quality is also done in software development. While developing software or if you're inspecting code written by your team, you need to make sure you verify its quality at every level of development before it gets more complex. In the world of software, the phrase code quality can be interpreted in different ways by different industries and teams.

However, there are some code quality measuring parameters that cut across all industries and teams. In this article, I am going to share with you everything you need to know about code quality, why it is necessary, and how it is measured.

The code quality assurance methods that I am going to share can be used to verify code quality on both your local machine or GitHub code quality.  Just make sure you read till the end.


What is code quality?

Code quality refers to the measure of how good code for executing a given task is written. So, code that is not written well enough can be referred to as bad quality code, whereas code that is written well can be referred to as good quality code.

The quality of code can be asses by either the programmer, CTO, or even the CEO in some cases.


Why you need to measure code quality

Just like Bill Gates said,

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

The progress of programming should be assessed by not only the quantity of code but by quality too. Here is why:

· It is necessary for continuity: If you are building any software, having poor quality code will make it hard for the next person or team to take on the project.

· To avoid having to make too many modifications in the future: If you don't measure code quality early enough, you will likely have to make modifications in the future that would likely lead to more financial costs and a waste of time.

· To build a good reputation as a brand: When you write poor quality code, the end program will not be as effective and efficient as it should be. Such work could damage your reputation as a brand in the long run. So, measuring code quality can help you avoid all this.

· It eases team collaboration: Doing a code quality check will ensure that the code written by every programmer on the team is easily understood by the rest of the team members. This is important for the project that requires collaborative efforts.

·Nurturing: code quality checking works best for junior developers. In that case, senior engineers can spend less time on code review and also less time to explain why it is worth writing this way and not otherwise. It will also be useful for more experienced workers who start to learn new technologies.


Why is it so important for business?

How to measure the quality of code

Here are some of the parameters used to measure the quality of code

Maintainability

It is almost impossible to write code that is free of bugs, especially if you are working on complex software projects that requires writing programs with several lines of code. That is why it is necessary to make it easy to fix any errors that could be in the code without taking a lot of time.

For instance, if fixing a few lines code takes hours or even days because it affects the major part of the program, it means that code is not easily maintainable and hence poor-quality code.

Good quality code should be efficient

Any software program runs using computing hardware resources. Efficient code uses the minimum possible hardware resources that it needs to get the intended task done. A program that uses more hardware resources that it requires is considered not efficient, which means its code is not of good quality.

Another way of measuring efficiency is the time it takes for the code to do the intended task. A program that takes less time to run is considered to be more efficient hence having code quality code than one that takes more time.

Readability and formatting

Good quality code should be easy to read for even beginner programmers. The formatting and spacing used while writing programs should also follow the standards of the programming language used to write the program.

Code that is properly formatted and easy to read is considered to be of good quality than code that is harder to read and not properly formatted.

Adding comments to the code also improves readability, which further boosts its quality. So, while doing code quality assurance, you need to take note of whether the comments are used wherever they are required.

A large codebase is hard to read and difficult to find the right part of the code in it, so this issue should be avoided.

Extensibility

Extensibility in coding refers to the level of flexibility of adding more features in your program. Good quality should make adding new features to the program easy and shouldn't require making a lot of modifications for the code to run properly.


Use of code quality analysis tools

There are several software programs out there that were designed to measure the quality of code. Here are some of the most commonly used ones that you can try out.

1. Reshift: This is a SaaS platform that developers can be used to check for any deficiencies in the code before going ahead to deploy it to production. It is used mainly for programs written in Java, .Net, and C#.

2. duecode.io: It is a SaaS platform that can be used by both top management and the real programmers to assess the quality of code. duecode.io will surely help you improve the quality of code – and the good news is it supports several programming languages. This tool can be used for up to 30 days for free and you don’t even have to give in your credit card details to get this trial period.

3. Embold: This is another code quality analysis tool that can is used to assess the robustness, maintainability, stability and security of your code. Embold supports over ten programming languages and can be integrated into GitHub, Azure, Bitbucket, and Git.

4. PVS-Studio:  It is a software quality analysis tool that is used to check for bugs and any security vulnerabilities in code written in languages like C#, C++, C, and Java. The good news is PVS-Studio can be used on Linux, Windows, and macOS.

5. SonarQube: It is an online code reviewing tool that makes sure all your coding modules are analyzed for their quality. Packed with a range of features, it helps you write good quality code without much hassle.

There are several other code quality analysis tools that you use to measure the quality of your code. All you need to do is look for one that suits the language used to write the program whose quality you intend to measure.

Java code quality examples

Order of Constructors and Overloaded Methods

Constructors and overloaded methods should be grouped together by functionality and ordered with increasing arity. This implies that delegation among these constructs flow downward in the code.

Constructors and overloaded methods should not be split apart by other members.

Good code:

public HashSet() {
    this(DEFAULT_INITIAL_CAPACITY);
}

public HashSet(int capacity) {
    this(capacity, DEFAULT_LOAD_FACTOR);
}

public HashSet(int capacity, double loadFactor) {
    …
}

Bad code:

// Overloaded methods should not be split apart
void logValue(int i) {
    log("Int: %d", i);
}

void setValue(int i) {
    val = i;
}

void logValue(double d) {
    log("Double: %.2d", d);
}

void setValue(double d) {
    val = d;
}

Braces

Opening braces should be put on the end of the current line rather than on a line by its own.There should be a new line in front of a closing brace unless the block is empty (see Short Forms below)

Braces are recommended even where the language makes them optional, such as single-line if and loop bodies.

  • If a block spans more than one line (including comments) it must have braces.
  • If one of the blocks in a if / else statement has braces, the other block must too.
  • If the block comes last in an enclosing block, it must have braces.
  • Indentation level is four spaces.
  • Only space characters may be used for indentation. No tabs.
  • Empty lines must not be indented. (This is implied by the no trailing white space rule.)
  • Case lines should be indented with four spaces, and statements within the case should be indented with another four spaces.

Examples of good quality code:

void method() {
    …
}
try {
    something();
} catch (AnException e) {
    …
}
for (int[] row : matrix) {
    for (int val : row) {
        sum += val;
    }
}

Examples of bad quality code:

// Wrong placement of opening brace
void method()
{
    …
}
// Newline in front of catch should be avoided
try {
    something();
}
catch (AnException e) {
    …
}
// Braces should be used
if (flag)
    // Restore x
    x = 1;
// Use braces if block comes last in enclosing block
// to avoid accidentally indenting the closing brace.
for (int[] row : matrix) {
    for (int val : row)
        sum += val;
}

Indentation

Dos:

switch (var) {
    case TWO:
        setChoice("two");
        break;
    case THREE:
        setChoice("three");
        break;
    default:
        throw new IllegalArgumentException();
}

Don'ts:

switch (var) {
case TWO:
    setChoice("two");
    break;
case THREE:
    setChoice("three");
    break;
default:
    throw new IllegalArgumentException();
}

Constants

Constants (static final fields whose content is immutable, by language rules or by convention) should be named with all capital letters and underscore (_) to separate words.

Dos:

public static final int BUFFER_SIZE = 1024;
enum ApplicationMode { RUNNING, PAUSED, TERMINATED }

Don'ts:

public final List<String> CURRENT_WORDS = new ArrayList<>();
enum ApplicationMode { Running, Paused, Terminated }

Javadoc

  • Start longer comments with a short summarizing sentence since Javadoc includes this in the method summary table.
  • Prefer inline tags (such as {@code …} and {@link …} etc) over corresponding HTML tags (<code>…</code>, <a href="…">…</a> etc).
  • Use <p> to separate paragraphs (closing </p> tags are not needed and should not be used)
  • Declaration annotations should be put on a separate line from the declaration being annotated.
  • Few/short annotations annotating a single-line method may however be put on the same line as the method if it improves readability.
  • Either all annotations should be put on the same line or each annotation should be put on a separate line.

Well-written code:

/** A short javadoc comment */
/**
 * …
 *
 * <blockquote>{@code
 *     List<String> names;
 * }</blockquote>
 */

Bad-written code:

/** put on single line instead
 */
/**
 * The <String> below may interfere with the HTML!
 *
 * <blockquote><pre>
 *     List<String> names;
 * </pre></blockquote>
 */

Annotations

Good quality code:

@Deprecated
@Override
public void foo() {
    …
}
@Deprecated @Override
public void foo() {
    …
}
addListener(new Listener() {
 
    // Ignored events
    @Override public void event1() { }
    @Override public void event2() { }
    @Override public void event3() { }
 
    // Important event
    @Override
    public void event4() {
        …
    }
});

Bad quality code:

@Override @Deprecated public void foo() {
    …
}
@Override @Deprecated
@SafeVarargs
public void foo() {
    …
}

Wrapping Lines

Source code and comments should generally not exceed 80 characters per line and rarely if ever exceed 100 characters per line, including indentation.

The character limit must be judged on a case by case basis. What really matters is the semantical “density” and readability of the line. Making lines gratuitously long makes them hard to read; similarly, making “heroic attempts” to fit them into 80 columns can also make them hard to read. The flexibility outlined here aims to enable developers to avoid these extremes, not to maximize use of monitor real-estate.

URLs or example commands should not be wrapped.

Dos:

// Ok even though it might exceed max line width when indented.
Error e = isTypeParam
        ? Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on)
        : Errors.InvalidRepeatableAnnotationNotApplicableInContext(targetContainerType));
String pretty = Stream.of(args)
                      .map(Argument::prettyPrint)
                      .collectors(joining(", "));

Don’ts:

// Too strict interpretation of max line width. Readability suffers.
Error e = isTypeParam
        ? Errors.InvalidRepeatableAnnotationNotApplicable(
                targetContainerType, on)
        : Errors.InvalidRepeatableAnnotationNotApplicableInContext(
                targetContainerType);
// Should be wrapped even though it fits within the character limit
String pretty = Stream.of(args).map(Argument::prettyPrint).collectors(joining(", "));

More Java code quality examples and guidelines here.

JavaScript code quality examples

Use expanded syntax

For JavaScript we use expanded syntax, with each line of JS on a new line, the opening brace of a block on the same line as its associated statement, and the closing brace on a new line. This maximizes readability, and again, promotes consistency on MDN.

Do this

function myFunc() {
    console.log('Hello!');
};

Not this

function myFunc() { console.log('Hello!'); };

We also have a few specific rules around spacing inside language features. You should include spaces between operators and operands, parameters, etc.

This is more readable:

if(dayOfWeek === 7 && weather === 'sunny') { 
    goOnTrip('beach', 'car', ['ice cream', 'bucket and spade', 'beach towel']); 
}

than this:

if(dayOfWeek===7&&weather==='sunny'){ goOnTrip('beach','car',['ice cream','bucket and spade','beach towel']); }

In addition, keep these specifics in mind:

  • Don't include padding spaces after opening brackets or before closing brackets — (myVar), not ( myVar ).
  • All statements must end with semicolons (";"). We require them in all of our code samples even though they're technically optional in JavaScript because we feel that it leads to code that is clearer and more precise about where each statement ends.
  • Use single quotes in JavaScript, wherever single quotes are needed in syntax.
  • There should be no space between a control statement keyword, function, or loop keyword and its opening parenthesis (e.g. if() { ... }, function myFunc() { ... }, for(...) { ... }).
  • There should be a space between the parentheses and the opening curly brace in such cases as described in the previous bullet.

Operators and comparison

Ternary operators should be put on a single line:

let status = (age >= 18) ? 'adult' : 'minor';

Not nested:

let status = (age >= 18) 
? 'adult' 
: 'minor';

This is much harder to read.

Always use strict equality and inequality.

Good code:
name === 'Chris'; 
age !== 25;
Bad code:
name == 'Chris'; 
age != 25;

Control statements

Write control statements like this:

if(iceCream) {
    alert('Woo hoo!'); 
}

Not this:

if (iceCream){
    alert('Woo hoo!');
}

Strings

Use template literals


For inserting values into strings, use string literals.

Do this:
let myName = 'Chris';
console.log(`Hi! I'm ${myName}!`);
Not this:
let myName = 'Chris';
console.log('Hi! I\'m' + myName + '!');

Use textContent, not innerHTML

When inserting strings into DOM nodes, use Node.textContent:
let text = 'Hello to all you good people';
const para = document.createElement('p');
para.textContent = text;
Not Element.innerHTML:
let text = 'Hello to all you good people';
const para = document.createElement('p'); 
para.innerHTML = text;

textContent is a lot more efficient, and less error-prone than innerHTML.

Conditionals

General purpose looping

When loops are required, feel free to choose an appropriate loop out of the available ones (for, for...of, while, etc.) Just make sure to keep the code as understandable as possible.

When using for/for...of loops, make sure to define the initializer properly, with a let keyword:
let cats = ['Athena', 'Luna']; 
for(let i of cats) {
    console.log(i);
}
Not
let cats = ['Athena', 'Luna'];
for(i of cats) { 
    console.log(i); 
}
Also bear in mind:
  • There should be no space between a loop keyword and its opening parenthesis.
  • There should be a space between the parentheses and the opening curly brace.

Functions and objects


For function names use lowerCamelCasing, and use concise, human-readable, semantic names where appropriate.

Do this:
function sayHello() {
    alert('Hello!');
};
Not this:
function SayHello() {
    alert('Hello!');
};

function notVeryObviousName() { 
    alert('Hello!');
};

Defining functions


Where possible, use the function declaration to define functions over function expressions:

Do this:
function sum(a, b) {
    return a + b; 
}
Not this:
let sum = function(a, b) {
    return a + b;
}

When using anonymous functions inside a method that requires a function as a parameter, it is acceptable (although not required) to use an arrow function to make the code shorter and cleaner.

So instead of this:
const array1 = [1, 2, 3, 4];
let sum = array.reduce(function(a, b) {
    return a + b; 
});
you could write this:
const array = [1, 2, 3, 4];
let sum = array.reduce((a, b) =>
     a + b 
     );
Also bear in mind:
  • There should be no space between a function name and its opening parenthesis.
  • There should be a space between the parentheses and the opening curly brace.

Creating objects


Use literals — not constructors — for creating general objects (i.e., when classes are not involved):

Good code:
let myObject = { };
Smelly code:
let myObject = new Object();

Arrays

Creating arrays


Use literals — not constructors — for creating arrays:

Do this:
let myArray = [ ];
Not this:
let myArray = new Array(length);

Adding to an array


When adding items to an array, use push(), not direct assignment. Given the following array:

const pets = [];
do this:
pets.push('cat');
not this:
pets[pets.length] = 'cat';

More JavaScript code quality examples and guidelines here.

PHP code quality examples

Include/Require Once

Include/require once SHOULD be used.

Acceptable

<?php

include 'some-file.php';
require 'some-other-file.php';

// EOF
 
↳ Acceptable, but _once should be appended to include and require if possible.

Preferred

<?php

include_once 'some-file.php';
require_once 'some-other-file.php';

// EOF

Parenthesis

Parenthesis MUST NOT be used.

Incorrect

<?php

include_once('some-file.php');
require_once('some-other-file.php');

// EOF
 
↳ Incorrect because include_once and require_once are used with parenthesis.


Correct

<?php

include_once 'some-file.php';
require_once 'some-other-file.php';

// EOF


Purpose of Include

Purpose of include MUST be documented with a comment.

Incorrect

<?php

require_once 'some-file.php';

// EOF
 
↳ Incorrect because there is no comment as to what some-file.php does or provides.

Correct

<?php

// Provides XYZ framework
require_once 'some-file.php';

// EOF

Line Length

Line length MUST NOT exceed 80 characters, unless it is text.

Incorrect

<?php

if(in_array('Slumdog Millionaire', $movies) && in_array('Silver Linings Playbook', $movies) && in_array('The Lives of Others', $movies) && in_array('The Shawshank Redemption', $movies)) {
	// if body
}

// EOF
 
↳ Incorrect because expression exceeds 80 characters and should be refactored.
<?php

$my_movies = array('Slumdog Millionaire', 'Silver Linings Playbook', 'The Lives of Others', 'The Shawshank Redemption');

// EOF
 
↳ Incorrect because arguments exceed 80 characters and should be placed on their own line.

~ Acceptable

<?php

$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec posuere rutrum tincidunt. Duis lacinia laoreet diam, nec consectetur magna facilisis eget. Quisque elit mauris, auctor quis vulputate id, sagittis nec tortor. Praesent fringilla lorem eu massa convallis ultricies. Maecenas lacinia porta purus, sollicitudin condimentum felis mollis a. Proin sed augue purus. Quisque scelerisque eros vitae egestas porta. Suspendisse vitae purus justo. Pellentesque justo nunc, luctus quis magna sit amet, venenatis rutrum ante. Nam eget nisi ultricies, sodales lectus vel, luctus dui. Cras pellentesque augue vitae nulla laoreet convallis. Mauris ut turpis mollis, elementum arcu eu, semper risus. Mauris vel urna ut felis blandit dictum. Aliquam sit amet tincidunt arcu. Nunc et elit quam. Aliquam hendrerit magna ut lacus semper consequat blandit eu ipsum.';

// EOF
 
↳ Acceptable because line length was exceeded due to text, not code.

Correct

<?php

$my_movies = array(
	'Slumdog Millionaire',
	'Silver Linings Playbook',
	'The Lives of Others',
	'The Shawshank Redemption'
);

$has_all_movies = true;

foreach($my_movies as $my_movie) {
	if(!in_array($my_movie, $movies)) {
		$has_all_movies = false;
	}
}

if($has_all_movies) {
	// if body
}

$some_long_variable = get_something_else(
	'from_some_other_function',
	'another_long_argument'
);

// EOF

Line Indentation

Line indentation MUST be accomplished using tabs.

Bad Quality

<?php

function print_welcome_message() {
    echo WELCOME_MESSAGE;
}

// EOF
 
↳ Incorrect because spaces are used to indent echo WELCOME_MESSAGE; instead of a tab.

Good Quality

<?php

function print_welcome_message() {
	echo WELCOME_MESSAGE;
}

// EOF

Trailing Whitespace

Trailing whitespace MUST NOT be present after statements or serial comma break or on blank lines.

Incorrect

<?php

$quotes_exist = false;  

print_welcome_message();

// EOF
 
↳ Incorrect because there are two spaces after $quotes_exist = false;.
<?php

$my_movies = array(
	'Slumdog Millionaire', 
	'Silver Linings Playbook', 
	'The Lives of Others', 
	'The Shawshank Redemption'
);

// EOF
 
↳ Incorrect because there is a space after ,.
<?php

$quotes_exist = false;
  
print_welcome_message();

// EOF
 
↳ Incorrect because there are two spaces on the blank line below $quotes_exist = false;.

Correct

<?php

$quotes_exist = false;

print_welcome_message();

// EOF
 
<?php

$my_movies = array(
	'Slumdog Millionaire',
	'Silver Linings Playbook',
	'The Lives of Others',
	'The Shawshank Redemption'
);

// EOF

Keywords

Keywords MUST be all lowercase.

Don’ts

<?php

$is_true = FALSE;
$is_false = TRUE:
$movie_quote = NULL;

// EOF
 
↳ Incorrect because FALSE, TRUE and NULL are not all lowercase.

Dos

<?php

$is_true = false;
$is_false = true:
$movie_quote = null;

// EOF

Variables

Variables MUST be all lowercase and words MUST be separated by an underscore.

Incorrect

<?php

$welcome_Message = '';
$Welcome_Message = '';
$WELCOME_MESSAGE = '';

// EOF
 
↳ Incorrect because $welcome_Message, $Welcome_Message and $WELCOME_MESSAGE are not all lowercase.
<?php

$welcomemessage = '';

// EOF
 
↳ Incorrect because welcome and message are not separated with an underscore.

Correct

<?php

$welcome_message = '';

// EOF

Operators

Operators MUST be surrounded a space.

Bad Code

<?php

$total=3+14;
$string='Hello, World! ';
$string.='Today is a good day!';

// EOF
 
↳ Incorrect because there is no space surrounding the =, + or .= sign.

Good Code

<?php

$total = 3 + 14;
$string = 'Hello, World! ';
$string .= 'Today is a good day!';

// EOF


Python code quality examples

Indentation

Use 4 spaces per indentation level.

Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent [7]. When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line:

Correct:

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# Add 4 spaces (an extra level of indentation) to distinguish arguments from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# Hanging indents should add a level.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

Wrong:

# Arguments on the first line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# Further indentation required as indentation is not distinguishable.
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)

Should a Line Break Before or After a Binary Operator?

For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line. Here, the eye has to do extra work to tell which items are added and which are subtracted:

Wrong:

# operators sit far away from their operands
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          student_loan_interest)

To solve this readability problem, mathematicians and their publishers follow the opposite convention. Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations" .

Following the tradition from mathematics usually results in more readable code:

Correct:

# easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)


In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.

Whitespace in Expressions and Statements

Avoid extraneous whitespace in the following situations:

Immediately inside parentheses, brackets or braces:

Correct:
spam(ham[1], {eggs: 2})
Wrong:
spam( ham[ 1 ], { eggs: 2 } )

Between a trailing comma and a following close parenthesis:

Correct:
foo = (0,)
Wrong:
bar = (0, )

Immediately before a comma, semicolon, or colon:

Correct:
if x == 4: print x, y; x, y = y, x
Wrong:
if x == 4 : print x , y ; x , y = y , x

However, in a slice the colon acts like a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority). In an extended slice, both colons must have the same amount of spacing applied.

Exception: when a slice parameter is omitted, the space is omitted:

Correct:
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
ham[lower:upper], ham[lower:upper:], ham[lower::step]
ham[lower+offset : upper+offset]
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
ham[lower + offset : upper + offset]
Wrong:
ham[lower + offset:upper + offset]
ham[1: 9], ham[1 :9], ham[1:9 :3]
ham[lower : : upper]
ham[ : upper]

Immediately before the open parenthesis that starts the argument list of a function call:

Correct:
spam(1)
Wrong:
spam (1)

Immediately before the open parenthesis that starts an indexing or slicing:

Correct:
dct['key'] = lst[index]
Wrong:
dct ['key'] = lst [index]

More than one space around an assignment (or other) operator to align it with another:

Correct:
x = 1
y = 2
long_variable = 3
Wrong:
x             = 1
y             = 2
long_variable = 3

Operators

If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Use your own judgment; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary operator:

Correct:

i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

Wrong:

i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)

Return Statements

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable):

Correct:

def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)

Wrong:

def foo(x):
    if x >= 0:
        return math.sqrt(x)

def bar(x):
    if x < 0:
        return
    return math.sqrt(x)

Variable Annotations

Annotations for module level variables, class and instance variables, and local variables should have a single space after the colon.

There should be no space before the colon.

If an assignment has a right hand side, then the equality sign should have exactly one space on both sides:

Correct:

code: int

class Point:
    coords: Tuple[int, int]
    label: str = '<unknown>'

Wrong:

code:int  # No space after colon
code : int  # Space before colon

class Test:
    result: int=0  # No spaces around equality sign


Final thought

Measuring the quality of code is something that every programmer, CTO, and CEO has to embrace if they want to write software that is efficient and effective in doing what it has to do at the present moment and in the future.

It could take you a couple of hours or even days to measure the quality of code, but this would save you a lot of financial resources and time that you could waste in the future as a result of poor-quality code. It is way much cheaper and less time consuming to have all the issues of quality resolved early enough than dragging them to the future after programs have gotten bigger and more complex.


FURTHER READING

- Code Quality Tools

- Code Quality Metrics

- Code Quality Standards

- How to measure, check and improve code quality:

-- How To Check Code Quality?

-- How To Measure Code Quality

-- How Can I Improve My Code Quality

-- How To Build A Website With Good Quality Code?

Updated on the 2nd of November, 2021