i am thinking about design for such simple exercise as Man in Maze.
I would like to make Maze object, put some Man objects inside it and call solve() for each to get out of Maze.
Man should know nothing about Maze. It just can try to go and find way out.
Here is how i see it:
maze = Maze.new
man1 = Man.new
man2 = Man.new
man3 = Man.new
maze.put(man1,man2,man3)
maze.men.each do |man| { man.solve }
But how to implement body of these classes?
How can man know how to walk inside Maze unless I give Maze instance to him?
But if i do that:
maze.put(man1(maze),man3(maze),man2(maze))
What the reason to put men inside Maze if I can just give Maze instance to them?
This is what i don’t understand and can’t find elegant solution.
Think of it this way: what data belongs with each class? What methods belong with it to work with that data? This is object-orientation: the bundling of data and relevant code.
The Maze class doesn’t need to know about any men. It’s a maze. All it is are some walls, some structure. Build it as such, as if nothing outside of it exists. Make some methods to obtain information about the maze, such as whether there’s a wall at some point, a corner, a junction…
The Man class is, in your case, conceived for a single purpose: find his way out of the maze. A Man therefore should have a position in the maze (part of his data) and some methods that help him look for the exit. Some depth-first search algorithm, for example.
Of course, you could have some collection of all men currently in a Maze embedded in the maze itself. But that’s not necessary. You could use any other collection to hold the men and iterate over them.