java - 如何通过使用对 InOrder 的调用来简化/更具可读性(下面的代码)
问题描述
如何通过使用对 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
可以重构以定义最小值和最大值,然后重用 modified 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));
}
推荐阅读
- netsuite - 将交易链接到子列表记录
- javascript - 如何在模态(弹出)外部按下时消失
- html - 如何使用 CSS 突出显示文本中带有圆框的一些短语?
- android - 识别视图所属的片段
- arrays - React.js:来自 API 调用的图像未在浏览器中呈现
- docker - gRPC-Node 错误:位置 0 处 JSON 中的意外令牌 u
- android - 那么有没有办法在 gradle 中获取基于 product.flavor 的变量来执行任务?
- kubernetes - 添加选择器后,“选择器”与模板“标签”不匹配 - Azure DevOPs
- python - 创建具有顺序名称的多个数据框
- vb.net - Zxing.Net 读取二维码