As a rule, in the context of a large project, is it considered safe to take make an existing, ubiquitously used interface into a functional interface?
E.g., given an existing interface and class:
public interface Interface {
public double calculateSomething(double x);
public void doSomething();
}
which is implemented by
class InterfaceImplementer implements Interface {
public double calculateSomething(double x) {
return 2 * x;
}
public void doSomething() {
// insert specific behavior here
}
}
can I safely change the interface by defining all but one method as default:
public interface Interface {
public double calculateSomething(double x);
default void doSomething() {
// insert some default behavior here
}
}
So that I can go from defining an object as
Interface object = new InterfaceImplementer() {
@Override
public double calculateSomething(double x) {
return 2 * x;
}
};
to
Interface object = (x) -> 2 * x;
while still being able to define objects in the old, tedious way.
From what I can tell, this runs no risk of upsetting any existing code, and I've made such a change to a large project and had no runtime or compile errors. But I want some confirmation whether this matches up with common knowledge and best practices.
Functional interfaces are included in Java SE 8 with Lambda expressions and Method references in order to make code more readable, clean, and straightforward. Functional interfaces are interfaces that ensure that they include precisely only one abstract method.
A functional interface can extends another interface only when it does not have any abstract method.
java - Replace functional interface with Function - Stack Overflow.
No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete.
Any interface that only has a single non-default method (only one method needs to be implemented in a class) is by definition a functional interface. This is a good rule!
However, a @FunctionalInterface
annotation has the advantage of enforcing the "only one method in the interface for a functional interface"-rule. So if you added it to your original two-method interface, you would have gotten a compiler error. Therefore by explicitly adding @FunctionalInterface
you declare your intent and make your code more clear to future maintainers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With