[英]reducing code.. to function
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;
}
how can i reduce the result[5] addition of values to a function call... 我如何减少对函数调用的结果[5]值加法...
can i pass like this ? 我可以这样通过吗?
public static final byte[] createCheckSum(byte[] paramsToBeAdded){
byte[] result = paramsToBeAdded;
............
........... etc
return result[0] + result[2];
}
Correct answer: 正确答案:
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);
}
Looks like your using some class member variables. 看起来像您在使用某些类成员变量。 In that case, a function would make the code a bit more readable (choose a good name that shows what the method is doing):
在那种情况下,一个函数会使代码更具可读性(选择一个好名字显示该方法的作用):
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);
}
call it like this: 这样称呼它:
result[5] = computeSomething(commandName, memLocation, dataId);
(and replace the name computeSomething
for the readabilty effect ) (并为可读性效果替换名称
computeSomething
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.