Java中的方法链 [英] Method Chaining in Java

查看:21
本文介绍了Java中的方法链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在之前在这里回答一些问题以及我最近所做的一些工作时,我一直想知道为什么 Java 不支持其内置类的方法链.

While answering a few questions on here earlier and from some work I have been doing lately I have been wondering why Java does not support method chaining on its built in classes.

例如,如果我要创建一个 Car 类,我可以通过重新输入 this 而不是 void 使其可链接,如下所示:

If I were to create a Car class for example, I could make it chainable by reutrning this instead of void as follows:

public class Car {
    private String make;        

    public Car setMake(String make) {
        this.make = make;
        return this;
    }   
}

内置库不倾向于以这种方式做事有什么特别的原因吗?方法链有缺点吗?

Is there any particular reason why the built in libraries don't tend to do things this way? Is there a downside to method chaining?

我可能忽略了一些可以解释缺少方法链的东西,但是默认情况下返回 void 的任何 setter 方法都应该返回对 this 的引用(至少在我看来应该如此).这将使以下情况更加清晰.

I may have overlooked something which would explain the lack of method chaining however any setter method that returns void by default should return a reference to this (at least in my eyes it should). This would make situations like the following much cleaner.

container.add((new JLabel("label text")).setMaximumSize(new Dimension(100,200)));

而不是长篇大论:注意:如果您愿意,它不会阻止您以这种方式编码.

JLabel label = new JLabel("label text");
label.setMaximumSize(new Dimension(100,200));
container.add(label);

我很想知道这个决定背后的原因,如果我不得不猜测它会产生与此相关的开销,所以应该只在需要时使用.

I would be very interested to hear the reasons behind this decision, If I had to guess it would be that there is an overhead associated with this and so should only be used when needed.

推荐答案

嗯.需要在两个方向上进行可读性论证——试图将太多内容放在一行中.

Eh. There's readability arguments to be made in both directions -- there's such a thing as trying to put too much into a single line.

但老实说,我怀疑这是出于历史原因:普遍的链接"行为并没有真正变得流行或广为人知,例如Swing 正在开发中.您可能会争辩说它应该在稍后添加,但类似的事情往往会造成二进制不兼容以及 Sun/Oracle 历来极为谨慎的其他问题.

But honestly, I suspect here it's for historical reasons: pervasive "chaining" behavior hadn't really become popular or well-known when e.g. Swing was being developed. You could argue that it should've been added in later on, but things like that tend to create binary incompatibilities and other issues that Sun/Oracle have historically been extremely cautious about.

最近的 JDK 库——参见例如ByteBuffer 对于专业,众所周知的例子——已经在有意义的地方提供了链接行为等.

More recent JDK libraries -- see e.g. ByteBuffer for a major, well-known example -- have provided chaining behavior and the like, where it makes sense.

这篇关于Java中的方法链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆