Search code examples
javaoopclass-design

Use class level field or method variable?


I have a object I initialize in a method like :

public void something()
{
    Dummy obj = Factory.getDummy();
    method2(obj);
}

now, this Dummy object is to be used by many methods

public void method2(Dummy obj)
{
    method2(obj);
    ....
}

Now, my doubt is how this scenario must be handled, the way I am doing it. Or, make obj in something a class level field and initialize in something.

like:

private Dummy obj;

public void something()
{
    obj = Factory.getDummy();
    method2(obj);
}

And use in subsequent methods. (Removing parameters from the methods).

So, what is the best way of handling this situation? and Why?


Solution

    1. If it's strongly associated with the class, make it static.
    2. If it's strongly associated with an instance, make it a non--static member.
    3. If it's strongly associated with a method invocation, or the current thread, or you can't decide about (1) or (2), make it method-local.