2011-03-01 104 views
1
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

您确定只需要添加该函数吗?对于通用功能,通常功能将更为明智。如果可以说,如果你有重复的代码,你想放在一个函数中,它会对你更有用。 – bits 2011-03-01 06:38:49

+0

嗯...我可以没有它...但我会在整个项目中有这样的补充..是啊..你是对的... – 2011-03-01 06:42:15

+0

啊,这是一个测试。我已更正(格式化)您的正确答案。但是,说实话,我没有看到你的正确答案与你正确的问题相符......最初你问了一个方法的建议,把某些东西分配给'result [5]'。您的正确答案甚至不使用代码片段中的变量。 – 2011-03-01 09:23:27

回答

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可读性效果

+0

private String createCheckSum(byte [] byteHolder,int startIndex,int endIndex){ \t byte [] byteToCompute = byteHolder; \t int sum = 0; \t for(int i = startIndex; i <= endIndex; i ++){ \t \t sum + = Integer.valueOf(byteToCompute [i]); \t} return Integer.toHexString(sum); } – 2011-03-01 08:57:30