Hacker News new | past | comments | ask | show | jobs | submit login

> you should write your code such that a destructor closing a resource is considered a programming error.

Not disposing your resources properly is an error. Your language should make it as easy as possible to make this impossible (or at least highly unnatural).

> The only exceptions are C++ RAII wrapper classes, which are designed to have magical destructors.

They are the (only?) correct form of resource management: automatically clean it up when you're done with it.

> C#'s using(), Python's with statement, Haskell's with* functions -- they're all designed to solve the problem that a generic garbage collector doesn't and shouldn't, which is "I need precise control over the lifetime of this resource allocation". Java doesn't have such a mechanism, but then, Java doesn't have much of anything for a supposedly high-level language.

using() is the same as try{}finally{}, which Java does have. The problem with these is that you can forget them.

The problem with garbage collection is that it seems to always come with the baked-in assumption that memory is the only resource that really matters, so handling of other resources is a bolted-on afterthought. GC impeded correctness, not because of anything fundamental, but because it is seen to substitute for proper resource management.




The "With" style construct is the correct way to handle this. Embedding resources like file-descriptors in objects is a Bad Idea.

Python has added the "with" construct so it can move away from ref-counted implementations, because the amortized time for refcounting is slower, and even if you don't care about that, there is still the circular reference problem.

[edit] I should make it clear I think tying an FDs lifetime to that of an object is a Bad Idea; I'm not suggesting a blanket ban on ever having a FD stored in an object.


Correct resource management is to clean it up when everyone is done with it. As one book put it, liveness of an object is a global, not local, property. If a reference to an object escapes the function which created it, it rapidly becomes infeasible to statically prove it is ever safe to destroy the object, and the penalty for almost getting it right is undefined behavior. That's why memory deserves to be handled specially. Leaving files and connections unclosed can cause errors, but they can't make correct code go unpredictably insane.


using isn't quite the same as try/finally. using is a construct explicitly for freeing resources. With a try/finally construct it's up to the user to fill in the finally block correctly.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: