使用getter和setter(只获取和设置)而不是简单地为这些变量使用公共字段有什么好处?

如果getter和setter所做的不仅仅是简单的get/set,我可以很快地解决这个问题,但我不是100%清楚如何做到:

public String foo;

比:

private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }

而前者需要的样板代码要少得多。


当前回答

DataStructure和Object之间存在差异。

数据结构应该暴露其内部而不是行为。

一个物体不应该暴露其内部,但它应该暴露其行为,这也被称为德米特定律

大多数DTO被认为是一种数据结构,而不是对象。他们应该只公开自己的数据,而不是行为。在数据结构中设置Setter/Getter将暴露行为,而不是其中的数据。这进一步增加了违反德梅特定律的可能性。

鲍勃叔叔在他的《干净的代码》一书中解释了得墨忒耳定律。

有一种著名的启发式方法叫做得墨忒耳定律,它说:模块不应该知道它的对象的内部结构操纵。正如我们在上一节中看到的,对象隐藏其数据并暴露操作。这意味着对象不应公开其通过访问器的内部结构,因为这样做是为了暴露,而不是隐藏其内部结构。更准确地说,德米特定律说C类的方法f应仅调用以下方法:Cf创建的对象作为参数传递给f的对象保存在C的实例变量中的对象该方法不应在任何允许的函数返回的对象上调用方法。换句话说,与朋友交谈,而不是与陌生人交谈。

因此,根据这一点,LoD违规的例子是:

final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();

在这里,函数应该调用它的直接朋友的方法,这里是ctxt,它不应该调用它直接朋友的朋友的方法。但该规则不适用于数据结构。所以在这里,如果ctxt、option、scratchDir是数据结构,那么为什么要用一些行为包装它们的内部数据,并违反LoD。

相反,我们可以这样做。

final String outputDir = ctxt.options.scratchDir.absolutePath;

这满足了我们的需求,甚至没有违反LoD。

灵感来源于Robert C.Martin(Bob叔叔)的“清洁代码”

其他回答

如果您想要一个只读变量,但不想让客户端改变访问它的方式,请尝试使用这个模板类:

template<typename MemberOfWhichClass, typename primative>                                       
class ReadOnly {
    friend MemberOfWhichClass;
public:
    template<typename number> inline bool   operator==(const number& y) const { return x == y; } 
    template<typename number> inline number operator+ (const number& y) const { return x + y; } 
    template<typename number> inline number operator- (const number& y) const { return x - y; } 
    template<typename number> inline number operator* (const number& y) const { return x * y; }  
    template<typename number> inline number operator/ (const number& y) const { return x / y; } 
    template<typename number> inline number operator<<(const number& y) const { return x << y; }
    template<typename number> inline number operator^(const number& y) const  { return x^y; }
    template<typename number> inline number operator~() const                 { return ~x; }
    template<typename number> inline operator number() const                  { return x; }
protected:
    template<typename number> inline number operator= (const number& y) { return x = y; }       
    template<typename number> inline number operator+=(const number& y) { return x += y; }      
    template<typename number> inline number operator-=(const number& y) { return x -= y; }      
    template<typename number> inline number operator*=(const number& y) { return x *= y; }      
    template<typename number> inline number operator/=(const number& y) { return x /= y; }      
    primative x;                                                                                
};      

示例用途:

class Foo {
public:
    ReadOnly<Foo, int> cantChangeMe;
};

记住,您还需要添加按位和一元运算符!这只是为了让你开始

编辑:我回答这个问题是因为有很多学习编程的人都在问这个问题,大多数答案在技术上都很好,但如果你是新手,就不那么容易理解了。我们都是新手,所以我想我会尝试一个更适合新手的答案。

两个主要的是多态性和验证。即使它只是一个愚蠢的数据结构。

假设我们有一个简单的类:

public class Bottle {
  public int amountOfWaterMl;
  public int capacityMl;
}

这是一个非常简单的类,它包含有多少液体,容量是多少(毫升)。

当我这样做时会发生什么:

Bottle bot = new Bottle();
bot.amountOfWaterMl = 1500;
bot.capacityMl = 1000;

嗯,你不会指望这会奏效,对吧?你想进行某种理智检查。更糟糕的是,如果我从未指定最大容量呢?哦,亲爱的,我们有问题。

但也有另一个问题。如果瓶子只是一种容器呢?如果我们有几个容器,所有容器都有容量和液体量,会怎么样?如果我们能做一个接口,我们就可以让程序的其他部分接受这个接口,而瓶子、偷工减料和各种各样的东西就可以互换使用了。那不是更好吗?由于接口需要方法,这也是一件好事。

我们最终会得到这样的结果:

public interface LiquidContainer {
  public int getAmountMl();
  public void setAmountMl(int amountMl);
  public int getCapacityMl();
}

太棒了现在我们把瓶子换成这个:

public class Bottle extends LiquidContainer {
  private int capacityMl;
  private int amountFilledMl;

  public Bottle(int capacityMl, int amountFilledMl) {
    this.capacityMl = capacityMl;
    this.amountFilledMl = amountFilledMl;
    checkNotOverFlow();
  }

  public int getAmountMl() {
    return amountFilledMl;
  }

  public void setAmountMl(int amountMl) {
     this.amountFilled = amountMl;
     checkNotOverFlow();
  }
  public int getCapacityMl() {
    return capacityMl;
  }

  private void checkNotOverFlow() {
    if(amountOfWaterMl > capacityMl) {
      throw new BottleOverflowException();
    }
}

我将把BottleOverflowException的定义作为练习留给读者。

现在请注意这是多么的强大。我们现在可以通过接受LiquidContainer而不是Bottle来处理代码中的任何类型的容器。这些瓶子是如何处理这种东西的呢。您可以有在磁盘发生变化时将其状态写入磁盘的瓶子,也可以有保存在SQL数据库或GNU知道其他内容的瓶子。

所有这些都可以有不同的方法来处理各种各样的百日咳。瓶子只是检查,如果它溢出,就会抛出RuntimeException。但这可能是错误的做法。(关于错误处理有一个很有用的讨论,但我有意保持非常简单。评论中的人可能会指出这种简单方法的缺点。;)

是的,我们似乎从一个非常简单的想法迅速得到更好的答案。

请注意,您不能更改瓶子的容量。它现在被镶嵌在石头上。您可以通过将int声明为final来实现这一点。但如果这是一个列表,你可以清空它,添加新的东西,等等。你不能限制接触内脏的权限。

还有第三件事不是每个人都解决过:getter和setter使用方法调用。这意味着它们看起来像其他地方的正常方法。DTO和其他东西没有奇怪的特定语法,而是到处都有相同的语法。

另一个用途(在支持财产的语言中)是setter和getter可以暗示操作是非平凡的。通常,您希望避免在属性中执行任何计算成本高昂的操作。

我想发布一个我刚刚完成的真实世界示例:

背景-我使用休眠工具为我的数据库生成映射,这是一个我在开发时正在更改的数据库。我更改数据库模式,推送更改,然后运行hibernate工具来生成java代码。在我想向这些映射实体添加方法之前,一切都很好。如果我修改了生成的文件,则每次对数据库进行更改时都会覆盖这些文件。所以我这样扩展生成的类:

package com.foo.entities.custom
class User extends com.foo.entities.User{
     public Integer getSomething(){
         return super.getSomething();             
     }
     public void setSomething(Integer something){
         something+=1;
         super.setSomething(something); 
     }
}

我上面所做的是用我的新功能(something+1)覆盖超类上的现有方法,而不需要接触基类。如果你在一年前写了一个类,并且想在不改变基类的情况下升级到第2版(测试噩梦),也是同样的情况。希望这会有所帮助。

因为从现在起2周(月、年),当您意识到setter需要做的不仅仅是设置值时,您还将意识到该属性已直接用于238个其他类:-)