4

这是我一直在考虑的一个设计问题,但没有找到令人信服的信息。

假设我的类中有一些实例变量,现在想象我想使用该值为我的类编写一些私有功能。写这样的东西不是问题:

public class Example{

    private String attribute1;

    public void setAttribute1(String att){
        this.attribute1 = att;
    }

    private void processAttribute(){
        //do something with attribute1
    }

    public void executeExample(){
        processAttribute();
    }

}

Where在内部processAttribute()使用该attribute1值。但是,许多文档说我们应该尝试限制全局变量的使用。编写这样的东西会是一种更可重用且设计良好的方式吗?

public class Example{

    private String attribute1;

    public void setAttribute1(String att){
        this.attribute1 = att;
    }

    private void processAttribute(String att){
        //do something with attribute1
    }

    public void executeExample(){
        processAttribute(this.attribute1);
    }

}

汇集你的想法。

4

3 回答 3

2

许多反对全局状态的论点也适用于这里:

  • 如果在 processAttribute 方法之外的其他地方使用该属性,则很难推断程序的正确性
  • 使用全局状态的代码更难并行化:如果在处理属性时修改了属性会发生什么?
  • 更多:http ://c2.com/cgi/wiki?GlobalVariablesAreBad

另一方面,它是一个私有方法,只要您履行该类的合同,您就可以随意实现它。

于 2013-06-26T07:33:05.533 回答
1

However, many doc says we should try to limit the use of global variables.

I think you have misunderstood the concept. Usually global variables are those which are declared as public static so that it can be accessed directly from any other part of the application.

So in your both example the variable attribute1 is not a global variable. It is only a member variable of the class.

Hence I don't see much difference between the two different codes.

If the design is fixed then I think it is better to use the first one to make it more readable. And if in future there is other chances to send other variables as parameter rather than the member variable then you can use the second implementation. (Although I think it totally depends on coder's personal choice)

于 2013-06-26T07:29:37.523 回答
1

首先,attribute1 不是全局属性,它只是一个类变量。使用此操作,类变量将在所有类方法中可用,因此您无需将它们作为方法参数传递。

由于这里不需要传递方法参数,因此实现它似乎不合逻辑。顺便说一句,这是我个人的看法,其他人可能有不同的想法。

于 2013-06-26T07:24:40.150 回答