views:

112

answers:

1

So I have these two classes, mpqs_client and client_protocol. The mpqs_client class handles a Boost socket connection to a server (sending and receiving messages with some specific format. Upon receiving a message, it calls a static method, parse_message(..), in the class client_protocol, and this method should analyse the message received and perform some corresponding action.

Given some specific input, the parse_message method needs to send some data back to the server. As mentioned, this happens through the class mpqs_client. So I could, from mpqs_client, pass "this" to parse_message(..) in client_protocol. However, this leads to a two-way association relationship between the two classes. Something which I reckon is not desireable. Also, to implement this, I would need to include the other in each one, and this gives me a terrible pain.

I am thinking this is more of a design issue. What is the best solution here?

Code is posted below.

Class mpqs_client:

#include "mpqs_client.h"

mpqs_client::mpqs_client(boost::asio::io_service& io_service, tcp::resolver::iterator endpoint_iterator) : io_service_(io_service), socket_(io_service) {
    ...
}
...
void mpqs_client::write(const network_message& msg) {
    io_service_.post(boost::bind(&mpqs_client::do_write, this, msg));
}

Class client_protocol:

#include "../network_message.hpp"
#include "../protocol_consts.h"

class client_protocol {
public:
    static void parse_message(network_message& msg, mpqs_sieve **instance_, mpqs_client &client_) { 
        ...                 
        switch (type) {         
            case MPQS_DATA: 
                ...         
                break;
            case POLYNOMIAL_DATA:
                ...
                break;
            default:
                break;
        }
    }
A: 

Extract out an interface (abstract base call in C++) for the mpqs_client, and pass an instance of that into the client_protocol - the instance actually being the real mpqs_client object, but the interface avoids the bi-directional dependency.

Douglas Leeder
My solution was to do forward declaration, so in client_protocol I do class mpqs_client; and then use a pointer to it instead..
Martin Lauridsen