Dennis Grinch Dennis Grinch - 1 year ago 88
Java Question

Method naming conventions in interfaces ending with -able

So let's say I have an

class or interface (doesn't matter), which has a method
public open(Openable<T> item)
. A
interface, because all of them can be opened.

Question: how should I name method in
interface? If I name it
void open()
then this will imply that all objects which are
can open, which is not true, only
can open

Answer Source

An interface is a contract. If a class implements an interface, this means that the class fully supports all operations stated in the interface. (Although this is not always the case). Regarding the statement in the title: generally all interfaces whose names end with "-able" mark the class as being able to do something. Examples: Runnable - run(), Executable - execute(), Comparable - compareTo(), etc.


public interface Openable {
    void open();

The above interface does indeed imply that any class implementing it can be opened, irrespective of the call context. It does not necessarily mean that the object will open, but that is not the point.

Consider the following, as proposed by @sgj88_:


public interface Openable {
    void open(Opener opener);

Since you state that only Opener can open Openable objects, theoretically this is a better option. (Ideally, objects should only change their own internals not other objects'). However, in practice Opener acts like a behaviour altering object, akin to the strategy pattern.

public interface Opener {
    // or something similar
    double fractionToOpen();

    Opener FULL_OPENER = () -> 1.0;
    Opener HALF_OPENER = () -> 0.5;

The reason for this is that Opener does not know anything about the internals of Openable in order to change its state, while the name suggests that it does. You wouldn't have open() in Opener because then you wouldn't need Opener in the first place. Hence the semantics of design and implementation do not match.


Since only Opener type can open them then it can be assumed that there are more ways to modify the state of Openable than just a single call to open(). Then, Openable needs more methods for modifying its internal state,e.g.

setOpenRate(), setOpenFraction(), etc.

If this is not the case and the question refers to the call privileges, i.e. there is just a single class Opener in which open() can be used, then it shouldn't be an interface.

Perhaps given some context in which the interface is being designed would help to identify the best option.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download