I am receiving messages of 14 bytes via a socket’s InputStream.
They look like this: a55a0b051000000000223664300c
and they have a specific pattern. The first two bytes are for synchronization and are always constant.
I am looking for the best way to verify this message.
First the length of 14 bytes would have to be verified, then the first 2 Bytes etc.
This is my approach until now:
public void handleMessage(String msg){
if(msg.length() == 14){
if(msg.substring(0, 1).equals("a5") && msg.substring(2, 3).equals("5a") ){
//Determine tpye
if(msg.substring(4, 5).equals("0b")){
//Type = 05
if(msg.substring(6, 7).equals("05")){
if(msg.substring(8, 15).equals("0b")){
}
}
}
else if(msg.substring(4, 5).equals("6b")){
//Type = 05
if(msg.substring(6, 7).equals("05")){
if(msg.substring(8, 15).equals("0b")){
}
}
}
else if(msg.substring(4, 5).equals("4b")){
// ...
}
else if(msg.substring(4, 5).equals("ab")){
// ...
}
else System.out.println("Error: telegram type");
}else System.out.println("Error: Sync Bytes.");
}else System.out.println("Error: Telegram length.");
}
But I want to avoid all those nested ifs and the redundant code that comes with them.
Any ideas on how to handle the string in a more efficient way?
Thanks!
first as I said in the comments don’t convert to string when you don’t need to
you can invert the guard causes and put an early return there to avoid those indents
also a switch on top level might be prudent as this is more readable then if-else cascade (less prone to typos)