Procedural Programming vs Functional Programming

Procedural Programming vs Functional Programming





Procedural programming focuses on a step-by-step sequence of instructions that change data over time, while functional programming treats computation as the evaluation of mathematical functions without changing state.
Core Differences
  • 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 for and while) to iterate through steps. Functional code prefers recursion and higher-order functions (like map, filter, and reduce).  
  • 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. 

Procedural example using Java 

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]

 }

}


Comments

Popular posts from this blog

Companies and real-world applications using JavaFX

Building Cross-Platform JavaFX Apps with Gluon

Delete vs Truncate in MySQL and MS SQL Server