sentenz / convention

General articles, conventions, and guides.
https://sentenz.github.io/convention/
Apache License 2.0
4 stars 2 forks source link

Create an article about `Indentation` #357

Open sentenz opened 2 weeks ago

sentenz commented 2 weeks ago

Indentation

Code indentation is a critical aspect of writing clean, readable, and maintainable software. It encompasses the practice of using Indentation Styles and Whitespaces (spaces or tabs) at the beginning of lines of code to visually separate blocks or statements according to their hierarchical level, typically within loops, conditionals, functions, or classes. Proper indentation enhances readability and clearly communicates the structure and flow of the code.

1. Category

1.1. Styles

1.1.1. K&R Style (Kernighan & Ritchie)

The Kernighan & Ritchie (K&R) style is a indentation styles widely used in C, C++, Java. It was introduced by Brian Kernighan and Dennis Ritchie, the creators of the C programming language

  1. Characteristics

    • Braces

      Opening brace { is placed on the same line as the control statement. Closing brace } is aligned with the control statement, on its own line.

    • Indentation

      Indentation typically uses 4 spaces or a tab.

  2. Examples and Explanations

    #include <stdio.h>
    #include <stdbool.h>
    
    bool isPrime(int number) {
        if (number <= 1) return false;
        for (int i = 2; i < number; i++) {
            if (number % i == 0) return false;
        }
        return true;
    }
    
    int main() {
        int num = 29;
        if (isPrime(num)) {
            printf("%d is a prime number.\n", num);
        } else {
            printf("%d is not a prime number.\n", num);
        }
        return 0;
    }

1.1.2. Allman Style (BSD Style)

The Allman Style, also known as BSD Style, is an indentation style used primarily in programming. It is named after Eric Allman, a computer scientist who helped develop the style while working on the BSD (Berkeley Software Distribution) operating system. This style emphasizes readability and clarity by placing braces on separate lines, which helps to visually distinguish code blocks.

  1. Characteristics

    • Braces

      The opening brace { of a code block (such as for loops, if statements, or function definitions) is placed on its own line directly below the control statement. The closing brace } is placed on a new line at the same indentation level as the control statement, matching the position of the corresponding opening brace.

    • Indentation

      The code within the block is indented, typically using either tabs or spaces (commonly 4 spaces), making the structure clear and organized.

  2. Examples and Explanations

    #include <stdio.h>
    #include <stdbool.h>
    
    bool isPrime(int number)
    {
        if (number <= 1)
            return false;
        for (int i = 2; i < number; i++)
        {
            if (number % i == 0)
                return false;
        }
        return true;
    }
    
    int main()
    {
        int num = 29;
        if (isPrime(num))
        {
            printf("%d is a prime number.\n", num);
        }
        else
        {
            printf("%d is not a prime number.\n", num);
        }
        return 0;
    }

1.1.3. OTBS (One True Brace Style)

The One True Brace Style (OTBS), also known as 1TBS, is a variant of the Kernighan & Ritchie (K&R) brace style and is a widely used indentation style, especially in C, C++, Java, and JavaScript. It is designed to maximize readability while minimizing vertical space usage, which makes it an efficient style for writing concise and structured code.

  1. Characteristics

    • Braces

      The opening brace { for control structures (e.g. if, for, while) is placed on the same line as the control statement. The closing brace } is aligned with the start of the control statement. The else or else if statements are placed on the same line as the closing brace of the preceding block.

    • Indentation

      Improves code maintainability and reduces the likelihood of introducing bugs.

  2. Examples and Explanations

    #include <stdio.h>
    #include <stdbool.h>
    
    bool isPrime(int number) {
        if (number <= 1) {
            return false;
        }
        for (int i = 2; i < number; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
    
    int main() {
        int num = 29;
        if (isPrime(num)) {
            printf("%d is a prime number.\n", num);
        } else {
            printf("%d is not a prime number.\n", num);
        }
        return 0;
    }

1.1.4. GNU Style

GNU style is a indentation style that originates from the GNU project, primarily used in C and C++ programming. It focuses on providing clarity and readability, especially for large codebases.

  1. Characteristics

    • Braces

      The opening brace { is placed on a new line, indented by two spaces. The closing brace } is aligned with the beginning of the statement that opens the block.

    • Indentation

      Indentation is typically 2 spaces per level. This minimizes excessive indentation while maintaining clear visual separation between code blocks.

  2. Examples and Explanations

    #include <stdio.h>
    #include <stdbool.h>
    
    bool isPrime(int number) {
        if (number <= 1)
            return false;
        for (int i = 2; i < number; i++) {
            if (number % i == 0)
                return false;
        }
        return true;
    }
    
    int main() {
        int num = 29;
        if (isPrime(num)) {
            printf("%d is a prime number.\n", num);
        }
        else {
            printf("%d is not a prime number.\n", num);
        }
        return 0;
    }

1.1.5. Whitesmiths Style

The Whitesmiths Style is an indentation style used in programming that places a strong emphasis on aligning the opening and closing braces {} with the indented code block rather than with the control structure or function header. Whitesmiths style is notable for its visual alignment, which is designed to make the start and end of code blocks very clear.

  1. Characteristics

    • Braces

      The opening and closing braces {} are placed on new lines, and they are indented to the same level as the code inside the block. This means the braces appear aligned with the block of code they contain, rather than with the control structure or function header.

    • Indentation

      Code inside a block is indented further than the braces, usually with a standard indentation width (typically 4 spaces or a tab).

  2. Examples and Explanations

    #include <stdio.h>
    #include <stdbool.h>
    
    bool isPrime(int number)
        {
            if (number <= 1)
                return false;
            for (int i = 2; i < number; i++)
                {
                    if (number % i == 0)
                        return false;
                }
            return true;
        }
    
    int main()
        {
            int num = 29;
            if (isPrime(num))
                {
                    printf("%d is a prime number.\n", num);
                }
            else
                {
                    printf("%d is not a prime number.\n", num);
                }
            return 0;
        }

1.1.6. Python Style (PEP 8)

Python's style guide, known as PEP 8, provides comprehensive guidelines for writing readable and maintainable Python code. Among its numerous recommendations, indentation is a fundamental aspect that ensures code structure is clear and consistent. Adhering to PEP 8's indentation rules not only enhances readability but also prevents common errors, especially in a language like Python where indentation defines code blocks.

  1. Characteristics

    • Braces

      Python relies entirely on indentation for defining code blocks, without the use of braces {}.

    • Indentation

      Uses consistent indentation (commonly 4 spaces) to define blocks, tabs are discouraged. Python Style syntax requires proper indentation, incorrect indentation leads to errors.

  2. Examples and Explanations

    def is_prime(number):
        if number <= 1:
            return False
        for i in range(2, number):
            if number % i == 0:
                return False
        return True
    
    def main():
        num = 29
        if is_prime(num):
            print(f"{num} is a prime number.")
        else:
            print(f"{num} is not a prime number.")
    
    if __name__ == "__main__":
        main()

1.2. Whitespaces

1.2.1. Tabs

In programming, tabs refer to the use of the tab character \t for indentation, typically to denote levels of nested code in many programming languages.

  1. Characteristics

    • Character

      A single tab character \t represents an indentation level in the code. The width of a tab character is usually displayed as 4 or 8 spaces, depending on the configuration of the editor or environment in use.

    • Efficiency

      Tabs allow for quicker navigation since a single keypress inserts a full indentation level. This can be particularly convenient for developers working on large blocks of code.

    • Accessibility/Customizable Width

      Each developer can configure their editor to display tab widths according to personal preferences (e.g. 4 spaces or 8 spaces). This flexibility allows different users (e.g. visually impaired) to view the code in the way they find most readable without altering the underlying structure.

    • File Size

      Since tabs represent a single character, they can result in slightly smaller file sizes compared to spaces, where multiple space characters are required for the same indentation level.

  2. Examples and Explanations

    if (condition)
    →do_something()

1.2.2. Spaces

Spaces refer to the use of space characters for code indentation, as opposed to using tab characters. Utilizing spaces for indentation is a widely adopted practice across many programming languages and is often preferred for its consistency and predictability in code formatting.

  1. Characteristics

    • Fixed Width

      Each space character has a uniform width, making indentation levels predictable.

    • Configurable Indentation Levels

      Typically, developers use 2 or 4 spaces per indentation level, depending on the project's style guide.

    • Consistency

      Spaces eliminate discrepancies in indentation caused by different tab width settings across editors.

  2. Examples and Explanations

    if (condition)
      do_something()

2. Best Practices

3. References

sentenz commented 1 week ago

Rename article tabs-vs-spaces.md to indentation.md.