Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

java - Is this a good example of Law of Demeter?

I'm studying for an oral exam, and I wonder if I have understood Law of Demeter correctly. In essence, I have understood that the Law of Demeter aims to loosen coupling by making classes less dependent on one another, and by not giving away explicitly how the classes get certain information. This is concluded in the quote "Only talk to your immediate friends". I have come up with this simplified example:

If we have a class Board and we have game pieces on our playing field and for example want to find out which pieces have moved an intuitive way to find this out would be to write something like:

Board.getGamePiece(p).getMovement();

But this violates the Law of Demeter. We thus delegate that task to the getMovement method by simply writing:

Board.getMovement(p);

Have I understood it correctly and are there any errors within my explanation? I am a bit unsure as to how to use the term "delegate" here, is it used correctly in my example?

question from:https://stackoverflow.com/questions/65599765/is-this-a-good-example-of-law-of-demeter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you grok the idea but I'm not sure if your example really makes sense. In the context of a board game, it's difficult for the Board to not be concerned with the possible movements! (So applying Demeter here would not make sense as possible the Board already has access to the Movement class).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...