如果被执行return语句后的dsLen
值是无关紧要的,你的代码可以简化为
if (dsLen >= 4) {
ds.longitude = buff.readInt();
}
if (dsLen >= 8) {
ds.latitude = buff.readInt();
}
if (dsLen >= 10) {
ds.velocity = buff.readShort();
}
return ds;
的代码的其余部分可能也得到改善。它看起来像longitude
,latitute
和velocity
是public
字段ds
。代替它们来封装它们可能是一个更好的主意。
如果您确实需要在代码的其他部分更改ds
的状态,请使用setter。
如果您不需要改变状态的ds
,考虑做田野final
,在构造函数中为它们分配和方法在你的问题返回DS'类型的新对象,
public final class WhateverType {
private final int longitude;
private final int latitude;
private final short velocity;
public WhateverType(int longitude, int latitude, short velocity) {
this.longitude = longitude;
this.latitude = latitude;
this.velocity = velocity;
}
// rest of the code
}
然后您的方法中的代码可能看起来像:
int longitude = -1; // or whatever default values you're assigning
int latitude = -1;
short velocity = -1;
if (dsLen >= 4) {
longitude = buff.readInt();
}
if (dsLen >= 8) {
latitude = buff.readInt();
}
if (dsLen >= 10) {
velocity = buff.readShort();
}
return new WhateverType(longitude, latitude, velocity);
* *之前的代码是什么? – Kayaman