Is there any way to reduce the amount of code?

Gvidas Pranauskas :

I have been doing a project on my studies, it looks fine, but I want to make it as good as possible. I have two separate JSON files, containing Users and Actions. I need to extract that data and do some work with it. But the question is about getting that data. I have a class called DataReader that has two methods - readUsers and readActions.

public class DataReader {
    Gson gson = new GsonBuilder().setDateFormat("MM.dd").create();

    public ArrayList<Action> readActions(String fileName)
            throws JsonIOException, JsonSyntaxException, FileNotFoundException {
        Type actionsArrayList = new TypeToken<ArrayList<Action>>() {
        }.getType();
        return gson.fromJson(new FileReader(fileName), actionsArrayList);
    }

    public HashMap<Integer, User> readUsers(String fileName)
            throws JsonIOException, JsonSyntaxException, FileNotFoundException {
        Type usersHashMap = new TypeToken<HashMap<Integer, User>>() {
        }.getType();
        return gson.fromJson(new FileReader(fileName), usersHashMap);
    }
}

As you can see, those two methods do pretty much the same thing, the difference is only the type of object it returns and gets from that JSON file.

So is there any possibilities to make a method like readData that would get only the fileName parameter and sort the things out itself to reduce the amount of code?

Jason :

You need to close that Reader, specifically your FileReader object you're creating. You also don't need to define Type as a local variable since it's unnecessary. Just inline it. You can do the same for the other method.

        public List<Action> readActionsSimplified(String fileName) throws IOException {
            try (Reader reader = new FileReader(fileName)) {
                return gson.fromJson(reader, new TypeToken<List<Action>>() {}.getType());
            }
        }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=169966&siteId=1