Should I place a public static method in a class or an interface?

98 Views Asked by At

I wonder what considerations I should make, when I have to decide whether to take an interface or a class to place my static helper method in.

Concrete example: I want to provide a little method, that I can call from the main method in Swing components, so I can faster iterate the development on them.

Should I place it in an interface or in a class?

public final class SwingDevHelper {
    public static void startSwingContainer(Container container) {
        ...
    }
}
public interface SwingDevHelper {
    static void startSwingContainer(Container container) {
        ...
    }
}

Do I have to consider semantical or technical points, e.g. performance or visibility?

2

There are 2 best solutions below

0
Max Farsikov On

If this question is raised then this method does not belong to an interface ('interface' in broad meaning, not just Java). So it is always better to put it as low as possible. In other words, if it is possible -- keep it in a class, and move to interface only essential members.

1
Andy Turner On

The difference comes in the instantiability of SwingDevHelper.

If you need to instantiate SwingDevHelper, it can be either an interface or a (final) class.

If you don't need to (and/or don't want to) instantiate SwingDevHelper, make it a class with a private constructor:

public final class SwingDevHelper {
    private SwingDevHelper() {}  // Prevents instantiation outside this class.

    public static void startSwingContainer(Container container) {
        ...
    }
}

Making the class non-instantiable is a good idea where possible (i.e. when an instance of that class is meaningless/useless) because it simplifies the reasoning about the code: you never have to worry about what to do when you encounter an instance of it.

There is an item specifically about this in Effective Java: it's Item 22 in 3rd Ed: "Use interfaces only to define types". TL;DR: if SwingDevHelper isn't a meaningful type, don't use an interface.