Background
Working towards my final project at University, team project and we're stuck with a disagreement on a point in our Class Diagram.
We have a class, called "Road". In here with have some attributes like "ID", "Name", etc.
This class also has functions like getName(ID): string
Question
Should we include a getRoads()
function within the class?
My thought is that we can use this to select all roads where we want to generate a picklist listing all the roads, for example.
My colleague suggests that this is wrong, and such a function should be held outside of any classes.
While I understand his point, I cannot understand rationale behind either way being right or wrong.
We have worked very hard on this project and I would hate to lose points over something so small, so any advice on the matter would be greatly appreciated!!
1 Answer 1
A road-object would presumably represent a single road. A getRoads()
would require the road to somehow know about all the other roads in existence. This would likely violate the law of demeter
Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
I.e. If there are two unrelated roads they should have no knowledge of each other. It would be much better to maintain this picklist outside the road class.
One case where getRoads()
may make sense is if a road-object is a node in a graph, and returns a list of connected roads, so that graph traversal algorithms can be used to traverse the complete road network. But then it should probably be named getConnectedRoads
or similar to make the behavior clearer.
-
Amazing, thank you so much! Clears my understanding so well. And thank you for the added points of clarity, that is even more helpful than I can put into words!!!Simon– Simon2024年06月17日 12:34:14 +00:00Commented Jun 17, 2024 at 12:34
-
3Let me add that a function which returns connected roads should not be named getRoads, but something like getConnectedRoads.Doc Brown– Doc Brown2024年06月18日 05:14:22 +00:00Commented Jun 18, 2024 at 5:14