有的时候,我们可以利用java的异常来代替一if判断,
以下面这代码片段为例,modifyFocus方法中为了防止List下标访问越界,用了if判断语句来判断下标是否有效。
public class AnnotationCanvas{
private List<AnnRectUI> rects;
/**
* 从rects中找到焦点对象(focus为true),没有找到则返回-1
*/
private int getFocus(){
for(int i=0;i<rects.size();++i)if(rects.get(i).focus)return i;
return -1;
}
/**
* 修改焦点矩形
* @param rect
*/
public void modifyFocus(Rectangle rect){
int focusIndex = getFocus();
// 没找到焦点对象则返回
if(focusIndex <0)return;
rects.get(focusIndex).setBounds(new AnnRectUI(rect.x,rect.y,rect.width,rect.height).unZoom(zoom));
drawAction=refreshAll;
}
}
我写代码有个习惯,就是if条件判断分支越少越好,能不用if判断的就尽量避免之,所以我利用java.lang.IndexOutOfBoundsException异常代替这个判断语句:
重写的modifyFocus方法如下,还省去临时变量focusIndex的定义:
/**
* 修改焦点矩形
* @param rect
*/
public void modifyFocus(Rectangle rect){
try{
rects.get(getFocus()).setBounds(new AnnRectUI(rect.x,rect.y,rect.width,rect.height).unZoom(zoom));
drawAction=refreshAll;
} catch (IndexOutOfBoundsException e) {}
}