Avoid DD anomalies

I have this problem called out by PMD (static code analyzer) more often that I would like, and would like to know how someone with more experience than me would write it. My code is functional but I find it inelegant, so I want to know how other programmers would write this piece.

The case is, in a network/IO petition I may or may not get a result from, but my parent method is not null-proof so I always have to return something. I also don’t like several returns on a method.

public String getBingLocation(Coordinate... data)
{
    String response = "Not Retrieved";
    final Coordinate location = data[0];
    JSONObject locationData;
    try {
        locationData = NetworkManager.getJSONResult(ApiFormatter
                .generateBingMapsReverseGeocodingURL(location.Latitude, location.Longitude));
        if (null != locationData) {
            final String address = this.getAddressFromJSONObject(locationData);
            response = address;
        }
    } catch (final ClientProtocolException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        return response;
    } catch (final JSONException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        return response;
    } catch (final IOException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        return response;
    } finally {
        location.Street = response;
    }
    return response;
}

Other example:

public static Object loadObject(final String fileName, final Context context) {
    Object object = null;
    try {
        ObjectInputStream objectInputStream = null;
        try {
            final FileInputStream fileStream = context.openFileInput(fileName);
            objectInputStream = new ObjectInputStream(fileStream);
            object = objectInputStream.readObject();
        } catch (final ClassNotFoundException catchException) {
            LoggerFactory.consoleLogger().printStackTrace(catchException);
        } catch (final ClassCastException catchException) {
            LoggerFactory.consoleLogger().printStackTrace(catchException);
        } catch (final Exception catchException) {
            LoggerFactory.consoleLogger().printStackTrace(catchException);
        } finally {
            if (objectInputStream != null) {
                objectInputStream.close();
            }
        }
    } catch (final IOException catchException) {
        LoggerFactory.consoleLogger().printStackTrace(catchException);
    }
    return object;
}

3

Part of the problem is your functions have more than one responsibility. They are both getting a result and handling errors. You’re also getting unnecessarily hung up trying to avoid multiple return points, which is a vestigial practice from C programming where it can cause memory leaks. You should use multiple returns if it clarifies your code, especially in short functions. I’m also guessing that your logging code is getting repeated all over the place. If you separate those concerns and try to avoid repeating yourself, you get something like this:

public JSONObject getLoggedJSONResult(String api)
{
    try {
        return NetworkManager.getJSONResult(api);
    } catch (final ClientProtocolException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
    } catch (final JSONException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
    } catch (final IOException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
    }

    return null;
}

public String getBingLocation(Coordinate... data)
{
    final Coordinate location = data[0];

    JSONObject locationData = getLoggedJSONResult(
       ApiFormatter.generateBingMapsReverseGeocodingURL(
          location.Latitude, location.Longitude));

    if (null == locationData) {
        return "Not Retrieved";
    } else {
        return this.getAddressFromJSONObject(locationData);
    }
}

As a general principle, most DD anomalies can be fixed by splitting the function. It’s mostly a matter of figuring out where to split it.

Your second example is trickier. That sort of situation is why try-with-resources statements were invented. You can use an early return to eliminate the DD anomaly on object, but you’re not going to be able to do much about objectInputStream without a try-with-resources.

3

As for your first example, I’d write it like this :

public String getBingLocation(Coordinate... data)
{
    String response;
    final Coordinate location = data[0];
    JSONObject locationData;
    try {
        locationData = NetworkManager.getJSONResult(ApiFormatter
                .generateBingMapsReverseGeocodingURL(location.Latitude, location.Longitude));
        if (null != locationData) {
            final String address = this.getAddressFromJSONObject(locationData);
            response = address;
        } else {
            response = "Not Retrieved";
        }
    } catch (final ClientProtocolException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        response = "Not Retrieved";
    } catch (final JSONException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        response = "Not Retrieved";
    } catch (final IOException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        response = "Not Retrieved";
    } finally {
        location.Street = response;
    }
    return response;
}

The main idea is to avoid overriding a value without reading it (this means one assignement is useless because never read).

A solution is to have a single return statement, and return a non initialized variable. Then go through all possible path and check that a value is always assigned, and no more than once.

8

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật