Re: Closing/Despose of JFrame
Andreas Leitgeb wrote:
Lew wrote:
Dying old:
public class Example
{
Collection<Foo> foos = getSomeFoos();
Bar bar; // the elephant in the room
public void run()
{
for (Foo foo : foos)
{
bar = foo.obtainBar();
// do whatever with 'bar'
// 'bar' does not fall out of scope
// The last reference from the loop lasts as
// long as this instance does, and could
// tenure the 'Bar' it points to
}
}
}
[...]
There are some notable urban
legends out there, such as the advice to set all references
to 'null' when finished with them. There are specific times
to do so, such as when a collection such as a 'Stack' is
holding hidden references ("packratting", or the Java version
of a memory leak). [...]
...or right after the loop in above "dying old"-Example, if for
whatever reason there really was some need to have "bar" as a
field, instead of as a local var within the loop.
True, but dangerous. If you are nulling out the reference after the loop
anyway, there is a low probability that a member variable is the right
scope. I can think of reasons why one might do that, but they all seem
like tangled and ill-advised code to me.
The scope and lifetime of the variable should match the scope and
lifetime of the need for its reference. The scenario you describe seems
to violate that. I say "seems to" because sure, there very well could be
cases for it. But they all would (or should) fit into the "scope and lifetime
should match" rule. So if you do see a situation where the scope is the
instance, and/or the lifetime matches that of the enclosing instance, then
a member variable is correct even should Lew feel that your code is tangled
and ill advised.
OTOH, you shouldn't be too quick to dismiss my insight into the matter.
--
Lew