Junior
What is the difference between object-oriented programming and functional programming?
sobes.tech AI
Answer from AI
OOP focuses on objects, their state, and behavior. Functional programming emphasizes functions and data transformation.
Main differences:
- State: In OOP, objects have mutable state. In FP, functions generally do not have mutable state and work with immutable data (immutability).
- Side effects: In OOP, methods can have side effects (modify object state). In FP, functions aim to be pure (no side effects, return the same result for the same inputs).
- Paradigm: OOP is based on classes, objects, inheritance, polymorphism, encapsulation. FP is based on functions as first-class entities, lambda calculus, recursion, immutability.
- Code structure: In OOP, code is organized around objects. In FP, code is organized around functions that transform data.
- Concurrency: FP usually simplifies parallel execution due to the absence of mutable state and side effects. OOP requires careful management of state in parallelism.
Example (simplified):
OOP:
class Counter {
private int count = 0; // Object state
public void increment() {
count++; // State change (side effect)
}
public int getCount() {
return count;
}
}
FP:
// Function for incrementing. Does not change external state.
// Returns a new value.
public static int increment(int value) {
return value + 1;
}
In real systems, elements of both paradigms are often used.