减少代码..功能

时间:2011-03-01 06:35:27

标签: java function hex

public final byte[] getParam(String commandName,String memLocation,String dataId){
    byte[] result = new byte[9];
    result[0] = START_FRAME.getBytes()[0];
    result[1] = START_FRAME.getBytes()[0];
    result[2] = Integer.toHexString(commandMap.get(commandName)).getBytes()[0];
    result[3] = Integer.toHexString(dataIdMap.get(dataId)).getBytes()[0]; 
    result[4] = Integer.toHexString(locationMap.get(memLocation)).getBytes()[0];

    result[5] = Integer.toHexString(commandMap.get(commandName) + dataIdMap.get(dataId) + locationMap.get(memLocation)).getBytes()[0];

    result[6] = END_FRAME.getBytes()[0];
    result[7] = END_FRAME.getBytes()[0];
    result[8] = END_OF_LINE.getBytes()[0];
    //Check sum -> {{d10d}}
    return result;
}

如何减少结果[5]向函数调用添加值...

我可以这样通过吗?

    public static final byte[] createCheckSum(byte[] paramsToBeAdded){
            byte[] result = paramsToBeAdded;
            ............
            ........... etc
    return result[0] + result[2];
}

正确答案:

private String createCheckSum(byte[] byteHolder,int startIndex,int endIndex){
     byte[] byteToCompute = byteHolder;      
     int sum = 0;     
 for(int i=startIndex; i<=endIndex; i++){    
      sum += Integer.valueOf(byteToCompute[i]);     
 }    
 return Integer.toHexString(sum);     
}    

1 个答案:

答案 0 :(得分:1)

看起来你正在使用一些类成员变量。在这种情况下,函数会使代码更具可读性(选择一个显示方法正在做的好名称):

private String computeSomething(String commandName,String memLocation,String dataId) {
  int  commandValue = commandMap.get(commandName);
  int  dataValue    = dataIdMap.get(dataId);
  byte memValue     = locationMap.get(memLocation)).getBytes()[0];
  return Integer.toHexString(commandValue + dataValue + memValue);
}

这样称呼:

result[5] = computeSomething(commandName, memLocation, dataId);

(并替换名称computeSomething以获取可读性效果