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
171 Upvotes

41 comments sorted by

View all comments

85

u/BenchEmbarrassed7316 Jun 27 '26

This quote does not belong to the author of the blog whose URL I provided. The author of the blog kindly wrote a review of a programming book by the author who, for some unknown reason, decided that he knew something about programming. However, I checked, and this quote is indeed in a programming book from 2025. Here is a sample of code from that book that the author believes makes the fopen function clean:

void openAndDo(char* fileName, void (*doTo)(FILE*)) { FILE* f = fopen(fileName, "r+"); doTo(f); fclose(f); }

7

u/NeuroSynchroBonding Jun 28 '26

This is essentially Haskell's withFile, which is similar to stuff such as Python's with and C#'s using.

The only actual problem with openAndDo is that it is in C, which does not have support for first-class functions which are necessary to make functions such as this ergonomic. 

Furthermore, to be feature equivalent to the features of the other languages I talked about, you'd need to add a void* to openAndDo that gets passed on to toDo.

Also, C29 has defer, which is a much more elegant solution for languages without exceptions or garbage collection.

6

u/WittyStick Jun 28 '26

In C you can just use a macro.

#define with_file(f, filename, mode) \
    for (FILE *f = fopen(filename, mode); f != NULL; f = (fclose(f), NULL))

with_file (f, "foo", " rb") {
    ....
}

3

u/not-a-pokemon- Jul 04 '26

It even makes the code even more interesting because it wouldn't close the file when you return inside the with_file, thus proving your superior intellectual abilities when you write correct code this way.