Live data from Hacker News

The Setup-Cleanup Problem

blog.gnoack.org

11–20 of 27 posts

Re: The Setup-Cleanup Problem

#11
post #6

When mentioning C# (not sure about any other language), I would have mentioned the using statement and IDesposable objects. This way each object's needed cleanup is encapsulated in each objects dispose method(s). Granted using compiles down to a try-catch-finally with the Dispose method called in the finally, but there is an elegance to it. https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...

Looks similar to Python's "with" statements in the first form, and RAII-ish in the second form.

Re: The Setup-Cleanup Problem

#14

The C# version is lacking the using pattern. https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...

Similar for Java's try-with-resources.

Also, I use a style in Java with higher-order functions (aka Callables/Runnables) that's like the pattern ascribed to Ruby, for situations not covered by AutoCloseable.

Re: The Setup-Cleanup Problem

#17
There's also linear types, where you only give things capable of closing a resource a type that consumes a linear type.

There's also monadic resources, which you can view as a combination of RAII and what the author calls higher order functions.

Finally there's also monadic regions (as distinct from resources), which take advantage of higher rank types.

Re: The Setup-Cleanup Problem

#19

What I find an interesting design choice about Go’s approach (using ‘defer’) is that they are executed at the end of the function — not the end of the current block: https://play.golang.org/p/q5n0P-mKrmS This means that if you were to alter a function by placing parts of its body inside a loop, you may accidentally introduce O(n) buildup of deferred statements. This means that you could also be piling up resources as…

You just explained why it's done this way. Because 'defer' is not scoped by block you can now use your standard constructs with blocks — if, for-loops, etc. — to initiate the defers. If your function opens a N files based on some parameter N, it can still use a loop and defer each's close dynamically.

Sure there's ways to work around it like putting another loop in a single defer but it's not completely braindead this way.

It's much more annoying to need to add syntax to "expand" the scope of a deferred beyond a codeblock when you need it than to just wrap some code in a function when you need it.

Post reply on HN