Clojure states within states within states

前端 未结 3 1949
梦谈多话
梦谈多话 2021-02-13 02:45

I\'d love to hear what advice the Clojure gurus here have about managing state in hierarchies. I find I\'m often using {:structures {:like {:this {:with {:many \'levels}}

3条回答
  •  失恋的感觉
    2021-02-13 03:19

    Don't use nested atoms in a data structure if at all possible.

    The main reason is that immutability is your friend. Clojure is a functional language that thrives on immutable data structures. Most libraries assume immutable data structures. Clojure's STM assumes immutable data structures to get the best possible concurrency. Immutability gives you the opportunity to take consistent snapshots of the entire state at any one instant. Pure functions that operate on immutable data are easy to develop and test.

    If you put atoms inside your data structures then you lose all the advantages of immutability and risk making your code very complex - it's a lot harder to reason about a data structure if it contains a lot of mutable components.

    Some suggested alternative approaches:

    • Put your entire data structure in a single ref or atom. This can be a huge data structure with no problem - I once wrote a game where the entire game map was held in a single atom without any difficulty.
    • Use the various methods that are designed for accessing and changing nested immutable data structures: assoc-in, get-in, update-in etc.
    • Use recursive functions to make navigating your data structure more managable. If one node of your structure has sub-nodes of the same "type" then it's usually a good hint that you should be using some form of recursive function.

提交回复
热议问题