Method chaining 是否推荐?

2015-12-03 15:04:55 +08:00
 pinkman
我记得学编程的时候又听过尽量避免 method chaining ,因为其中任何一个环节出错就挂了(我记得还有个专门的术语,哪个达人记得的麻烦指点下)。但我看到写 jQuery 貌似很多时候都有用到 method chaining ,的确也会让程序更加简短,这和我理解的 mehtod chaining 有区别吗?最佳实践是什么呢?
1491 次点击
所在节点    问与答
3 条回复
shibo501c
2015-12-03 15:39:42 +08:00
你说的专门术语 指的是 fluent style 吗?
tylr
2015-12-03 15:49:48 +08:00
应该是 Law of Demeter, quote from [wikipedia]( https://en.wikipedia.org/wiki/Law_of_Demeter): an object should avoid invoking methods of a member object returned by another method. For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as "use only one dot". That is, the code a.b.Method() breaks the law where a.Method() does not. As an analogy, when one wants a dog to walk, one does not command the dog's legs to walk directly; instead one commands the dog which then commands its own legs.
pinkman
2015-12-03 16:03:41 +08:00
@tylr 感谢!就是这样说的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/240867

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX