今天和同时讨论问题,他说他的写法比我好,但从逻辑的角度来讲,我觉得我写的逻辑没有问题,而且更简洁,大家来帮忙看一下到底有什么区别?
这是我写的:
private static int statusBarHeight = DeviceUtils.fromDipToPx(ApplicationContext, 20);
public static int getStatusBarHeight(Activity activity) {
if (activity == null||activity.isFinishing) {
return statusBarHeight;
} else {
Rect rectgle = new Rect();
Window window = activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
statusBarHeight = rectgle.top;
return rectgle.top;
}
}
这是我同事写的:
private static boolean USE_CUSTOM_STATUS_BAR_HEIGHT = true;
private static int statusBarHeight = -1;
public static int getStatusBarHeight(Activity activity) {
if (statusBarHeight != -1 && !USE_CUSTOM_STATUS_BAR_HEIGHT){
return statusBarHeight;
}
try {
if (activity != null && !activity.isFinishing()){
Rect rect = new Rect();
Window window = activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rect);
statusBarHeight = rect.top;
USE_CUSTOM_STATUS_BAR_HEIGHT = false;
}
} catch (Exception e){
LOGGER.d(TAG,"getStatusBarHeight Exception",e);
}
if (USE_CUSTOM_STATUS_BAR_HEIGHT){
statusBarHeight = DeviceUtils.fromDipToPx(ApplicationContext, 20);
}
return statusBarHeight;
}
同事对异常的处理还是有必要的。不过乍一看的确有点乱,除去这点,你的代码更容易懂。
不过既然有两个类变量出现在方法的判断语句里,可能是为了之后业务扩展的时候能够用上。