私は、さまざまな種類のバイナリパケットを送受信するネットワークアプリケーションを作成しています。できるだけ簡単に新しい種類のパケットをアプリケーションに追加しようとしています。バイナリ構造の読み書き:このコードを単純化するには?
今のところ、私はPacket
クラスを作成しました。そして、私は異なる種類のパケットごとにそのサブクラスを作成します。しかし、それは見た目ほどきれいではありません。私はこのようなコードで終わった:
static class ItemDesc extends Packet {
public final int item_id;
public final int desc_type;
public final String filename;
public final String buf;
public ItemDesc(Type t, int item_id, int desc_type, String filename, String buf) {
super(t); // sets type for use in packet header
this.item_id = item_id;
this.desc_type = desc_type;
this.filename = filename;
this.buf = buf;
}
public ItemDesc(InputStream i) throws IOException {
super(i); // reads packet header and sets this.input
item_id = input.readInt();
desc_type = input.readByte();
filename = input.readStringWithLength();
buf = input.readStringWithLength();
}
public void writeTo(OutputStream o) throws IOException {
MyOutputStream dataOutput = new MyOutputStream();
dataOutput.writeInt(item_id);
dataOutput.writeByte(desc_type);
dataOutput.writeStringWithLength(filename);
dataOutput.writeStringWithLength(buf);
super.write(dataOutput.toByteArray(), o);
}
}
このアプローチについて私が気になるのはコードの繰り返しです - 私はパケット構造を4回繰り返しています。私はこれを避けることがうれしいですが、私はそれを簡素化する合理的な方法を見ることができません。
私はすべての可能なフィールドタイプの辞書を作成し、このような新しいパケットタイプを定義するPythonで書いていた場合:
ItemDesc = [('item_id', 'int'), ('desc_type', 'byte'), ...]
私は、任意の関数型言語に似た何かをすることができることとします。しかし、私はJavaにこのアプローチをとる方法を見ることができません。
(たぶん私はあまりにも杓子定規だ、または私は、コードを書き、関数型プログラミングと書き込みコードに慣れて、私は:)任意の繰り返しを避けることができ)
は、任意の提案のために事前にありがとうございます。
非常によく見えます。私はあなたがそれをより少ないコードにすることができるとは思わない。 – ChaosPandion