3 ms·
the "with-" pattern (originally from lisp, i believe, but ruby did a lot to bring it to the masses), where something like a filehandle manages its own lifecycle
by zem 12y ago
the "with-" pattern (originally from lisp, i believe, but ruby did a lot to bring it to the masses), where something like a filehandle manages its own lifecycle, and calls your closure in between. so rather than the C-like
let f = open-file-for-writing(filename);
for line in array {
write-line-to-file(f, line);
}
close-file(f);
you can do
with-open-file-for-writing(filename) {|f|
for line in array {
write-line-to-file(f, line);
}
}
where the definition of with-open-file-for-writing() would look like
def with-open-file-for-writing(filename, closure) {
let f = open-file-for-writing(filename);
call-closure(closure, f);
close-file(f);
}
the benefit of having this be a closure rather than just a function pointer can be seen in the write array to file example above, where the "array" variable is in the scope of the calling function, but when with-open-file-for-writing calls your closure it can make full use of its own local variables.
- dllthomas 12y agoOf course, you can build your own closure: void do_stuff_with_file(struct relevant_data *, FILE *); ... { struct relevant_data data = { ... } with_open_file_for_writing(do_stuff_with_file, data, filename); } IMO, the biggest downside there being how far it typically pushes the definition of that function from the call site. Small functions - a good practice anyway - ameliorates that a bit.
- zem 12y agoyou can, but it's sufficiently clunky that it simply doesn't feel like a natural thing to do in the language. good language design is a lot more about the things it makes easy and natural than the things it makes possible.
- dllthomas 12y ago"you can, but it's sufficiently clunky that it simply doesn't feel like a natural thing to do in the language." It does to me, but I've done enough functional programming that I easily reach for concepts from that space. "good language design is a lot more about the things it makes easy and natural than the things it makes possible." Of course. I don't know where you got the idea I was saying closures aren't a good thing to have language support for. I said precisely the opposite.
- edwintorok 12y agoYou can also wrap the call-closure with an exception handler to make sure that 'f' is always closed when you leave with-open-file-for-writing.
- zem 12y agoright. and the beautiful thing is that once you realise that you only need to do it once, not everywhere you open, write to, and close a file.