“扁平优于嵌套"- 数据和代码? [英] "Flat is better than nested" - for data as well as code?

查看:40
本文介绍了“扁平优于嵌套"- 数据和代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题让我思考:我们是否应该将扁平优于嵌套"的原则应用于数据和代码?即使数据有逻辑树结构"?

This question got me thinking: should we apply the principle that "flat is better than nested" to data as well as to code? Even when there is a "logical tree structure" to the data?

在这种情况下,我想这意味着将子节点表示为一个 ID 列表,而不是一个实际的子节点列表,所有节点都在一个列表中:

In this case, I suppose it would mean representing children as a list of IDs, rather than an actual list of children, with all the nodes in a single list:

[ {'id': 4, 'children': ()},
  {'id': 2, 'children': (1, 7)},
  {'id': 1, 'children': (6, 5)},
  {'id': 6, 'children': ()},
  {'id': 5, 'children': ()},
  {'id': 7, 'children': (3,)},
  {'id': 3, 'children': ()} ]

(我使用元组是因为我不想让自己灵活地改变一个对象,直到这种灵活性以一种清晰的方式证明它自己是有用和可用的.无论如何,我永远不会使用 None在这里而不是一个空序列,因为它使逻辑复杂化,并且特殊情况还不够特殊" - 在这里,它根本不特殊.)

(I used tuples because I prefer not to give myself the flexibility to mutate an object until that flexibility proves itself to be useful and usable in a clear manner. In any case I would never use None here instead of an empty sequence, because it complicates the logic, and "special cases aren't special enough" - here, it isn't special at all.)

当然这更短,但树结构被模糊了.这是否与显式优于隐式"相矛盾?

Certainly this is shorter, but the tree structure is obscured. Does that contradict "explicit is better than implicit"?

我个人认为扁平胜于嵌套"的适用性有限,远不及禅宗最重要的方面.(当然,如果我不允许自己有重要的嵌套,我就不能做很多好的函数式编程事情.)我怀疑嵌套"的问题在于当您理解信息时它需要上下文切换.我真的认为在遵循命令式逻辑时,这比解析数据或函数式代码更像是一个问题 - 在这种情况下,更容易在脑海中命名嵌套块,并将其与外部上下文分开考虑.

Personally I find that "flat is better than nested" is of limited applicability, and nowhere near the most important aspect of the Zen. (Certainly I could not do a lot of the nice functional-programming things that I do if I didn't allow myself significant nesting.) I suspect that the problem with "nested" is that it requires context switching when you comprehend the information. I really think this is more of a problem when following imperative logic than for parsing data or functional-style code - where it's easier to just mentally name the nested block, and consider its workings separately from the outer context.

你怎么说?

推荐答案

我天生不喜欢这两种方法,而是使用看起来最适合任务的方法.

I wouldn't inherently prefer either, but rather use whatever seems best suited to the task.

如果结构很重要,嵌套让生活变得简单.如果您经常对每个节点进行操作,那么扁平结构可以很容易地使用 for node in tree.当然,如果你定义自己的类,抽象它很容易,所以两个选项都很简单;但与外部系统一起使用可能会更困难,例如转换为 JSON.

If the structure is important, nesting makes life simple. If you're regularly operating over each node, the flat structure makes it easy to use for node in tree. Of course, if you define your own class, its easy enough to abstract it so both options are simple; but it may be harder to use with external systems, such as converting to JSON.

这篇关于“扁平优于嵌套"- 数据和代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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