I am designing an interface between a Java application and a device that accepts command sequences (a series of bytes) over a secure shell channel.
For the purpose of simplicity, there are fields
fieldAlpha
fieldBeta
...fieldn
that I can get and set on this device.
The command sequence is created out of a StringBuilder object, which consists of a
- prefix
- payload (if setter)
- suffix
After writing about 20 of these, I figured there MUST be a more maintainable way to handle this.
public String getFieldAlpha() {
StringBuilder sb = new StringBuilder();
sb.append((char) 0x1B).append("ABC").append("DEF").append((char) 0x0D);
byte[] command = sb.toString().getBytes();
String response = (sendMessage(command));
return response;
}
public String setFieldAlpha(String alpha) {
StringBuilder sb = new StringBuilder();
sb.append((char) 0x1B).append("ABC*").append(alpha).append("DEF").append((char) 0x0D);
byte[] command = sb.toString().getBytes();
String response = (sendMessage(command));
return response;
}
public String getFieldBeta() {
StringBuilder sb = new StringBuilder();
sb.append((char) 0x1B).append("OPQ").append("RST").append((char) 0x0D);
byte[] command = sb.toString().getBytes();
String response = (sendMessage(command));
return response;
}
public String setFieldBeta(String beta) {
StringBuilder sb = new StringBuilder();
sb.append((char) 0x1B).append("OPQ*").append(beta).append("RST").append((char) 0x0D);
byte[] command = sb.toString().getBytes();
String response = (sendMessage(command));
return response;
}
// ... and so forth
I suspect a better design for an API would be two methods that select functions based on parameters. I am hung up on the fact that the command sequence changes depending on the field.
getField()
setField(Method FieldName, String value)
Or is there an even better way I am not thinking about? I looked possibly using Enum Objects to set the prefix and suffix of field command sequences.
Aucun commentaire:
Enregistrer un commentaire