Tame product development chaos with YOUR Platform.

😊 Align the "happy path" in your code

Cliff Brake September 30, 2025 #coding #patterns #readability #simplicity #programming

An idiom that I learned in the Go community is to align the happy path. An example in C below:

happy path not aligned

int process_file(const char* filename) {
    FILE* f = fopen(filename, "r");
    if (f != NULL) {
        char buffer[100];
        if (fgets(buffer, sizeof(buffer), f) != NULL) {
            // process buffer
            fclose(f);
            return 0; // success
        } else {
            fclose(f);
            return -2; // error: unable to read
        }
    } else {
        return -1; // error: unable to open
    }
}

happy path aligned

int process_file(const char* filename) {
    FILE* f = fopen(filename, "r");
    if (f == NULL)
        return -1; // error: unable to open

    char buffer[100];
    if (fgets(buffer, sizeof(buffer), f) == NULL) {
        fclose(f);
        return -2; // error: unable to read
    }

    // process buffer

    fclose(f);
    return 0; // success
}

In the first example, it is more difficult to follow the logic due to nested if statements. In the second example, it is easy to scan down through the code aligned to the left and sequentially see what it is supposed to do.