Content deleted Content added
m v1.38 - WP:WCW project (Code tag without correct end) |
|||
Line 55:
== Approaches ==
=== Unwind protection ===
The most common approach to resource management across languages is to use unwind protection, which is called when execution exits a scope – by execution running off the end of the block, returning from within the block, or an exception being throw. This works for stack-managed resources, and is implemented in many languages, including C#, Common Lisp, Java, Python, Ruby, and Scheme. The main problems with this approach is that the release code (most commonly in a <code>finally</code> clause) may be very distant from the acquisition code (it lacks ''adjacency''), and that the acquisition and release code must always be paired by the caller (it lacks ''encapsulation''). These can be remedied either functionally, by using closures/callbacks/coroutines (Common Lisp, Ruby, Scheme), or by using an object that handles both the acquisition and release, and adding a language construct to call these methods when control enters and exits a scope (C# <code>using</code>, Java <code>try</code>-with-resources, Python <code>with</code>); see below.
Line 77 ⟶ 78:
==== RAII ====
{{main article|Resource Acquisition Is Initialization}}
A natural approach is to make holding a resource be a [[class invariant]]: resources are acquired during object creation (specifically initialization), and released during object destruction (specifically finalization). This is known as [[Resource Acquisition Is Initialization]] (RAII), and ties resource management to [[object lifetime]], ensuring that live objects have all necessary resources. Other approaches do not make holding the resource a class invariant, and thus objects may not have necessary resources (because they've not been acquired yet, have already been released, or are being managed externally), resulting in errors such as trying to read from a closed file. This approach ties resource management to memory management (specifically object management), so if there are no memory leaks (no object leaks), there are no [[resource leak]]s. RAII works naturally for heap-managed resources, not only stack-managed resources, and is composable: resources held by objects in arbitrarily complicated relationships (a complicated [[object graph]]) are released transparently simply by object destruction (so long as this is done properly!).
Line 111 ⟶ 112:
</source>
By contrast, in Python, a [https://docs.python.org/2/library/csv.html#csv.reader csv.reader] does not own the <code>file</code> that it is reading, so there is no need (and it is not possible) to close the reader, and instead the <code>file</code> itself must be closed.<ref>[
<source lang="Python">
|