Procedural Programming vs Functional Programming
Procedural Programming vs Functional Programming
- Execution Style: Procedural programming is imperative; you tell the computer how to do something by listing actions in order. Functional programming is declarative; you describe what result you want by combining functions.
- State and Data: Procedural code uses variables that update and can be shared globally or modified by different procedures. Functional code relies on immutability, meaning data cannot change once created, and avoids shared state.
- Side Effects: Procedural functions often cause side effects by altering external variables or system states. Functional programming uses pure functions—functions that always return the same output for the same input and cause no side effects.
- Flow Control: Procedural code uses loops (like
forandwhile) to iterate through steps. Functional code prefers recursion and higher-order functions (likemap,filter, andreduce). - Languages: Common procedural languages include C and Fortran, while typical functional languages include Haskell and Clojure. Many modern languages (like Python, JavaScript, and Rust) support both styles.
import
java.util.ArrayList;
import java.util.List;
public class ProceduralExample {
public static void main(String[] args) {
List<Integer>
numbers = List.of(1, 2, 3, 4, 5);
List<Integer>
result = new ArrayList<>();
//
Step-by-step loop modifying an external list
for
(int num : numbers) {
if
(num % 2 == 0) { // State check
result.add(num * num); //
Side effect
}
}
System.out.println(result);
}
}
Functional example using Java
import java.util.List;
import java.util.stream.Collectors;
public class FunctionalExample {
public static void main(String[] args)
{
List<Integer> numbers =
List.of(1, 2, 3, 4, 5);
// Pipeline of
pure functions with zero mutation
List<Integer> result =
numbers.stream()
.filter(num
-> num % 2 == 0) // What to keep
.map(num -> num *
num) // What transformation
.collect(Collectors.toList());
System.out.println(result); // [4, 16]
}
}
.png)

Comments
Post a Comment