Is there any place for OOP in redux?

前端 未结 3 762
耶瑟儿~
耶瑟儿~ 2021-02-05 06:14

I\'ve been using object-oriented programming practices for 25 years and trying to move toward functional programming for the last 5 years, but my mind always goes towards OOP wh

3条回答
  •  野性不改
    2021-02-05 07:17

    I'll answer my own question by describing what I ended up doing, imperfect as it is.

    First, instead of regular ES6 class syntax, I've started using stampit, which is uglier that ES6 classes, but much more flexible.

    Mainly, though, my complex objects exist in two forms:

    • plain JS objects for the store
    • class (actually stamped) instances for convenience and power of using instance methods.

    I use a convention of putting an _underscore in front of all references to the plain objects. My "solution" is kludgy and bad for lots of reasons, but I think trying to use selectors for everything would be worse. If you're curious, here's the place in my code where I "inflate" my plain store objects into instances: https://github.com/Sigfried/vocab-pop/blob/localstorage/src/ducks/conceptSet.js#L292

    UPDATE

    Turning redux state POJOs into class instances (regular or stampit) is a terrible idea and someone should have stopped me long ago.

    I probably should have accepted @markerikson's answer, and maybe the Redux-ORM thing is worth looking at, but I just wanted to say definitively, DON'T DO WHAT I DID. (I always think I'm so smart filling in the "gaps" of technologies I'm learning with clever hacks -- and then I spend painful months cleaning up the mess once I understand why that technology didn't include my hack in the first place.)

    Another update

    From Composing Software: An Introduction:

    What we won’t do is say that functional programming is better than object-oriented programming, or that you must choose one over the other. OOP vs FP is a false dichotomy. Every real Javascript application I’ve seen in recent years mixes FP and OOP extensively.

    Looks like there are good ways to think about combining FP and OOP, and it will, no doubt, use some immutable classes and composition without a lot of inheritance. This series on composition looks like what I needed to learn.

提交回复
热议问题