我应该用不可变或可变的数据结构来表示数据库数据吗? [英] Should I represent database data with immutable or mutable data structures?

查看:327
本文介绍了我应该用不可变或可变的数据结构来表示数据库数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在Scala中编程,但我想这适用于任何函数式编程语言,或者更确切地说,任何推荐不可变性并且可以与数据库交互的编程语言。

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 interact with a database.

当我从我的数据库获取数据时,我将其映射到模型数据结构。在函数式编程中,数据结构往往是不可变的。但是数据库中的数据是可变的,所以我不知道我的模型是否应该是可变的。

When I fetch data from my database, I map it to a model data structure. In functional programming, data structures tend to be immutable. But the data in a database is mutable, so I wonder whether or not my model should be mutable as well. In general, what would be a good and well-accepted practice in such a case?

在Coursera的Martin Odersky的Scala课程之后,我记得他说的是这样的: / p>

Following Scala courses by Martin Odersky on Coursera, I remember he said something like:


最好使用不可变的数据结构,但是当你想要
与真实世界交互时,对于使用可变数据
结构非常有用。

It's better to use immutable data structures, but when you want to interact with the real world, it can be useful to use mutable data structures.

因此,我不知道该怎么办。到目前为止,我的数据结构是不可变的,这导致了很多样板代码,当我想更新我的数据库中的记录。使用可变模型有助于减少此锅炉板吗?

So, again, I wonder what should I do. As of now, my data structures are immutable, and this is leading to a lot of boilerplate code when I want to update a record in my database. Would using a mutable model help reduce this boiler plate?

(我已经问过一个类似的问题,这是相当具体的我使用的技术,但我不满意的实际答案,所以我在这里概括了一下。)

(I already asked a similar question which was quite specific to the technologies I use, but I wasn't satisfied with the actual answers, so I've generalized it here.)

推荐答案

与真实世界进行交互与是否使用mutable或不变的数据结构。

"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.

虽然通常情况下更像这样的垃圾垃圾,你可能会更加健康感兴趣的粗略debunking:
http://blog.higher-order.com/blog/2012/09/13/what-purity-is-and-isnt/

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/

但是,我强烈建议您关闭它并继续操作。

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

希望有所帮助。

这篇关于我应该用不可变或可变的数据结构来表示数据库数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆