dimanche 14 octobre 2018

decoupled design for async http request

What i am trying to write is a view-> controller -> model -> client -> HttpRequestSender relationship that is abstract, so i can replace the HttpRequestSender when i am using different platform (android-volley, Fx-SpringRest). since on android i need to use a-non main thread to preform the HttpRequest, my solution was to use a callback that is sent from the controller down throw the chain to enable the asynchronous behavior needed.

My issue is that all though it is a working solution, the code becomes highly hard to follow.

So that a simple method like registerDevice(String name) - as seen below:

`public class DeviceRegModel {

DeviceClient client;

DeviceInfoMgr deviceInfoMgr;

public void registerDevice(String name) throws DeviceNameTakenException {
    checkIfNameTaken(name);

    Device device = client.createDevice().getBody();

    device.setName(name);

    client.updateDevice(device);

    deviceInfoMgr.set(name);
}

private void checkIfNameTaken(String name) throws DeviceNameTakenException {
    for(Device dev : client.getAllDevices()) {
        if(dev.getName() == name) {
            throw new DeviceNameTakenException();
        }
    }
}`

Becomes that:

public class DeviceRegModel implements IModel {

DeviceClient client;

DeviceInfoMgr deviceInfoMgr;


public void registerDevice(String name, HttpCallback callback)   {
    ResponseCommand onOk = (res) -> checkIfNameTaken(name, res, callback);
    HttpFailCommands onFail = callback.getOnFailCmds();

    client.getAllDevices(HttpCallback.build(onOk, onFail));

}

private void checkIfNameTaken(String name, IResponse res, HttpCallback callback)  {
    for(Device dev : res.<Device[]>getBody()) {
        if(dev.getName() == name) {
            ExceptionCommand failCmd = callback.getOnFailCmds().getInternalFailCmd();
            failCmd.execute(new DeviceNameTakenException());
        }
    }
    createDevice(name,callback);
}

private void createDevice(String name, HttpCallback callback) {
    ResponseCommand onOk = (res) -> setNameLocally(name, res, callback);
    HttpFailCommands onFail = callback.getOnFailCmds();

    client.createDevice(HttpCallback.build(onOk, onFail));
}

private void setNameLocally(String name, IResponse res, HttpCallback callback) {
    Device device = res.<Device>getBody();
    device.setName(name);

    ResponseCommand onOk = (cmdRes) -> updateServer(name, cmdRes, callback);
    HttpFailCommands onFail = callback.getOnFailCmds();

    client.updateDevice(device, HttpCallback.build(onOk, onFail));
}

private void updateServer(String name, IResponse res, HttpCallback callback) {
    deviceInfoMgr.set(name);
    callback.getOnOkCmd().execute(res);
}

}'

I am trying to figure out if i am on the correct path here (with the second version) or should change my design?

Aucun commentaire:

Enregistrer un commentaire