rstml
rstml

Reputation: 308

Accessing external source from DAO implementation

Consider following simple DAO example:

public abstract class DAOFactory
{
    public abstract AccountDAO getAccountDAO();
    public abstract MessageDAO getMessageDAO();

    public static DAOFactory getDAOFactory(int whichFactory)
    {
        // depending on whichFactory
        return new SpecificDAOFactory();
    }
}

public interface AccountDAO
{
    public void add(Account account);
    public void delete(Account account);

    public int authenticate(Account account); // another source!
}

public interface MessageDAO
{
    //other methods
}

All above mentioned methods have to be implemented using the same data source, except AccountDAO.authenticate().

Authentication information available at the other data source and should be pluggable in turn (e.g. could be SQL, LDAP, etc.). At the same time, authentication data source is independent from the DAO data source, i.e. whichFactory could be A, B or C while authentication source X or Y.

From interface design point of view, authenticate fits nicely into AccountDAO. But from implementation point of view I feel uncomfortable.

What would be better design which will provide clear data access layer interface and implementation?

Upvotes: 0

Views: 205

Answers (1)

Perception
Perception

Reputation: 80623

Data access objects tend to follow the same structure and pattern, so you might want to consider creating a higher level class encapsulating this shared logic. I will highlight with an example, please note that I am omitting interfaces because I rarely find them useful at the DAO level.

Base DAO class:

public class BaseDAO<T> {
    private Class<T> clazz;

    public BaseDAO(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    public T find(Long id) { ... }

    public List<T> findAll() { ... }

    public T create(T entity) { ... }

    public T update(T entity) { ... }

    public void delete(T entity) { ... }
}

A derived DAO for a hypothetical Account object

public class AccountDAO extends BaseDAO<Account> {
    public AccountDAO() {
        super(Account.class);
    }

    public List<Account> findByAccountStatus(String status) { ... }
}

As you can see, you greatly minimize the amount of code in derived DAO's. With this setup you do not need to use a factory, just initialize your DAO's directly.

As far as your second question, I would not place an authenticate method on the Account DAO. Authentication should be dealt with at a higher level of abstraction (fits very nicely in the service layer), even if it eventually retrieves some information from the data access layer.

Upvotes: 1

Related Questions