开发者

variable scope - how to decide

If I have class "A" that I want to declare 开发者_C百科an instance of, that I use frequently within class "B", what is the deciding factor on whether I should declare it outside of class "B" or within each method I use it in within class "B"?

public Class A
{
}

A declareClassA = new A();
public Class B 
{
}

or

public Class B 
{
  public void MethodA()
  {
      A declareClassA = new A();
      ...
  }
  public void MethodB()
  {
      A declareClassA = new A();
      ...
  }

}


Firstly, you can't (AFAIK) declare a variable outside a class.

For your first example, I think you mean:

public Class B 
{
   A declareClassA = new A();
   // methods here..
}

As for your question - do you need to use the same instance in both MethodA and MethodB, or not?

If you do, use the above code. If not, use a separate declaration in each method.


Best practices would be to scope a variable at its lowest necessary level. If you need to share a variable between methods, then it's scope should be outside of that. If the methods operate independently and can survive with a scope at that level, then you should declare/instantiate your new variable there.

Always keep your scope as minimal as possible without reducing functionality.


Do you want to use a new instance for each method? If so, declare and instantiate inside the method.

If not, declare it inside the class.

public Class B
{
    A myA = new A();
}


In your first method, seems like A could either be a singleton pattern or a static class. This really depends on the data inside A, and if it should be reused and how many instances should exist.


It depends on if you need persistent storage of that object. If you need to reference the same instance declare it as a class level variable otherwise declare it in the methods so that you can decrease coupling between your methods.

Additionally if those functions are always using Class A think about whether they should belong to Class A instead of Class B

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜