Roberto Júnior
Roberto Júnior

Reputation: 95

How to implement sorting to a DAO method?

This question was made 3 years ago here by another person but it didn't have an final answer: Specify Ordering to a DAO Method

My question is this same. I have a class Student and a class StudentDAOImpl which implements DAO. How can I tell my method getAll that I want all the students ordered by name without coupling the caller to a specific implementation. I wonder several ways to do it, but I would like to know what's the best practise.

Thank you very much for your kind attention.

public class Student{
    private int id;
    private String name;

    public Student() {
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

}

public class Student{} 

public interface StudentDao{ 
    public LinkedList<Student> getAll(Student s, StudentSortCriterion sortBy); 
} 

public class StudentDaoImpl implements StudentDao{ 
     getAll(...){implementation/SQL Statement}
} 

Upvotes: 1

Views: 1650

Answers (1)

Durandal
Durandal

Reputation: 20069

Look at this abstractly, you need to pass in information how to sort. This can be designed in a number of ways, but to keep it simple, the properties that can be sorted by are directly tied to the student class; so why not define constants for the sortable properties?

The DAO needs to have intimate knowledge of the student class anyway (since it has to know how to create them), so it can respond to parameters defined by the student class:

class Student {
    public static enum SortCriterion {
        ID,
        NAME
    }
    // ...
}

Collection<Student> getAll(SortCriterion sortBy, boolean descending) {
    switch (sortBy) {
    }
}

This couples the DAO to student (no harm in that, its already coupled), but the DAO user doesn't need to know how sorting is actually implemented.

But for any normal purpose, I'd rather not have the DAO implement sorting; if you getAll() the students anyway, why not use a simple plain Comparator, maybe nicely embedded into Student:

class Student {
    public static interface Order {
        public final static Comparator<Student> ID = new Comparator() {
            // implemetation
        }
    }
}

The only point in having the DAO sort would be if it returns a lazy collection backed by a database result set. But if the result set is that large, then why would you use getAll()?

Point for thought: whats the use case for a sorting DAO?

Upvotes: 3

Related Questions