Is there an idiom in Java for empty methods which exist to satisfy an interface?
Asked Answered
A

10

28

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?

Amabil answered 19/5, 2009 at 18:19 Comment(1)
You are aware of the MouseAdapter class, right? java.sun.com/javase/6/docs/api/java/awt/event/MouseAdapter.htmlFilagree
C
11

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
}
Czardom answered 19/5, 2009 at 18:29 Comment(0)
C
9

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

Cornelia answered 19/5, 2009 at 18:23 Comment(0)
R
5

Use MouseAdapter

Retardment answered 19/5, 2009 at 18:21 Comment(4)
While this answer is correct it doesn't address the spirit of the question which is what is to be done when only part of an interface is being implemented.Shows
He's asking for conevtions, not what interface to implement.Cornelia
Extend this class to create a MouseEvent listener and override the methods for the events of interest. (If you implement the MouseListener interface, you have to define all of the methods in it. This abstract class defines null methods for them all, so you can only have to define methods for events you care about.) java.sun.com/j2se/1.4.2/docs/api/java/awt/event/…Felic
The source for MouseAdapter would be as good a convention as any. However, I would argue that it depends on the method. In the case of MouseListener, there is no need to indicate if you have provided an implementation or not. For other interfaces, it may be appropriate to throw an exception and in others, it may be appropriate to just log that the method didn't do anything.Retardment
S
5

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
Spessartite answered 20/5, 2009 at 14:0 Comment(0)
T
3

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.

Turki answered 10/1, 2014 at 11:59 Comment(1)
Thanks for actually providing a link to the coding conventions like the OP asked.Pubescent
H
1

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.

Hulahula answered 19/5, 2009 at 18:26 Comment(0)
L
1

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.

Laky answered 19/5, 2009 at 18:31 Comment(1)
The caller is also probably not expecting the function to do nothing. By not doing anything, you have violated the interface contract, which will lead to weird and extremely hard to debug bugs. I would say throw the error so that the problem comes up immediately during testing/use. If you can't throw an error, you should at the very least log a warning that an Unsupported Operation has been called. Doing absolutely nothing, can be a costly mistake (in time debugging the resulting bugs). (when in doubt, at least log it so that there is at least a good hint for the bugs it causes)Ergener
G
0

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.

Gigantean answered 19/5, 2009 at 18:32 Comment(0)
E
0

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

Eyrie answered 19/5, 2009 at 18:36 Comment(0)
V
0

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.

Vector answered 25/8, 2012 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.