Let's say I have a method getAverageDifficulty
in my class Difficulty
that goes like this:
public static Float getAverageDifficulty (List<Difficulty> difficultyList) {
...
return average;
}
My method obviously needs to be static, since it makes no sense requiring an instance of Difficulty
. Now let's say I'm using an interface IDifficulty
so I can change my implementation later. Obviously, I do want my getAverageDifficulty
method to be available from IDifficulty
, and, as I can't declare a static method abstract, the obvious option is to put getAverageDifficulty
directly in my interface. My question is: am I making a mistake by putting that static method in my interface, which contains other Difficulty
methods waiting to be implemented? Should I not mix static and "normal" interface abstract methods? Should I create DifficultyHelper
class and put my method there?
Ultimately, this is a matter of style. However, if the only purpose of the helper class is to hold this method (and maybe a few similar ones), then you will be saving yourself one class definition by placing them in the interface:
As of Java 8, the restriction that interfaces cannot contain static methods was eliminated, so there is typically little reason to provide a noninstantiable companion class for an interface [Effective Java, 3rd edition, Item 1: Consider static factory methods instead of constructors].