Content deleted Content added
m Task 70: Update syntaxhighlight tags - remove use of deprecated <source> tags |
|||
Line 15:
For example, in [[C file input/output]], files are represented by objects of the <code>FILE</code> type (confusingly called "[[file handle]]s": these are a language-level abstraction), which stores an (operating system) handle to the file (such as a [[file descriptor]]), together with auxiliary information like I/O mode (reading, writing) and position in the stream. These objects are created by calling <code>[[C file input/output#fopen|fopen]]</code> (in object-oriented terms, a [[factory method|factory]]), which acquires the resource and returns a pointer to it; the resource is released by calling <code>[[C file input/output#fclose|fclose]]</code> on a pointer to the <code>FILE</code> object<ref>{{man|bd|stdio.h|SUS}}</ref>. In code:
<
FILE *f = fopen(filename, mode);
// Do something with f.
fclose(f);
</syntaxhighlight>
Note that <code>fclose</code> is a function with a <code>FILE *</code> parameter. In object-oriented programming, this is instead an [[instance method]] on a file object, as in Python:
<
f = open(filename)
# Do something with f.
f.close()
</syntaxhighlight>
This is precisely the dispose pattern, and only differs in syntax and code structure{{efn|In [[class-based programming]], methods are defined in a class, using an implicit <code>this</code> or <code>self</code> parameter, rather than as functions taking an explicit parameter.}} from traditional file opening and closing. Other resources can be managed in exactly the same way: being acquired in a constructor or factory, and released by an explicit <code>close</code> or <code>dispose</code> method.
Line 48:
For example:
<
def func(filename):
f = open(filename)
Line 55:
f.close()
return y
</syntaxhighlight>
If the function returns at the first return, the file is never closed and the resource is leaked.
<
def func(filename):
f = open(filename)
g(f) # Do something with f that may raise an exception.
f.close()
</syntaxhighlight>
If the intervening code raises an exception, the function exits early and the file is never closed, so the resource is leaked.
Both of these can be handled by a <code>try...finally</code> construct, which ensures that the finally clause is always executed on exit:
<
def func(filename):
try:
Line 74:
finally:
f.close()
</syntaxhighlight>
More generically:
<
Resource resource = getResource();
try {
Line 86:
resource.dispose();
}
</syntaxhighlight>
The <code>try...finally</code> construct is necessary for proper [[exception safety]], since the <code>finally</code> block enables execution of cleanup logic regardless of if an exception is thrown or not in the <code>try</code> block.
Line 97:
The [[C Sharp (programming language)|C#]] language features the <code>using</code> statement <ref>Microsoft MSDN: [http://msdn.microsoft.com/en-us/library/yh598w02.aspx using Statement (C# Reference)]</ref> that automatically calls the <code>Dispose</code> method on an object that implements the <code>IDisposable</code> [[interface (computer science)|interface]]:
<
using (Resource resource = GetResource())
{
Line 103:
...
}
</syntaxhighlight>
which is equal to:
<
Resource resource = GetResource()
try
Line 118:
((IDisposable)resource).Dispose();
}
</syntaxhighlight>
Similarly, the [[Python (programming language)|Python]] language has a <code>with</code> statement that can be used to similar effect with a ''context manager'' object. The ''context manager protocol'' requires implementing <code>__enter__</code> and <code>__exit__</code> methods which get automatically called by the <code>with</code> statement construct, to prevent duplication of code that would otherwise occur with the <code>try</code>/<code>finally</code> pattern.<ref>{{cite web |author=[[Guido van Rossum]], Nick Coghlan |date={{date|2011-06-13}} |title=PEP 343: The "with" Statement |publisher=Python Software Foundation |url=http://legacy.python.org/dev/peps/pep-0343/ }}</ref>
<
with resource_context_manager() as resource:
# Perform actions with the resource.
Line 127:
# Perform other actions where the resource is guaranteed to be deallocated.
...
</syntaxhighlight>
The [[Java (programming language)|Java]] language introduced a new syntax called <code>try</code>-with-resources in Java version 7.<ref>Oracle Java tutorial: [http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html The try-with-resources Statement]</ref> It can be used on objects that implement the AutoCloseable interface (that defines method close()):
<
try (OutputStream x = new OutputStream(...)) {
// Do something with x
Line 138:
// The resource x is automatically closed
} // try
</syntaxhighlight>
== Problems ==
|