【问题标题】:How to refactor this If/else statement in a try/catch block?如何在 try/catch 块中重构此 If/else 语句?
【发布时间】:2023-09-14 11:01:01
【问题描述】:

我想知道是否有更好的方法来编写这段代码:

private void getLatitudeAndLongitudeFromZipcode() {
        String zipcode = mSharedPreferences.getString("Zipcode", "");

        try {
            List<Address> address = geocoder.getFromLocationName(zipcode, 1);
            if ((address != null ? address.size() : 0) > 0) {
                Address first = address.get(0);
                mLatitude = first.getLatitude();
                mLongitude = first.getLongitude();
                mCurrentLocationName = getLocationAsName();
                mSharedPreferences.edit().putLong("oldLat", Double.doubleToRawLongBits(mLatitude))
                        .apply();
                mSharedPreferences.edit().putLong("oldLong", Double.doubleToRawLongBits(mLongitude))
                        .apply();
            } else {
                getOldZipcodeLocation();//duplicate method call
            }
        } catch (IOException e) {
            getOldZipcodeLocation();//duplicate method call
            e.printStackTrace();
        }
    } 

基本想法是,如果他们没有互联网并且抛出异常,我想从存储中获取旧坐标。但是,如果他们当前位于不给他们坐标的地方,我也想获得旧坐标。例如,如果地理编码器返回 null。困扰我的是 else 块和 catch 块中的重复方法调用。有什么办法可以让这段代码更干净?我也会接受任何其他提示!

【问题讨论】:

  • (1) 去掉address 为空或为空的测试。 (2) 在同一个catch 块中捕获空指针异常或索引超出范围异常。 (3) 丢失“打印堆栈跟踪”,尽管普通 IDE 认为,没有法律规定你必须这样做。 // 这是否“更好”是一个见仁见智的问题;我个人会保持原样。
  • 如果您有 1 行重复行,我真的看不出问题...是什么导致了 IOException
  • address 为空或为空时,您可以抛出IOException
  • @AlbertoSinigaglia 异常可能是由很多事情引起的。例如,如果没有互联网。
  • @user16632363 和 saka1029 我会这样做的

标签: java android try-catch catch-block


【解决方案1】:

是的,您可以,首先通过IOException 分别获取address,然后在您的if..else 语句中使用address。就是这样。

 private void getLatitudeAndLongitudeFromZipcode() {

    String zipcode = mSharedPreferences.getString("Zipcode", "");
    List<Address> address = null;
    try {
        address = new Geocoder(this).getFromLocationName(zipcode, 1);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if ((address != null ? address.size() : 0) > 0) {
        Address first = address.get(0);
        mLatitude = first.getLatitude();
        mLongitude = first.getLongitude();
        mCurrentLocationName = getLocationAsName();
        mSharedPreferences.edit().putLong("oldLat", Double.doubleToRawLongBits(mLatitude))
                .apply();
        mSharedPreferences.edit().putLong("oldLong", Double.doubleToRawLongBits(mLongitude))
                .apply();
    } else {
        getOldZipcodeLocation();

    }
}

【讨论】: