4 ms·
try/finally in Java / using in C# are designed for that scenario.
by harrytuttle 13y ago
try/finally in Java / using in C# are designed for that scenario.
- pyrtsa 13y agoBut you'll need to document it very visibly that "Thou shalt call resource.close() whatever happened." C++ makes it possible for the library writer to take care of freeing the resources automatically.
- moron4hire 13y agoA class implementing IDisposable is that documentation. You shouldn't need more documentation than the fact that IDisposable is there.
- jasomill 13y agoAn annoying fly in this ointment is cases where objects assume the responsibility for calling Dispose on caller-provided disposable objects. While it should always be okay to "double-dispose", this is only a guideline, and can't be enforced by the language, so, to maximize future compatibility with classes outside your control, you should probably defensively avoid calling Dispose on an object that will have already been disposed by other means.
- Sharlin 13y agoAnd try/finally assigns the cleanup responsibility to the caller, not the callee, which just adds boilerplate and mental burden. C++ does not need a finally block due to RAII. The using block (and "try-with-resource" in Java 7) is a poor man's RAII emulation. Anyway, what if you need to share non-memory resources? Suddenly you cannot depend on the garbage collector, you cannot use try/finally, you cannot use using or try-with-resource - you need to handle the situation just like in C++, except you're given fewer tools to do it - and a poorer understanding of the situation if you've learned that you don't need to do manual resource management due to the garbage collector.
- pkolaczk 13y agoTrue, but 90% of resources is memory. Java makes 90% of resources much easier to handle and 10% only little harder (like always use the try-catch-finally or try-with-resources).
- detrino 13y agoThey are poor solutions compared to RAII: leaky abstractions which are non-composable and error prone. Unfortunately, something like C# using is probably the best you can do in a language without clear ownership semantics like C++.