Note that there are some explanatory texts on larger screens.

plurals
  1. POReading/writing binary structures: how to simplify this code?
    text
    copied!<p>I'm writing a network app, which sends and receives a lot of different kinds of binary packets, and I'm trying to make adding new kinds of packets to my app as easy as possible.</p> <p>For now, I created a <code>Packet</code> class, and I create subclasses of it for each different kind of packet. However, it isn't as clean as it seems; I've ended up with code like this:</p> <pre><code>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); } } </code></pre> <p>What bothers me about this approach is the code repetition - I'm repeating the packet structure four times. I'd be glad to avoid this, but I can't see a reasonable way to simplify it.</p> <p>If I was writing in Python I would create a dictionary of all possible field types, and then define new packet types like this:</p> <pre><code>ItemDesc = [('item_id', 'int'), ('desc_type', 'byte'), ...] </code></pre> <p>I suppose that I could do something similar in any functional language. However, I can't see a way to take this approach to Java.</p> <p>(Maybe I'm just too pedantic, or I got used to functional programming and writing code that writes code, so I could avoid any repetition :))</p> <p>Thank you in advance for any suggestions.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload