A program that works (produces correct output) is not necessarily a good program. In fact, most programs that appear to work fine are actually pretty crappy in most respects. There are several objective and subjective measures of good code. Most code quality measures and advice are specific to particular topics in programming and are therefore discussed throughout the text alongside the relevant topic. Below is a brief introduction to some of the basic concepts.
There are tools available to help you check code quality. The
GCC and Clang compilers both provide a -Wall
flag to issue as many warnings as possible about potential issues
during compilation.
Most Unix systems provide the lint command for further checking C code for potential issues. ( The command is so named because it picks the "lint" off your source code. ) There are similar source code analysis tools for most other languages as well.
Readability is a somewhat subjective measure of how easy it is for people to understand the code. Readability is determined by several factors such as comments that explain why the code is doing what it's doing, variable names that make it clear what a variable contains, etc.
Good code format involves consistent indentation (which is actually required by Python), and spacing (blank lines) to separate logical sections of code that perform separate tasks.
Most existing programs could be made to run much faster and use far fewer resources. Most programmers are content if the program works and is fast enough for their purposes on their hardware. This is sometimes OK, but it can create problems when someone wants to run the program with bigger inputs or on a computer with less memory or a slower CPU. Hence, it's best to try to write the fastest code possible and minimize resources used every time you write new code.
Is a program that produces correct output a high-quality program?
How can we request help locating problems in our code from compilers like clang and gcc?
What other tool might find problems that were missed by the compiler?
How do we make our code readable?
How fast should we try to make our programs? Why?
How much memory should our programs use? Why?
What does a robust program do?