In some code I'm reviewing, I'm seeing stuff that's the moral equivalent of the following:

public class Foo
{
    private Bar bar;

    public MethodA()
    {
        bar = new Bar();
        bar.A();
        bar = null;
    }

    public MethodB()
    {
        bar = new Bar();
        bar.B();
        bar = null;
    }
}


The field bar here is logically a local variable, as its value is never intended to persist across method calls. However, since many of the methods in Foo need an object of type Bar, the original code author has just made a field of type Bar.


This is obviously bad, right?
Is there a name for this antipattern?



  This is obviously bad, right?


Yea.  


It makes the methods non-reentrant, which is a problem if they are called on the same instance recursively or in a multi-threaded context.
It means that state from one call leaks to another call (if you forget to reinitialize).
It makes the code hard to understand because you have to check for the above to be sure what the code is actually doing.  (Contrast with using local variables.)
It makes each Foo instance bigger than it needs to be.  (And imagine doing this for N variables ...)



  Is there a name for this antipattern?


IMO, this is does not deserve to be called an antipattern.  It is just a bad coding habit / a misuse of Java constructs / crap code.  It is the sort of thing that you might see in an undergraduate's code when the student has been skipping lectures and/or has no aptitude for programming.  If you see it in production code, it is a sign that you need to do a lot more code reviews ...



For the record, the correct way to write this is:

public class Foo
{
    public methodA()
    {
        Bar bar = new Bar();  // Use a >>local<< variable!!
        bar.a();
    }

    // Or more concisely (in this case) ...
    public methodB()
    {
        new Bar().b();
    }
}


Notice that I've also fixed the method and variable names to conform to the accepted style rules for Java identifiers.
