Maintaining high quality code is one of the developer’s top responsibilities.
It is easy to neglect code quality when working under a deadline, fixing bugs, or adding a new feature. Over time the code becomes harder to understand and maintain, and harder to test.
Eventually, such code is discarded and rewritten.
What is Code Quality
10 Best Practices
Clean Code
Coding Convention for Project or Organization
What To Include in your Coding Guide
Python Coding Standards
Documentation in Code
Style Checkers and Static Analysis
Django’s Coding Style Guide
Java Coding Style
Practices of an Agile Developer
What is Code Quality?
Code Quality is subjective, but accepted characteristics of good quality code are:
- code does what it should
- code can be tested (testable)
- easy to understand
- uses a consistent style
- is well-documented
- can be maintained (the above factors influence this)
References:
- What is Code Quality? on Perforce.com
- Code Quality Metrics on DZone.com
10 Best Practices
- Consistently use a coding standard. For Python use PEP8.
- Write document comments in a standard format: Javadoc or Python docstring.
- Use descriptive names for classes, functions, and variables.
- Write short functions (methods) that do only one thing.
- Use return values instead of side effects when possible.
- Avoid unexpected side effects. Use the “Command Query Separation Principle”.
- Review all your own code.
- On a team project, review code with others.
- Use a Code Review guide & checklist.
- Use tools to check code. Perform static analysis, linting, and style checking.
- pylint, flake8, or ruff for style, linting, and some error checking
- mypy for static analysis
- Refactor to improve code.
Many projects have a “refactoring day” when the only work done is code review and refactoring.
Clean Code
Clean Code refers to code that follows good design principles and is well-written.
Clean Code is easier to read, test, maintain, and evolve.
What defines Clean Code can be vague and subjective,
just as “good”, “well”, and “easy” are subjective.
Clean Code PDF by JeremyBytes. His web page on clean code has other useful material.
Discussion:
-
Important lessons from Clean Code and Code Complete.
-
How to use Checkstyle for Java or Pylint and Flake8 for Python.
-
Look at coding guidelines from some real projects. Apache is a good source.
Coding Convention for a Project or Organization
Team projects usually have a “coding standard”. It helps others understand your code, and avoids pointless commit conflicts caused when each person’s IDE reformats the same block of code.
Google, Microsoft, and the Apache Foundation have organization-wide coding standards. The VSCode Project has a coding standard.
What to include in your coding guide
- Include what is important to you and your team.
- Add things when you discover a repeated problesm.
- Keep it simple and practical
- Document by example is OK, instead of lots of text (TL;DR)
Here are some good things to include:
- how to name files and how to organize them
- code formatting rules
- coding rules
- naming convention for variables, functions, classes, interfaces, and more
- handling exceptions - don’t ignore exceptions
- when to raise an exception
- when to use logging?
- use assertions?
- use guard clauses instead of nested “if”?
- do you require type hints?
- how much detail in type hints?
- do collection type hints use
collections.abc
ortyping
?
- how to check coding style?
- For example, flake8, pylint, or ruff code checking tools
- Does the project have a config file to customize flake8 or pylint? (Google has one for pylint)
- use an code formatting tool to make it easy?
- Comments and comment style, especially method and class docstring comments.
Python Coding Standards
PEP8 is the Python “official” coding standard:
- How to Write Beautiful Code with PEP8 on RealPython. Lot’s of helpful examples.
- pep8.org is a single page easy-to-read summary of how to use PEP 8 the official Python Style Guide.
- Style guide lists “pros” and “cons” of style choices & explains why do it.
- Rule #1 is “Run
pylint
over your code using this .pylintrc” - Part 2 is guide for using the Python language
- Part 3 “Python Style Rules” for coding style
- Part 4 “Parting Words” is: Be Consistent
- Google’s guide is very prescriptive (do and don’t) on how to write code
Documentation in Code
PEP257 Docstrings is a one page guide to the Python docstring standard.
My Docstrings write-up describes 3 styles for parameters, returns, and exceptions in docstrings.
We will use Sphinx style docstrings except use Type Hints for parameter and return types, not docstring comments. So don’t use the :type var:
tags in docstrings.
def average(values: Collection[float|int]) -> float:
"""Compute the arithmetic average of a collection of values.
:param values: non-empty collection of numeric values to average
:returns: the population average of the values
:raises ValueError: if collection is empty or contains invalid values
"""
View docstrings in Python interactive shell:
help(something)
shows formatted docstringprint(something.__doc__)
shows docstring forsomething
Tools to generate formatted documentation:
- pydoc
- Sphinx and Napolean (add-on). Create HTML or ReSt format docs. Used to create ReadTheDocs content.
Comments in Code
- Use comments to explain why and details that are not obvious from the code.
- Don’t explain “what” or “how” that is evident from the code itself.
Style Checkers and Static Analysis Tools
flake8
withflake8-docstrings
extensionruff
a fast alternative to flake8. Claims to check a superset of flake8.pylint
performs both style checking and some static analysismypy
for static analysis. Uses type hints for improved static analysis.
PyCharm has a builtin code checking tool; you can customize it, or configure PyCharm to use an external tool.
VS Code: choose an external “Lint” tool in settings (CTRL-SHIFT-P and type ‘python’)
Python Code Quality on RealPython.com explains best practices & tools.
My Code Quality Tools page describes how to use some tools.
Django’s Coding Style Guide
Django uses the Python PEP8 and PEP? (another PEP) with a few exceptions, described in the link below.
The link is guidelines for anyone who contributes code to the Django project. The guide is also useful for developers writing Django apps.
Django uses flake8
to check coding style.
https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/
Practices of an Agile Developer
Many Tips in Practices of an Agile Developer concern code quality. The authors must think it’s important!
Tip 2. Quick Fixes Become Quicksand
Tip 25. Program Intently and Expressively
Tip 26. Communicate in Code
Tip 30. Write Cohesive Code
PAD Quick Reference from Practices of an Agile Developer.