链接设置器:有缺点吗?

发布于 2024-10-15 06:19:14 字数 453 浏览 7 评论 0原文

我已经开始在我的设置器中使用一种从 jQuery 中采用的技术,称为链接。示例:

class Foo {
  private int bar;
  private int baz;

  public int getBar() { return this.bar; }
  public int getBaz() { return this.baz; }

  public Foo setBar(int bar) {
    this.bar = bar;
    return this;
  }

  public Foo setBaz(int baz) {
    this.baz = baz;
    return this;
  }
}

我更喜欢这种方式,因为它可以非常轻松地设置多个属性。

有缺点吗?我曾就此询问过几位 Java 程序员,但他们只能说这“不好”,但他们无法给我一个正确的解释。

I have started using a technique, adopted from jQuery, called chaining in my setters. Example:

class Foo {
  private int bar;
  private int baz;

  public int getBar() { return this.bar; }
  public int getBaz() { return this.baz; }

  public Foo setBar(int bar) {
    this.bar = bar;
    return this;
  }

  public Foo setBaz(int baz) {
    this.baz = baz;
    return this;
  }
}

I prefer this way, because it makes easy to set multiple properties very easily.

Is there a drawback? I have asked several Java programmers about this, but all they could say is that it is "not nice", but they couldn't give me a proper explanation why.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终难愈 2024-10-22 06:19:14

我认为您遇到了一个缺点:在某些编程语言的文化中,这是不寻常且非常规的。有些文化比其他文化对不寻常和非常规的反应更好。我同意它有其优点,但 Java setter 通常不是这样编码的。

I think you've encountered one drawback: in the culture of some programming languages, it is unusual and unconventional. And some cultures react better than others to unusual and unconventional. I agree that it has merit, but Java setters are just not usually coded that way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文