Knute Johnson pisze:
I'm having a problem in some production code that I can't figure out.
Hi Knute,
I was trying to analyze your code, and currently it might be too
complicated. The class controls thread starting, stopping, network
operations, parsing the received lines, notyfying other components, and
so on... Too many concerns.
If I were you, I would start with refactoring it into manageable chunks.
For example, in the most general terms, your class has to read lines
from a server and process them somehow. Why don't you write a small
class, which does EXACTLY that, and push the remaining issues to other
classes ?
If you do that, you will be able to unit test each of the parts
separately. Currently it's rather hard...
See this class for example:
public class Worker implements Runnable {
private final String serverAddress;
private volatile boolean running;
//we will get lines from this fellow...
private LineSource lineSource;
//...and pass them to this guy
private final LineProcessor lineProcessor;
public Worker(String serverAddress, LineProcessor lineProcessor) {
this.running = true;
this.serverAddress = serverAddress;
this.lineProcessor = lineProcessor;
}
@Override
public void run() {
// does not connect to server, just creates the object and saves //
the server address
lineSource = new LineSource(serverAddress);
while (running) {
String line = null;
try {
line = lineSource.getLine();
} catch (Exception e) {
// TODO LOG IT. MUST... HAVE... LOGS...
}
if (line != null) {
try {
lineProcessor.processLine(line);
} catch (Exception e) {
// TODO LOG IT. MUST... HAVE... LOGS...
}
}
}
// ok, we're finished, just close the lineSource
try {
lineSource.close();
} catch (Exception e) {
// TODO LOG IT. MUST... HAVE... LOGS...
}
}
public void stop() {
running = false;
}
}
It is just a starting point, still too messy to be used in production.
And I did't really look into the subject of blocking operations.
I realize that my solution to your problem is an indirect one, but hey,
it just took five minutes to write this code.
Have a nice day,
Marcin Jaskolski