【发布时间】:2011-11-11 01:19:07
【问题描述】:
我有一个函数作为矩形类的一部分(其中的点是不可变的双精度数,因此矩形也是不可变的),我需要提供一种计算与另一个矩形的交点的方法。该方法将返回计算出的相交矩形。但是,如果对象根本不相交,则会引发异常。
我能想到的抛出异常的唯一替代方法是返回一个称为 RectIntersection 的特殊类型,调用者可以轮询该对象以查看交集计算是否失败。比起抛出异常,我更喜欢这样,但它让我需要测试对这个函数的每次调用以检查新创建的对象。
对于处理这种情况还有其他建议吗?
static public DoubleRect calcRectIntersection(DoubleRect r1, DoubleRect r2) throws DoubleRectException {
if((r1.topLeft.x > r2.bottomRight.x || r1.bottomRight.x < r2.topLeft.x || r1.topLeft.y > r2.bottomRight.y || r1.bottomRight.y < r2.topLeft.y) != true)
{
return new DoubleRect(r1.topLeft.x >= r2.topLeft.x ? r1.topLeft.x : r2.topLeft.x,
r1.topLeft.y >= r2.topLeft.y ? r1.topLeft.y : r2.topLeft.y,
r1.bottomRight.x <= r2.bottomRight.x ? r1.bottomRight.x : r2.bottomRight.x,
r1.bottomRight.y <= r2.bottomRight.y ? r1.bottomRight.y : r2.bottomRight.y);
}
else throw new DoubleRectException("Call to calcRectIntersection() could not complete since the two rectangles did not intersect");
}
【问题讨论】:
-
您不应该对正常控制流使用异常。两个不相交的矩形对我来说听起来像是正常的控制流。为什么不返回一个大小为零的矩形?
-
作为参考,
if ((humongously long condition) != true)的可读性非常糟糕。推荐if (!(humoungously long condition)),或者更好的是if (logical inversion of humongously long condition)。 -
@cHao 说的:
if (condition != true)也和if (!condition)一样。 -
我从 C 移植这个。原来是 !condition。 Java 似乎不喜欢原来的语法。
-
并考虑使用
max函数来处理大量三元组。
标签: java exception-handling error-handling