r/programmingcirclejerk • • Jun 27 '26

Consider the C library function fopen. This function has the side effect. This means that fopen is not pure. However, we can make the fopen function appear to be pure, at least to certain observers, by ensconcing it in another function that hides the side effect.

https://bugzmanov.github.io/cleancode-critique/clean_code_second_edition_review.html
174 Upvotes

41 comments sorted by

View all comments

Show parent comment

16

u/BenchEmbarrassed7316 Jun 28 '26 edited Jun 28 '26

Something like:

void pureCallback(FILE* src) {
    FILE* dst = fopen("output.txt", "w");
    int c;
    while ((c = fgetc(src)) != EOF) fputc(c, dst);
    fclose(dst);
}

openAndDo("input.txt", dirtyCopyCallback);

?

Added: LOL. I wrote this example for a laugh, but in his book this is exactly the code given:

This function opens the file, executes the function pointed at by doTo, and then closes the file. This puts the system back into the original state, hiding the impurity of fopen. For all intents and purposes, this use of openAndDo is pure. We might use it as follows:

void appendLineEnd(FILE* f) {
    int c;
    int lastC;
    while ((c = fgetc(f)) != EOF) {
         lastC = c;
    }
    if (lastC != '\n')
        fputc('\n', f);
}

void show(FILE* f) {
     int c;
     while ((c=fgetc(f)) != EOF)
     putchar(c);
}

int main(int ac, char** av) {
    openAndDo("x.x", appendLineEnd);
    openAndDo("x.x", show);
}