By the end of this post, you’ll understand:
✅ What pure functional programming is
✅ The key rules it follows
✅ How to write Java programs following these rules
Let’s get started! 🚀
1️⃣ What is Pure Functional Programming?
Pure functional programming follows strict rules to ensure that functions are predictable, reusable, and maintainable.
It follows four key principles:
1️⃣ No State – Functions should not store or rely on changing variables.
2️⃣ No Side Effects – Functions should not modify the external state or affect anything outside.
3️⃣ Immutable Variables – Data should not be changed after it is created.
4️⃣ Favor Recursion Over Looping – Loops are avoided in favor of recursive function calls.
Let’s explore these one by one with detailed examples in Java.
2️⃣ Rule 1: No State (Stateless Functions)
❌ Imperative Example (With State)
public class StatefulExample {
private int counter = 0; // State variable
public int increment() {
return ++counter; // Modifies state
}
public static void main(String[] args) {
StatefulExample obj = new StatefulExample();
System.out.println(obj.increment()); // Output: 1
System.out.println(obj.increment()); // Output: 2 (State changed)
}
}
🔴 Why is this bad?
- The function
increment()
modifiescounter
, making it stateful. - Every call changes the output, making it unpredictable.
✅ Functional Example (Stateless)
public class StatelessExample {
// Pure function that does not store state
public static int increment(int value) {
return value + 1; // No state change
}
public static void main(String[] args) {
System.out.println(increment(0)); // Output: 1
System.out.println(increment(0)); // Output: 1 (Always same for same input)
}
}
✅ Why is this good?
✔ No state modification – The function only depends on the input.
✔ Predictable behavior – It always gives the same result for the same input.
3️⃣ Rule 2: No Side Effects
A side effect happens when a function modifies external data, prints to the console, changes files, or modifies global variables.
❌ Imperative Example (With Side Effects)
public class SideEffectExample {
private static int total = 0; // External state
// Impure function that modifies external variable
public static int addToTotal(int value) {
total += value; // Modifies external state
return total;
}
public static void main(String[] args) {
System.out.println(addToTotal(5)); // Output: 5
System.out.println(addToTotal(5)); // Output: 10 (Different result for same input!)
}
}
🔴 Why is this bad?
- Modifies
total
(external state), making the function impure. - Unpredictable – Calling
addToTotal(5)
twice gives different outputs.
✅ Functional Example (No Side Effects)
public class NoSideEffectsExample {
// Pure function that does NOT modify external state
public static int add(int a, int b) {
return a + b; // Only depends on inputs
}
public static void main(String[] args) {
System.out.println(add(5, 5)); // Output: 10
System.out.println(add(5, 5)); // Output: 10 (Always same)
}
}
✅ Why is this good?
✔ No external variable modification
✔ No side effects – The function only depends on its parameters.
4️⃣ Rule 3: Immutable Variables
Functional programming does not allow variables to change after they are assigned.
❌ Imperative Example (Mutable Variables)
public class MutableExample {
public static void main(String[] args) {
int sum = 0; // Mutable variable
sum += 10; // Modified state
System.out.println(sum); // Output: 10
}
}
🔴 Why is this bad?
sum
changes its value, which goes against immutability.
✅ Functional Example (Immutable Variables)
public class ImmutableExample {
public static void main(String[] args) {
final int sum = 10; // Immutable variable
System.out.println(sum); // Output: 10
}
}
✅ Why is this good?
✔ No variable modification
✔ No unintended state changes
✅ Example: Using Immutable Lists
import java.util.List;
public class ImmutableListExample {
public static void main(String[] args) {
List<String> names = List.of("Alice", "Bob", "Charlie"); // Immutable List
System.out.println(names);
}
}
✅ Why is this good?
✔ List.of()
creates an immutable list that cannot be modified.
5️⃣ Rule 4: Favor Recursion Over Looping
Functional programming avoids loops and prefers recursion.
❌ Imperative Example (Using Loops)
public class LoopExample {
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
System.out.println(factorial(5)); // Output: 120
}
}
🔴 Why is this bad?
- Uses mutable state (
result
), violating immutability.
✅ Functional Example (Using Recursion)
public class RecursionExample {
// Recursive function for factorial
public static int factorial(int n) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive case
}
public static void main(String[] args) {
System.out.println(factorial(5)); // Output: 120
}
}
✅ Why is this good?
✔ No mutable state – No variable is modified.
✔ Uses recursion – Preferred in functional programming.
🎯 Final Takeaway
✅ Pure Functional Programming Rules:
✔ No State – Functions do not store or rely on changing variables.
✔ No Side Effects – Functions do not modify external state.
✔ Immutable Variables – No changes to assigned values.
✔ Favor Recursion Over Loops – Avoids modifying loop counters.
Following these principles makes your code predictable, testable, and scalable.
Comments
Post a Comment
Leave Comment