我有两种用Java编写的方法:
npm cache clean --force
public void fillRect(float x,float y,float width,float height,Color color) {
int xi = mapX(x);
int yi = mapY(y);
int heightf = mapHeight(height);
int widthf = mapWidth(width);
if (xi + widthf > pixelWidth){
widthf -= xi + widthf - pixelWidth;
}
if (yi + heightf > pixelHeight){
heightf -= yi + heightf - pixelHeight;
}
if (xi < 0) {
widthf += xi;
xi = 0;
}
if (yi < 0) {
heightf += yi;
yi = 0;
}
for (int xx = xi; xx < xi + widthf; xx++){
for (int yy = yi; yy < yi + heightf; yy++){
// here is the difference between the other method
setPixel(xx,yy,color);
}
}
}
我习惯于编写类似validateBoundary(float * x,float * y,float * width,float * height)这样的方法:void包含'if-statements'并调用它,但显然这会成功'不会发生在Java中。 此类问题的解决方案是什么?我们可以编写一个methode validateBoundaryWidthf(xi,widhtf,pixelWitdth)来返回widthf的新值。但类似这样:
public void fillRect(float x,float transparency,Color color) {
int xi = mapX(x);
int yi = mapY(y);
int heightf = mapHeight(height);
int widthf = mapWidth(width);
if (xi + widthf > pixelWidth){
widthf -= xi + widthf - pixelWidth;
}
if (yi + heightf > pixelHeight){
heightf -= yi + heightf - pixelHeight;
}
if (xi < 0) {
widthf += xi;
xi = 0;
}
if (yi < 0) {
heightf += yi;
yi = 0;
}
for (int xx = xi; xx < xi + widthf; xx++){
for (int yy = yi; yy < yi + heightf; yy++) {
// here is the difference between the other method
// this Method is slower then setPixel()
plot(xx,transparency,color);
}
}
}
无法通过此方法解决,因为只有一个返回值。当然,我可以创建一个具有widthf和xi属性的POJO,而不是返回this,但是我认为这对于cpu /内存而言代价很高。那么解决此重复代码问题的正确方法是什么?