今天突然在想一個問題:

this.mainObject.getA().getAB().getABA().getABAC().doSomething();

像這樣的 Method chaining / chain of getters 是好的作法嗎?

討論串

Drawback

  • NullPointerException: 這很直觀,如果中間有誰回傳 null 就炸了。
  • Law of Demeter

a.b.Method()違反了此定律,而a.Method()不違反此定律。一個簡單例子是,人可以命令一條狗行走(walk),但是不應該直接指揮狗的腿行走,應該由狗去指揮控制它的腿如何行走。

不過其中一段我蠻贊同的

the law of demeter doesn't apply in purely data/structural (ie "struct like") relationships. IE Student.GetAddress().GetStreetName() is perfectly acceptable.

也就是說,如果這只是一連串的 getters 的話,那沒有什麼問題;但如果涉及到 mutators 如 Student.GetLastTest().ChangeGradeToA(),那就不行了。

the Law only applies when mutators are involved.

Benefit

this.mainObject.getA().getAB().getABA().getABAC().doSomething();

v.s.

A A = this.mainObject.getA();
AB AB = A.getAB();
ABA ABA = AB.getABA();
ABAC ABAC = ABA.getABAC();
ABAC.doSomething();

其它

Comments

comments powered by Disqus
Copyright © 2013 Andro Chen
Powered by Logdown and Greyshade
Favicon from The Noun Project