Be Stylish
Learn to write code in a good style, as it is not only read by a compiler but other programmers, too.
We'll cover the following...
Coding in good style
The following two functions do exactly the same thing:
#include <assert.h>#include <stdint.h>#include <stdio.h>// START:good functionuint64_tfibonacci(unsigned int n) {if (n == 0 || n == 1) {return n;}else {uint64_t previous = 0;uint64_t current = 1;while (--n > 0) {uint64_t sum = previous + current;previous = current;current = sum;}return current;}}// END:good functionint main() {assert(fibonacci(0) == 0);assert(fibonacci(1) == 1);assert(fibonacci(2) == 1);assert(fibonacci(3) == 2);assert(fibonacci(4) == 3);assert(fibonacci(5) == 5);assert(fibonacci(6) == 8);assert(fibonacci(10) == 55);printf("All tests cases have been succesfully completed!");return 0;}
The following program is the same as given above. Both compute the Fibonacci of a number provided as input.
#include <assert.h>#include <stdint.h>#include <stdio.h>unsigned long long fbncci(unsigned int quux) { if(quux == 0 || quux == 1) { return quux; } else {unsigned long long foo = 0; unsigned long long bar= 1; while (--quux > 0) { unsigned long long baz =foo + bar; foo = bar; bar = baz; } return bar; } }int main(){assert(fbncci(0) == 0);assert(fbncci(1) == 1);assert(fbncci(2) == 1);assert(fbncci(3) == 2);assert(fbncci(4) == 3);assert(fbncci(5) == 5);assert(fbncci(6) == 8);assert(fbncci(10) == 55);printf("All tests cases have been succesfully completed!");return 0;}
Which would we rather maintain?
Maybe that example is a little extreme. But it illustrates a simple point that a compiler doesn’t just read our code. It’s read by other programmers, too. Writing code in good style is a factor in software quality because we simply can’t maintain illegible code.
Factors to style
The broad term style refers to everything the compiler doesn’t care about, but humans do. Here are some examples:
- Naming of classes, methods, variables, files, and so on
- Arrangement of functions within a file and across files
- Comments
- Braces and parentheses (where optional)
- Choice of control structures (where equivalent)
- Capitalization
- Indentation and other whitespaces
The definition of good style varies depending on the programmers we’re working with, project or corporate style guides, and conventions established by the programming language. However, there are some common themes we’ll look at here.