Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I refactor these wrapper methods to get rid of duplicated code?

The following two methods are used to wrap deserialization using Google Gson:

public static <T> T Deserialize(String jsonData, Type t) {
    T obj = null;

    try {
        obj = new Gson().fromJson(jsonData, t);
    } catch (Exception e) {
        Log.e(DEBUG_TAG, e.getMessage());
    }

    return obj;
}

public static <T> T Deserialize(String jsonData, Class<T> toClass) {
    T obj = null;

    try {
        obj = new Gson().fromJson(jsonData, toClass);
    } catch (Exception e) {
        Log.e(DEBUG_TAG, e.getMessage());
    }

    return obj;
}

They are almost identical, but I can't figure out a smart way to get rid of the duplicated code.

Any suggestions?

like image 429
aspartame Avatar asked Jan 28 '26 13:01

aspartame


1 Answers

Class implements the interface Type, so it looks like only having the first method should be sufficient.

EDIT: actually it looks like these methods are implemented separately for a reason. At least read the javadoc to understand why before refactoring. Thanks to home for pointing this out.

like image 92
Paul Bellora Avatar answered Jan 30 '26 02:01

Paul Bellora