Let's say you are engineering a chat room software.
let client = new Client();
let room = rooms.FindRoom();
room.addClient(client);
This room (parent) now has a client (child).
client.on('message', (event) => {
// With the above code, room must be found
let room = rooms.FindClientsRoom(client);
if(room){
room.handleMessage(event);
}
});
Or we have a child that knows about its parent
let client = new Client();
let room = rooms.FindRoom();
room.addClient(client);
client.setRoom(room);
client.on('message', (event) => {
let room = client.getRoom();
if(room){
room.handleMessage(event);
}
});
This is incredibly fast compared to looking for a client within 1000s of rooms. But is there something wrong with the design pattern? In any system, such as XML, do child nodes know about their parents? Should they?
rooms.FindClientsRoom
would be to have a map of client to room. That shouldn't be much slower than storing the room on the client. I assume it's slow now because you're looping over all rooms.Should child nodes have a reference to their parents?
If they need them, yes. If they don't, no. The better question is, When do child nodes require a reference to their parents? Something you might find an answer to here, or here