gpt4 book ai didi

parameters - 将类实例变量作为参数传递

转载 作者:行者123 更新时间:2023-12-03 18:40:59 25 4
gpt4 key购买 nike

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

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

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();
}

}

在哪里 processAttribute()使用 attribute1内在值(value)。但是,许多文档说我们应该尝试限制全局变量的使用。编写这样的东西会是一种更可重用且设计良好的方式吗?
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);
}

}

汇集你的想法。

最佳答案

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

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

  • 另一方面,它是一个私有(private)方法,只要您履行该类的契约(Contract),您就可以随意实现它。

    关于parameters - 将类实例变量作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17313904/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com