DEV Community

tyrael
tyrael

Posted on

Code Readability

or Coding for Human Consumption

"Doing it good is not enough, you have to look good while doing it."

readabilityTITLE

Code readability is something that I find gets often overlooked when it comes to programming. This is a problem as readability is analogous
to hand-writing, and if everyone's writing is unintelligible, then discourse, and even corrections, would be difficult to achieve.

In order to code good, you have to code good.

Coding has to be, and can be, fun. And the first step towards that is to write code that doesn't make you want to OFF yourself whenever you're reading it.
Code architecture is important, so here are some opinionated takes I have on good programming practices, which you can take as code design guidelines.


TABLE OF CONTENTS:

BRACES AND INDENTS

  • When writing blocks of code (code within curly braces), there are 2 ways you can go about doing it, which I refer to as : Inset and Offset.

insetoffset

  • I personally do not mind either. I prefer Inset bracing as I like the compact feel of words vertically.
  • Ultimately, it's an entirely stylistic decision, just be consistent: do not alternate between either or they will look more like speedbumps for the reader instead of grouping operators.
int main(){
    int x, y;
    cin >> x >> y;

    if (x > y)
        swap(x,y);

    for (int i = 0; i<5; i++){
        x = x + y;

        if (x > y)
            swap(x,y);

        cout << x;
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode
  • Lastly, remember to properly indent whenever you enter a code block, and that you can omit the curly braces for when your code block only has ONE statement. If you value stability over sleekness, it is much safer to put in the braces, if you are uncertain on whether or not that code block will expand in the future.
  • A good rule to check for matching braces is to see if the statement that started your code block aligns/is in the same indentation further down with a closing curly brace.


    NESTING AND CONDITIONS

  • Avoid overly nesting your code.1

earlyreturn

  • Getting rid of nesting can be a matter of identifying early returns (if-else clauses that can be negated by swapping the if and the else), and/or extracting deeply nested code and putting them into their own seperate function.

int get_year_value(int year)
{
    /* returns value of the year (leap year or not) */
    if (year % 4)
        return 365;
    return 366;

}

int get_age(int bday_m, int bday_d, int bday_y, int targ_m, int targ_d, int targ_y)
{
    ...
    while (targ_y > bday_y)
    {
        diff += get_year_value(bday_y); 
        bday_y++;
    }
    ...
}
Enter fullscreen mode Exit fullscreen mode

note how the if condition for getting year_value is put onto a seperate function as to not nest the code

  • Moreover, always remember that control flow operators (if-else, while loops, basically anything that requires a condition) take in boolean, a true or false.
  • Recall that true or false can be also represented as 0 and 1 in pretty much all programming languages, so a good shorthand for checking for zero or not zero, is to just put the expression into the condition as is. (x != 0) is equal to simply (x), and (x == 0) is equal to (!x).


    NAMING AND CONSTANTS

  • Always use brief and concise names2, and only choose between camelCase or snake_case:

case

  • Avoid using single character names, with exceptions to for loops int i or Python's _ throwaway variable. Be descriptive, you will have to interpret your code multiple times over before you finally finish your project, do yourself a favor and make your variable names have less brain power cost.
  • Moreover, please use constants. Avoid hard-coding values, and/or repeating long chains of method calls.

consts

  • Constants are quite often overlooked as they just get overshadowed by variables, however; the scalability and readability that they provide is a pretty good bonus.
  #define SIZE 5
  ...
  // const SIZE = 5;
  int array[SIZE];
Enter fullscreen mode Exit fullscreen mode
  • In this example, refactoring/changing the code to handle an array of a different size than 5 is much less expensive (energy and time-wise) to do, especially
    if there are other instances in the code that utilize the size of the array.


    SPACING AND COMMENTS

  • Space your code in paragraphs (lines that are relevant to eachother) to reduce the visual noise of packed letters.

comments

  • Moreover, write documentation for your code. This is one of the best ways to improve understandability for other people who read your code.
  • BUT, whenever you are writing comments, be sure to write WHY your code does something, and not WHAT it does. The code itself should be sufficient in showing what it is doing, due to its procedural (being a sequence of instructions) nature.
  • An exemption to this rule are Docstrings, or the main comments that describe your function. All of your functions must have a docstring, paired with concise function names. Not only does this benefit your readability, it also shows up as a short description whenever you hover over one of your function calls.

    image

ONELINERS AND TERNARY OPERATORS

  • Though it is quite tempting to always go for less lines, readability suffers the longer your lines get. So don't be shy, use up more lines!

oneliner

  • Though it doesn't hurt to come up with very line-efficient algorithms, there has to be a balance with the compactness and readability of your code.
  • Moreover; ternary operators are very satisfying to read, but it has diminishing returns the longer you chain it.
  • A good rule of thumb is whenever your ternary operator chains at least once, you are better off using if-else statements.
  /* ans can be "yes", "no", or "maybe" */

  int decision = (ans == "yes") ? 1 : (ans == "no") ? 0 : -1;   // what the hell is happening?

  int decision;   // oohh
  if (ans == "yes")
    decision = 1;
  else if (ans == "no")
    decision = 0;
  else
    decision = -1;
Enter fullscreen mode Exit fullscreen mode

The less mental gymnastics the reader has to go through to understand your code, means the better your readability is.


  1. Why You Shouldn't Nest Your Code by Code Aesthetic 

  2. Naming Things in Code by Code Aesthetic 

Top comments (0)