Reputation: 8653
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?
Upvotes: 0
Views: 1895
Reputation: 4691
If some property
is associated to class, then that property should be static. That is, if some property is same among all the instances of classes, then that property
should be the static in class.
If some property
is differing for every instance of class, then that property
should be member variable ( non-static variable ) of the class.
If some property needs on temporary basis for some operation then make that property as local variable of the operation ( method
).
Upvotes: 1
Reputation: 3950
You should declare obj
as a class-level
field and then instantiate it in the constructor.
But more points to clear:
something()
and the methods like method2()
that expect the Dummy
object, are located inside the same class, then you even don't need to pass the object. In that case, the above statement is upheldUpvotes: 2
Reputation: 5187
Generally you should minimize the scope of one variable. But, if the variable is very used within your class
, you should declare it as class-level, as instance variable.
Upvotes: 2
Reputation: 310884
Upvotes: 8