質問

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?

役に立ちましたか?

解決

  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.

他のヒント

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.

You should declare obj as a class-level field and then instantiate it in the constructor.

But more points to clear:

  • if 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 upheld
  • if not located in the same class, then pass the object by invoking the methods through their instances or classes based on what type they're.

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 ).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top