I've spent my fair share of time criticizing other people's code on this site; but I'm finding out I'm kind of a hypocrite. Almost everything I've written so far has been some program whipped together to do some task for me. I have little experience actually starting out writing maintainable code.
Then today I decided to start a semi-large project. I want to write a sort of custom networked remote manager; a kind of cross-breed between ssh
and an all-out remote desktop.
I wrote up the following class while realizing the previous revelations:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
public abstract class Connection implements Runnable {
private final Socket s;
private final InputStream is;
private final OutputStream os;
private final ArrayList<byte[]> posts;
private boolean run;
public Connection(String addr, int port) throws UnknownHostException, IOException {
s = new Socket(addr, port);
is = s.getInputStream();
os = s.getOutputStream();
posts = new ArrayList<>();
run = true;
new Thread(this).start();
}
public void post(byte data[]) {
synchronized (posts) {
posts.add(data);
}
}
public void stop() {
run = false;
}
public void run() {
while (run) {
byte send[] = null;
synchronized (posts) {
if (posts.size() > 0) {
send = posts.get(0);
posts.remove(0);
}
}
if (send != null) {
try {
os.write(send);
} catch (IOException e) {
hasError(e);
}
}
try {
if (is.available() > 0) {
byte data[] = new byte[is.available()];
receive(data, is.read(data));
}
} catch (IOException e) {
hasError(e);
}
}
}
public abstract void receive(byte data[], int len);
public abstract void hasError(Exception e);
}
It occurred to me I should probably be asking here how maintainable code is actually written. I'm kind of ashamed I haven't done this sort of thing before, but as a self-taught programmer I presume this sort of obstacle is common.
Given the above sample of my idea of how to make maintainable modular code, what sort of pitfalls should I look out for while making the excursion into a legitimate program of larger than two or three files?