如何使用泛型和外来类重构辅助方法? (Java Android)

时间:2016-04-16 17:52:27

标签: java android refactoring ormlite

我正在构建一个Android应用程序并使用ORMLite进行SQLite操作,并希望为数据库处理创建帮助程序类。我遇到了大代码重复的问题,但无法弄清楚如何重构它们 如果您有任何想法,请告知 我觉得这个问题是因为缺乏一些基础知识,所以如果你能给我一个建议,关于我应该深入学习哪个主题,那就太棒了!

以下是重构中的代码块需求:

public static BigGoal createBigGoalRecord(String title,
                                          String description,
                                          Dao<BigGoal, Integer> dao) throws SQLException {
    BigGoal bigGoal = new BigGoal(title, description);
    dao.create(bigGoal);
    assignBigGoalEmptyCollection(bigGoal, dao);
    return bigGoal;
}

public static SubGoal createSubGoalRecord(String title, String description,
                                          ObjectiveType type,
                                          Dao<SubGoal, Integer> dao,
                                          BigGoal bigGoal) throws SQLException {
    SubGoal subGoal = bigGoal.createSubGoal(title, description, type);
    dao.create(subGoal);
    assignSubGoalEmptyCollection(subGoal, dao);
    bigGoal.getSubGoals().add(subGoal);
    return subGoal;
}

public static List<BigGoal> getBigGoalList (Dao<BigGoal, Integer> dao) throws SQLException {
    ArrayList<BigGoal> bigGoalList = new ArrayList<>();
    CloseableIterator<BigGoal> iterator = dao.closeableIterator();
    try {
        while (iterator.hasNext()){
            BigGoal goal = iterator.next();
            bigGoalList.add(goal);
        }
    } finally {
        iterator.close();
    }

    return bigGoalList;
}

public static List<SubGoal> getSubGoalList (Dao<SubGoal, Integer> dao) throws SQLException {
    ArrayList<SubGoal> subGoalList = new ArrayList<>();
    CloseableIterator<SubGoal> iterator = dao.closeableIterator();
    try {
        while (iterator.hasNext()){
            SubGoal goal = iterator.next();
            subGoalList.add(goal);
        }
    } finally {
        iterator.close();
    }

    return subGoalList;
}

1 个答案:

答案 0 :(得分:0)

Oracle网站上有关于Java泛型的整个部分:https://docs.oracle.com/javase/tutorial/java/generics/

例如,对于返回实体列表的方法(例如getBigGoalList()),您可以用以下方法替换所有实体:

public static <T> List<T> getEntityList(Dao<T, Integer> dao) throws SQLException {
    ArrayList<T> list = new ArrayList<>();
    CloseableIterator<T> iterator = dao.closeableIterator();
    try {
        while (iterator.hasNext()){
            T item = iterator.next();
            list.add(item);
        }
    } finally {
        iterator.close();
    }

    return list;
}

我不太了解ORMLite是否告诉您相同类型的重构是否适用于在数据库中创建和保存实体的方法。你可能最好不要让这些方法将实体的实例作为参数,而不是采用用于构造实体的所有参数,例如:

createBigGoalRecord(BigGoal item, Dao<BigGoal, Integer> dao)

而不是

createBigGoalRecord(String title, String description, Dao<BigGoal, Integer> dao)

否则我看不到将它们合并为一种方法的简单方法,因为它们似乎需要不同的参数。