DEV Community

Discussion on: OOP vs functional programming

Collapse
 
skyjur profile image
Ski • Edited

You can do OOP with immutable objects. In js numbers, strings are objects but immutable.

But Date on other hand is mutable. Having some objects mutable some immutable leads to bugs if one does not know what are doing.

But regardless if it's mutable or not, state is mutated somewhere still.

Take redux reducer for example

reducer = (state, event) => newState
Enter fullscreen mode Exit fullscreen mode

it's immutable function on the surface, but it returns new (updated) state - of whole application state, thus there is a power to change anything in application state here. Mutability is not the main problem. Using purely immutable interfaces can help avoid certain type of bugs. But eventually it leads to the same big problem - somewhere state is updated, and the big question is, how is it encapsulated.

A careful developer would divide state in small chunks and ensure all reducers only take care of one little piece of state

const appReducer = state => {
   return {
      x: xReducer(state.x),
      y: yReducer(state.y)
   }
}
Enter fullscreen mode Exit fullscreen mode

not careful developer still can just as easily add unpredictable side effects even though interface is immutable

const xReducer = (state, event) => {
   if(event.type == 'UpdateX') {
      return { 
          ... state,
          x: state.x + event.size,
          y: state.y * -1 // hmm
      }
   }
   return state
}
Enter fullscreen mode Exit fullscreen mode

In redux on can also do same thing that one can do with setters/getters in object

const xReducer = (state, event) => {
    if(event.type === 'SetX') {
       return {...state, x: event.value}
    }
    return state
}
Enter fullscreen mode Exit fullscreen mode

now one can modify state anywhere from app code - immutable and functional version of setters/getters antipattern of OOP

render() {
  dispatch(SetX(1))
  dispatch(SetY(2))
}
Enter fullscreen mode Exit fullscreen mode

Immutability and functional development it self doesn't do that much. It's good but it's not a lot. One must also follow SOLID and other better known guiding principles (like Law of Demeter) to build good code and it doesn't matter OOP or functional.