Reputation: 61
I want to create a common functionality across many classes. SO I have 2 approaches. 1) Create a new class and have a static method in it. 2) Create a new interface and have a concrete static method in it.
Can anyone explain the difference with respect to performance on both these approaches? Please consider both memory and processing impact.
Which approach should I choose and why?
Upvotes: 2
Views: 381
Reputation: 120848
Performance wise it should not matter, meaning that even if it is, it would be extremely small; so this should never drive your decision.
On the other hand defining an interface with a static method that is solely used for common code is a big code smell IMO. static methods in interfaces are usually defined so that they return an instance of this interface; I tend to look at them as static factory methods that usually return instances of themselves, like Predicate#isEqual
:
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
Besides that an interface purpose is still to be extended, if you write a simple static method inside it, you are sort of breaking that rule.
Another problem is that when you define a static method in an interface, classes that extend this interface can not use that method. Unlike default methods for example. So if you have an interface:
interface Test {
public static String test() {
return "";
}
public default String testAgain() {
return "";
}
}
And a class TestImpl
that extends this interface, than:
TestImpl ti = new TestImpl();
ti.testAgain();
ti.test(); // will not compile
So may be you can use a default method instead of static. I sometimes favor this because it keeps the code closer to where I need it: if a certain class implements an interface with a default method
- the code is right there, I don't need to use an external class.
static utility classes on the other hand are present all over the jdk for example, like Collections
, Streams
or Spliterators
and that is what I would use if I were in your shoes.
Upvotes: 1