V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
pinkman
V2EX  ›  问与答

Method chaining 是否推荐?

  •  
  •   pinkman · 2015-12-03 15:04:55 +08:00 via iPhone · 1568 次点击
    这是一个创建于 3306 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我记得学编程的时候又听过尽量避免 method chaining ,因为其中任何一个环节出错就挂了(我记得还有个专门的术语,哪个达人记得的麻烦指点下)。但我看到写 jQuery 貌似很多时候都有用到 method chaining ,的确也会让程序更加简短,这和我理解的 mehtod chaining 有区别吗?最佳实践是什么呢?
    3 条回复    2015-12-03 16:03:41 +08:00
    shibo501c
        1
    shibo501c  
       2015-12-03 15:39:42 +08:00
    你说的专门术语 指的是 fluent style 吗?
    tylr
        2
    tylr  
       2015-12-03 15:49:48 +08:00   ❤️ 1
    应该是 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
        3
    pinkman  
    OP
       2015-12-03 16:03:41 +08:00 via iPhone
    @tylr 感谢!就是这样说的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2390 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 02:25 · PVG 10:25 · LAX 18:25 · JFK 21:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.