Is there an idiom in Java for empty methods which

2019-03-22 17:21发布

问题:

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?

回答1:

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'.



回答2:

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
}


回答3:

Use MouseAdapter



回答4:

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


回答5:

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.



回答6:

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.



回答7:

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.



回答8:

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.



回答9:

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).



回答10:

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.