Java 中是否存在用于满足接口而存在的空方法的习惯用法?

发布于 2024-07-21 05:23:49 字数 1377 浏览 3 评论 0原文

假设我有一个类 Foo 实现了一个接口,例如 MouseListenerMouseListener 接口由五个方法组成,但我只想重写其中之一 (mouseClicked())。 是否有一种标准的、惯用的方式来格式化其他方法?

我的倾向是写下以下内容:

@Override
public void mouseClicked(MouseEvent e) {
    // (...) <-- actual code here
}

@Override
public void mouseEntered(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

@Override
public void mouseExited(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

@Override
public void mousePressed(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

@Override
public void mouseReleased(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

我喜欢明确指出方法是故意留空的,而不是意外留空,但我并不热衷于放弃所有垂直空间。 我还看到了以下格式:

public void mouseClicked(MouseEvent e) {
    // (...) <-- actual code here
}

public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

我通常对此表示同意,并且我理解作者的意图,但是当 (推荐)添加了@Override注释。

我不是一个特别有经验的 Java 程序员,所以我想我会问是否有一个约定。 想法?

Let's say I have a class Foo implementing an interface such as MouseListener. The MouseListener interface consists of five methods but I only wish to override one of them (mouseClicked()). Is there a standard, idiomatic way of formatting the other methods?

My inclination was to write the following:

@Override
public void mouseClicked(MouseEvent e) {
    // (...) <-- actual code here
}

@Override
public void mouseEntered(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

@Override
public void mouseExited(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

@Override
public void mousePressed(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

@Override
public void mouseReleased(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

I'm a fan of making it explicit that methods are intentionally blank rather than accidentally left so, but I'm not crazy about all the vertical space given up for basically nothing. I've also seen the following format:

public void mouseClicked(MouseEvent e) {
    // (...) <-- actual code here
}

public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

I'm generally OK with this and I understand the author's intent, but it gets really ugly when the (recommended) @Override annotations are added.

I'm not a particularly experienced Java coder so I figured I'd ask if there was a convention. Thoughts?

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

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

发布评论

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

评论(10

天暗了我发光 2024-07-28 05:23:49

在这种特殊情况下,您应该遵循 wilums2 的建议并扩展 MouseAdapter 而不是实现 MouseListener。 这些适配器类的目的是让您在仅实现接口的某些方法时不必提供空的实现。

更一般地说,简短的答案是“不”,对于如何记录空方法没有标准约定,尽管我通常使用类似的东西

@Override
void foo() {
  // No implementation necessary
}

In this particular case you should follow wilums2's advice and extend MouseAdapter instead of implementing MouseListener. The purpose of these adapter classes is so that you don't have to provide empty implementations when you're only implementing some of the methods of an interface.

More generally, the short answer is 'no', there is no standard convention for how to document empty methods, though I generally use something like

@Override
void foo() {
  // No implementation necessary
}
雨轻弹 2024-07-28 05:23:49

如果一行没有留下任何内容,我会按照您的方式进行操作。 也许可以在一大堆“实施俏皮话”之上添加一条评论。

I do it the same way you do, if theres nothing there leave at one line. Maybe put a comment on top of a large block of 'implementation one-liners'.

等风也等你 2024-07-28 05:23:49

使用鼠标适配器

Use MouseAdapter

断爱 2024-07-28 05:23:49

一般来说,您所说的是空对象模式的扩展。 您定义了一个空对象,并通过仅覆盖您关心的方法来扩展它。

作为自动执行此操作的方法的示例,在我的 JavaDude Bean Annotations (http://code .google.com/p/javadude/wiki/Annotations),您可以执行如下操作。 [注意:我不建议对 MouseListener 执行此操作,因为 MouseAdapter 已经存在,您可以将其子类化...以下内容对于您只想实现一些选择方法的其他大型接口很有用]

@Bean(nullObjectImplementations = @NullObject(type=MouseListener.class))
public class MyMouseHandler extends MyMouseHandlerGen {
    public void mouseClicked(MouseEvent e) {
        // your handling of a MouseClick
    }
}

然后您可以使用MyMouseHandler 来处理点击。=

注意:MouseAdapter 对于 JRE/JDK 中的类名来说是一个非常糟糕的选择。 它不是 GoF 适配器模式的实例;它是 GoF 适配器模式的一个实例。 它实际上是 MouseListener 的空对象实现。

顺便说一句:您可以将 @Override 与方法声明放在同一行 - 对于您的示例,您可以

@Override public void mousePressed(MouseEvent e) { /* not needed */ }
// et al

In general, what you're talking about is an extension of the Null Object Pattern. You're definining a Null Object and extending it by only overriding the methods you care about.

As an example of a way to automate this, in my JavaDude Bean Annotations (http://code.google.com/p/javadude/wiki/Annotations), you can do something like the following. [NOTE: I wouldn't recommend doing this for MouseListener, as the MouseAdapter already exists and you can just subclass it... The following is useful for other large interfaces where you only want to implement a few select methods]

@Bean(nullObjectImplementations = @NullObject(type=MouseListener.class))
public class MyMouseHandler extends MyMouseHandlerGen {
    public void mouseClicked(MouseEvent e) {
        // your handling of a MouseClick
    }
}

You can then use MyMouseHandler to handle the click.=

Note: MouseAdapter was a really bad choice for the name of the class in the JRE/JDK. It's not an instance of the GoF Adapter pattern; it's really a Null Object implementation of a MouseListener.

BTW: You can put @Override on the same line as the method declaration - for your example you can have

@Override public void mousePressed(MouseEvent e) { /* not needed */ }
// et al
余生再见 2024-07-28 05:23:49

做这件事有很多种方法。
Oracle java conventions p6.4(第11页)表示空方法应该看起来像

public void empty() {}

还有一个由 Steve Yohanan 于 2003 年编写的文档说

public void empty()
{
}

虽然我还没有找到“空方法作为接口存根”的任何约定。
因此,作为结论,没有标准化的方法可以做到这一点。
有些人喜欢留下评论,有些人喜欢将其写成单行,有些人则像其他空白正文的方法一样编写。

There are several ways to do this.
The Oracle java conventions p6.4 (page 11) says the empty methods should look like

public void empty() {}

There is also a document by Steve Yohanan written in 2003 ant it says

public void empty()
{
}

Though I haven't found any convention for "empty method as interface stub".
So as a conclusion, there is no standardized way of doing this.
Some prefer leaving a comment, some prefer making it single line, some write it as any other method with blank body.

少女情怀诗 2024-07-28 05:23:49

MouseAdapter 非常适合这种特定情况,而 Adapter 惯用法一般来说也很棒。 适配器具有接口所有方法的空实现,允许您子类化并仅实现与您的类相关的那些方法。 正如 Andrew Hare 所建议的,适配器也可以抛出 NotImplementedException。

MouseAdapter is great for this specific case and the Adapter idiom is great in general. An Adapter has empty implementations of all the methods of the interface, allowing you to subclass and implement only those methods that are relevant to your class. The Adapter could alternatively, as Andrew Hare suggests, throw NotImplementedException's.

南七夏 2024-07-28 05:23:49

侦听器的目的是接收某些事件的通知。 如果侦听器接口包含的方法回调比您需要的多,则忽略您不关心的回调。 在您的情况下, MouseAdapter 就是为此目的而设计的。 不要不要抛出UnsupportedOperationException,因为调用者很可能不希望出现异常。 它也很可能违反了侦听器接口的约定,因为每个方法都需要实现。

The purpose of a listener is to be notified of some events. If the listener interface contains more method callbacks than you need, then just ignore the ones you don't care about. In your case MouseAdapter was designed for this exact purpose. Do not throw UnsupportedOperationException as the caller is most likely not expecting the exception. It also most likely violates the listener interface's contract as each method is expected to be implemented.

琉璃繁缕 2024-07-28 05:23:49

我想我会将其描述为“无操作实现”,或者可能使用术语“适配器”。 正如其他人所指出的,Java 提供了一个 MouseAdapter 类来执行您想要的操作。 严格来说,它并不完全属于适配器模式的定义,适配器模式将一种 API 转换为另一种 API,但坦率地说,我倾向于务实地命名此类事物。

也许最重要的事情是明确您打算让该方法没有实现。 在 MouseAdapter 的特定情况下,您可能不想到处抛出 UnsupportedOperationException,但总的来说,这可能是一个很好的信号,表明您不打算这样做提供一个实现。 通常需要在源代码(或者更好的是方法文档)中添加注释来解释为什么没有完全实现接口。

I guess I'd describe it as "no-op implementations" or perhaps use the term "adapter". As others have noted, Java provides a MouseAdapter class which does what you want. Strictly speaking, it doesn't quite fall into the definition of the Adapter pattern, which transforms one API into another, but frankly, I tend to be pragmatic about naming such things.

Probably the most important thing to do is be clear that you intend for the method to have no implementation. In the specific case of the MouseAdapter, you probably don't want to go around throwing UnsupportedOperationException, but in general, it's probably a good signal that you don't intend to provide an implementation. A comment in the source code (or better, the method documentation) to explain just why you're not implementing the interface fully is usually necessary.

世界等同你 2024-07-28 05:23:49

我认为这并不特别重要。 就我个人的口味而言,我不喜欢看到开头旁边的右大括号,这会给出:

public void mouseEntered(MouseEvent e) {
}

有点空,但还好。 对于返回值,我们可以使其看起来一致,而 [] 样式则无法做到这一点。

但是当涉及到循环中的罕见情况时,我喜欢在那里加一个分号:

// Made up example.
while (++i < len && str.charAt(i) != '\0') {
    ;
}

这会给出:

public void mouseEntered(MouseEvent e) {
    ;
}

catch 子句的情况下,你最好在注释中有一个很好的借口(也许会删除一个中断)。

I don't think it particularly matters. For my personal tastes I don't like to see the closing brace next to the opening, which gives:

public void mouseEntered(MouseEvent e) {
}

A bit empty, but okay. In the case of a return value we can make it look consistent, wich you don't get with the [] style.

But when it comes to the rare case in loops, I like a semicolon in there:

// Made up example.
while (++i < len && str.charAt(i) != '\0') {
    ;
}

Which would give:

public void mouseEntered(MouseEvent e) {
    ;
}

In the case of catch clauses, you'd better have a good excuse in a comment (perhaps dropping an interrupt).

三人与歌 2024-07-28 05:23:49

我在搜索这个确切问题时发现了这一点。 我在需要 onScrollStateChanged 但不需要 onScroll 的地方使用滚动。 我倾向于:

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
            int totalItemCount) {
    return;         
} 

但是,我喜欢你给出的第二个例子(大括号在同一行)。 它紧凑、干净,并且能够始终如一地表达出故意留空的想法。

编辑:这就是我决定的:

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
            int totalItemCount) {return;}

这个有很多参数,所以它看起来不像一行那么好,但你明白了。

I found this while searching for this exact question. I'm using on scroll where I need onScrollStateChanged but not onScroll. I was leaning towards:

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
            int totalItemCount) {
    return;         
} 

However, I like the second example you give (with braces on same line). It's compact and clean and can consistently express the idea that it is intentionally left blank.

Edit: this is what I settled on:

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
            int totalItemCount) {return;}

This one has a lot of parameters so it doesn't look as nice as on one line but you get the idea.

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