![](/img/trans.png)
[英]How Can I Further Simplify the InOrder code by making just one call to OutofOrder?
[英]How can I simplify/more readable this by using calls to InOrder (code below)
如何通過調用 InOrder(下面的代碼)來簡化/提高可讀性。 代碼的目的是檢查一個 Rectangle 是否包含一個 Point。 下面是首先是 Rectangle 類的代碼,然后是 InOrder 類。 我很難找到一種使代碼更具可讀性的方法,我想以盡可能最好的方式簡化它。
// Construct a rectangle from two arbitrary points
public class Rectangle {
private int x1;
private int y1;
private int x2;
private int y2;
public Rectangle(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public boolean contains(int x, int y) {
if(x1 <= x2) {
if(x1 <= x && x <= x2) {
if(y1 <= y2) {
return y1 <= y && y <= y2;
} else {
return y2 <= y && y <= y1;
}
}
} else {
if(x2 <= x && x <= x1) {
if(y1 <= y2) {
return y1 <= y && y <= y2;
} else {
return y2 <= y && y <= y1;
}
}
}
return false;
}
}
public class InOrder {
//Don't change this
public boolean OutOfOrder(int n1, int n2, int n3) {
return (n1 > n2) || (n2 > n3);
}
//The original and messy InOrder, leave this as an example of what not to do
public boolean inOrder(int n1, int n2, int n3) {
if (n2 > n1) {
if (n3 > n2) {
return true;
} else {
return false;
}
} else if (n2 == n1) {
if (n3 == n1) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
方法inOrder
可以這樣重構:
// InOrder
public static boolean inOrder(int min, int n, int max) {
if (n > min) {
return max > n;
} else if (n == min) {
return n == max;
}
return false;
}
這將是罰款作出inOrder
靜態的,以避免不必要的創作InOrder
實例。
然后可以重構Rectangle::contains
以定義最小值和最大值,然后重用修改后的InOrder::inOrder
:
// class Rectangle
public boolean contains(int x, int y) {
int minx = x1 < x2 ? x1 : x2;
int maxx = x1 > x2 ? x1 : x2;
int miny = y1 < y2 ? y1 : y2;
int maxy = y1 > y2 ? y1 : y2;
return InOrder.inOrder(minx, x, maxx) && InOrder.inOrder(miny, y, maxy);
}
也可以使用靜態進口Math.min
/ Math.max
方法以及inOrder
,然后Rectangle::contains
可改寫為一行代碼:
import static java.lang.Math.min;
import static java.lang.Math.max;
import static InOrder.inOrder;
// class Rectangle
public boolean contains(int x, int y) {
return inOrder(min(x1, x2), x, max(x1, x2)) && inOrder(min(y1, y2), y, max(y1, y2));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.