有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何用泛型和外部类重构helper方法?(Java Android)

我正在构建一个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) 个答案

  1. # 1 楼答案

    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)
    

    否则,我看不到一个简单的方法来将它们整合到一个方法中,因为它们似乎需要不同的参数