Sorry for the vague title, I couldn't think of a way to condense the question.

I am building an application that will run as a background service and intermittently collect data about the system its running on. A second Android controller application will query the system over tcp/ip for statistics about the system.

Currently, the background service has a tcp listener class that reads/writes bytes from a socket. When data is received, it raises an event to notify the service. The service takes the bytes, feeds them into a command parser to figure out what is being requested, and then passes the parsed command to a command executer class. When the service receives a "query statistics" command, it should return statistics over the tcp/ip connection.

Currently, all of these classes are fully decoupled from each other. But in order for the command executer to return statistics, it will obviously need access to the socket somehow. For reasons I can't completely articulate, it feels wrong for the command executer to have a direct reference to the socket. I'm looking for strategies and/or design patterns I can use to return data over the socket while keeping the classes decoupled, if this is possible.

Hopefully this makes sense, please let me know if I can include any info that would make the question easier to understand.

2 Answers 2


Perhaps implementing a message queue between whatever is responsible for the TCP/IP connection & your parser class would provide a nice, clean way to fully decouple everything.

Plus, you'd have the added bonus of any network communication issues not having to be handled by your parser class. It could just add messages to the queue and forget about them - nice separation of concerns. :-)


Ok, so this is what I've gone with for now. Any critiques are welcome. Basically I just modified the command executer to return a response object if a response is required, else null. That way the executer does not need any knowledge of where the response is going. The service mediator that sits between the socket and the rest of the classes checks if the response is null and if not, encodes it and ships it back over the tcp/ip connection.

enter image description here

  • 2
    That looks like a nice & simple implmentation. No extra, overly-clever bits to hide obscure bugs. Should be pretty easy to mock up some tests as well.
    – Alexander
    Nov 3, 2012 at 23:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.