Refactored Enough?

Status
Not open for further replies.
Continuation from here

Suppose you have the following bit of a single-threaded socket server in Java 7 (and assuming that I didn't miss parens or what-not ... At work, I don't have a dev environment on an Internet-facing box):

Code:
/**
 * File: SingleThreadSocketServer.java
 *
 * Listens on a port and processes the text data coming from client connections.
 * Single-threaded; only allows one client connection at a time
 */
public class SingleThreadSocketServer implements Runnable {

  private static final Logger LOG = Logger.getLogger(SingleThreadSocketServer.class.getName());
  private volatile running = false;
  private final int port;

  public SingleThreadSocketServer(int port) {
    this.port = port;
  }

  // main processing, Thread Runnable
  public void run() {
    running = true;
    try (ServerSocket socket = new ServerSocket(port)) {
      while(running) {
        try (Socket client = socket.accept()) {
          handleClientConnection(client);
        }
      }
    } catch (IOException e) {
      LOG.log(Level.SEVERE, "", e);
    }
  }

  // read input from the client inputstream and process it line by line
  // assumes: string/text-based input
  private void handleClientConnection(Socket client) {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
      String line;
      while((line = reader.readLine()) != null) {
        process(line);
      }
    } catch (IOException e) {
      LOG.log(Level.SEVERE, "", e);
    }
  }

  // process the line
  private void process(String line) {
    // do stuff with the line 
  }
}

This would require a "driver" something like:
Code:
public class Main {
  public static void main(String[] args) {
    Runnable server = new SingleThreadSocketServer(8080);
    server.run();
  }
}

Is "run" fully refactored/extracted? Does it do "one thing"? One could argue that you could factor out the initialization bits into an init() method which would require the ServerSocket to be a class member/field. Or, you could push the ServerSocket handling down a level, and make it look like:

Code:
public void run() {
  running = true;
  try (ServerSocket socket = new ServerSocket(port)) {
    handleServerSocket(socket);
  } catch (IOException e) {
    LOG.log(Level.SEVERE, "", e);
  }
}

public void handleServerSocket(ServerSocket socket) {
  while(running) {
    try (Socket client = socket.accept()) {
      handleClientConnection(client);
    } catch (IOException e) {
      LOG.log(Level.SEVERE, "", e);
    }
  }
}

Is this going too far? Does it really make sense? Or am I just begging for trouble?

Is "handleClientConnection" fully refactored/extracted?

In fact, I need TWO slightly different single-threaded socket servers, but the only difference in them are the ports and what is done with the incoming text-based data, so, a refactoring leads to:

Code:
/**
 * File: ClientConnectionHandler.java
 * 
 * Interface which defines how to handle a client connection via Socket
 */
public interface ClientConnectionHandler {
  public void handleClientConnection(Socket client);
}


/**
 * File: SingleThreadedSocketServer.java
 *
 * Single threaded socket server
 * User must provide a ClientConnectionHandler to handle connections
 */
public class SingleThreadSocketServer implements Runnable {

  private static final Logger LOG = Logger.getLogger(SingleThreadSocketServer.class.getName());
  private volatile running = false;
  private final int port;
  private final ClientConnectionHandler handler;

  public SingleThreadSocketServer(int port, ClientConnectionHandler handler) {
    this.port = port;
    this.handler = handler;
  }    

  // main processing, Thread Runnable
  public void run() {
    running = true;
    try (ServerSocket socket = new ServerSocket(port)) {
      while(running) {
        try (Socket client = socket.accept()) {
          handler.handleClientConnection(client);
        }
      }
    } catch (IOException e) {
      LOG.log(Level.SEVERE, "", e);
    }
  }
}


/**
 * LoggingClientHandler.java
 *
 * ClientConnectionHandler which simply writes all incoming data out to a log file.
 */
public class LoggingClientHandler implements ClientConnectionHandler {

  private final Writer writer;

  public LoggingClientHandler(String logFilePath) {
    this.writer = new PrintWriter(logFilePath);
  }

  // read input from the client inputstream and process it line by line
  // assumes: string/text-based input
  @Override
  public void handleClientConnection(Socket client) {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
      String line;
      while((line = reader.readLine()) != null) {
        process(line);
      }
    } catch (IOException e) {
      LOG.log(Level.SEVERE, "", e);
    }
  }

  // process the line
  private void process(String line) {
    writer.println(new Date() + ": " + line);
    writer.flush();
  }
}

requiring a driver that looks like:

Code:
public class LoggingServer {
  public static void main(String[] args) {
    // assumes args[0] contains the path to the logging directory
    ClientConnectionHandler handler = new LoggingClientHandler(args[0]);
    // assumes args[1] contains the port to listen on
    int port = Integer.parseInt(args[1]);

    SingleThreadSocketServer server = new SingleThreadSocketServer(port, handler);
    server.run();
  }
}

This complicates things such as Exception handling... where do I handle the exceptions? Or just let them trickle up? Certainly we don't want an exception to stop the main loop which is accepting connections as that would cause the entire program to exit and possibly lose data.

Also, now I've added a complication in that there is no way to close the writer inside LoggingClientHandler if/when I *DO* go to a multi-threaded model (not to mention a "global" handler handling multiple connections with the internal state...)

And, in truth, I HAVE taken it further and factored out the public void process(String line) bit into an InputLineProcessor interface with a LoggingLineProcessor which works as above. :sigh:


So I guess I'm asking ... Would you do anything remarkably different?
 
Exceptions: You handle them at the same layer, usually in the "presentation". In this case, you'd handle it in the "driver" or very near it. If you catch exceptions at lower levels, you end up replacing it with "might be null, and the compiler can't save you" returning.

SingleThreadedSocketServer: In this case, there's no reason to have a second class for handling the data. It should be using the interface directly. You don't have instances of generic classes, you have specific instances with meaningful names that implements this class. You'd pass a handler class as a parameter for something that's going to be changed at runtime, not compile time. (YourNameHereTextParser > implements SingleThreadedSocketServer > interface ClientConnectionHandler)

Also, is it handling the ClientConnection or is it really the Message Handler? The server is the one handling the connections, the "clientconnection" class is handling the message/data.
 
[url=http:/civis/viewtopic.php?p=26138017#p26138017:1tfe0sy9 said:
Jackass JoeJoe[/url]":1tfe0sy9]Exceptions: You handle them at the same layer, usually in the "presentation". In this case, you'd handle it in the "driver" or very near it. If you catch exceptions at lower levels, you end up replacing it with "might be null, and the compiler can't save you" returning.

So, catch / log / rethrow?

SingleThreadedSocketServer: In this case, there's no reason to have a second class for handling the data. It should be using the interface directly. You don't have instances of generic classes, you have specific instances with meaningful names that implements this class. You'd pass a handler class as a parameter for something that's going to be changed at runtime, not compile time. (YourNameHereTextParser > implements SingleThreadedSocketServer > interface ClientConnectionHandler)

I didn't show the OTHER class which actually processes/parses the data rather than logging it. Yes, both will be running on different ports on different machines (its... complicated.)

But I'm still not quite sure what you're saying here. Are you saying to create two identical classes let's call them LoggingServer and ProcessingServer, with the only thing different is the internal handlers (and keeping them internal as well?) That seems to fly in the face of once-and-only-once. Or am I misunderstanding?

Also, is it handling the ClientConnection or is it really the Message Handler? The server is the one handling the connections, the "clientconnection" class is handling the message/data.

Its the Socket that gets created by a successful ServerSocket.accept(). Therefore, its a client connection to the server. I was going to call it a ServerClientConnectionHandler or ServerSocketClientConnectionHandler, but those are just a bit much, I think.

But the Handler itself may not necessarily handle the individual messages... that would be an InputLineProcessor or something?
 
Status
Not open for further replies.