I have a socket.io server listening for certain events on sockets. Whenever an event is fired, it passes the event data to an event-handler. My question is, should the event handler have a reference to the server, and respond directly to the events like so?
eventHandler.handle = function(event){
myServerReference.emit(event, etc);
}
Or should the event handler fire an event when it has data to send, and the server should listen for it and handle the data sending like so:
eventHandler.onResponse(function(data){ server.emit(data); }
Which is a better approach in the long run? Is there a better way to design this?
While the short answer is "it depends," a good OO practice is to keep in mind the "S" of "SOLID":
In object-oriented programming, the single responsibility principle states that every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.
If the unit of code in which the event handler lives is doing too much (that is, doing someone else's job), you should move that functionality elsewhere.