Should I represent database data with immutable or mutable data structures?

后端 未结 3 2188
清歌不尽
清歌不尽 2021-02-13 23:13

I\'m currently programming in Scala, but I guess this applies to any functional programming language, or rather, any programming language that recommends immutability and can in

相关标签:
3条回答
  • 2021-02-13 23:35

    Why is a database mutable? Is it a fundamental nature of databases to be mutable? The relational model and using it as a persistence store for your application data might steer you towards this conclusion, but it may not be a fundamental property.

    Given that you may have other options such as storing a new version of your data when you update it, perhaps the premise of the question is undermined somewhat. Perhaps, even if you do have a 'mutable' database, you still need to provide a new value for the update function that is separate from the old value – consider for instance an optimistic lock where the update should only occur if the old value has not in the meantime changed.

    In other words, the mutability or otherwise of the database should not matter at all, you are dealing with a separate domain layer in your application. If you need to ask then the answer will always be immutable. Mutability is a complexity vector that experts should only introduce as a performance optimisation when it has been demonstrated to be necessary.

    0 讨论(0)
  • 2021-02-13 23:46

    "Interacting with the real world" has nothing to do with whether you use mutable or immutable data structures. This is a furfy that is repeated all too often and it is great that you have questioned it.

    While it is typically more healthy to dismiss garbage like this, you might be interested in a cursory debunking: http://blog.higher-order.com/blog/2012/09/13/what-purity-is-and-isnt/

    However, I strongly recommend dismissing it and moving on.

    Onto your question, you say you have boilerplate when you want to perform operations on your immutable data structures. In fact, there is very well established theory that solves this problem to a large extent. Here is a paper written about it using Scala:

    http://dropbox.tmorris.net/media/doc/lenses.pdf

    Hope that helps.

    0 讨论(0)
  • 2021-02-13 23:52

    In the trading app I'm currently working on, almost everything is immutable - certainly the model is.

    Our experience is that this has greatly simplified how we work with the model, including persistence.

    I don't understand yet why things have become simpler, it just has. I need to ponder on this more. Reasoning about the code and working with it is simpler.

    Yes, you need to use things like lenses but I tend to write them - a mechanical process - and move on. It's a tiny part which I am sure can be finessed.

    0 讨论(0)
提交回复
热议问题