Paradigm, as a set of concepts, model, way of thiking, langage independent.
Functional programming is about immutable data/state
// !Functional
public static void main(String[] args) {
Runnable runnable = () -> {
System.out.println("Hello, " + System.getenv("USER")) // this is a side effect
}
runnable.run();
}
// Functional
public static void main(String[] args) {
Runnable runnable = () -> {
System.out.println("Hello, World")
}
runnable.run();
}
Functional programming is about lambda calculus (anonymous function)
// The Runnable interface (known as functional interface, more on that later) has a single method called run() which has no arguments and returns no value.
// It serves as a functional descriptor for a block of code that can be executed by a thread.
// When a class implements the Runnable interface, it must provide an implementation for the run() method.
// This will compile
public static void main(String[] args) {
var name = "Jean";
Runnable runnable = () -> {
System.out.println("Hello, " + name)) // this is a side effect
}
runnable.run();
}
// This will not compile, variable should be final or "effectively final"
// final variable means "const" (in other langage, java does not have a const keyword) as it can only be defined once and never changed after
// "effectively final" means that even is the variable is not declared like this, compiler can infer it has final (never modified)
public static void main(String[] args) {
var name = "Jean";
name = "Paul"; // here we break the "effectively final" contract
Runnable runnable = () -> {
System.out.println("Hello " + name);
};
runnable.run();
}
}
It allows code to be considered “declarative” over “imperative”.
for loop & if vs filter@FunctionalInterface
public interface Profile {
// Abstract method to get the profile information
String getProfileInfo();
// Default method to display a default message
default void displayDefaultMessage() {
System.out.println("This is a default message for profiles.");
}
// Static method to create a default profile
static Profile createDefaultProfile() {
return () -> "Default Profile";
}
}
Old style
new Thread(new Runnable {
public void run() {
fetchProfiles();
}
}).start();
New style
new Thread(() -> fetchProfiles()).start();