Java Design – Making DAOs Independent of Each Other

daodesignjava

I have these two classes (Getter/Setter/Constructor omitted):

public class Company {
    private String name;
    private String adress;
    private List<Employee> employees;
    private Uuid id;
}

public class Employee {
    private String name;
    private int age;
    private Uuid id;
}

The two entities and their relationship are modeled in a relational database using the tables COMPANY, EMPLOYEE and EMPLOYMENT.

Now I want to write the DAO classes to manage persistance of the two entities and their relationship. The easy way would be making a DAO for each one and have the CompanyDao use the EmployeeDao internally. But according to some Stackoverflow answers I've read, this is a design smell and should be refactored into service methods which use the DAOs without them having to depend on each other.

This is the way I would implement this service method:

public class DBService {
    public DBService(CompanyDao companyDao, EmployeeDao employeeDao,
                     EmploymentDao employmentDao) { ... }

    public Company findCompany(Uuid companyId) {
        Company company = companyDao.find(companyId);
        List<Uuid> employeeIds = employmentDao.findEmployeeIds(company.getId());
        for(Uuid employeeId : employeeIds) {
            company.addEmployee(employeeDao.find(employeeId));
        }
    }
}

Is this a good way to do this? Or should the EmployeeDao have a findByCompany(Uuid companyId) method?

Info: I already asked a smiliar question on Stackoverflow, but the only answers I got was "Use an ORM tool". I know that something like Hibernate would manage all of the persistance for me, but I would like to know how to do this by hand.

Best Answer

The easy way would be making a DAO for each one and have the CompanyDao use the EmployeeDao internally.

Due to no link to StackOverflow has been shared, I just want to mention why is code smell.

In short:

  • it would introduce undesirable coupling. Potentially one of the DAOs would end up subordinated to the other.

  • It has all the recipes for a circular dependency. See also Circular references.

Regarding to the code (the exmaple of DBService)

Is this a good way to do this?

So far, the code is at the doors of the well known Repository pattern (despite the actual name) which is broadly adopted by the community. You will find many references to the pattern looking for DDD.

The Repository pattern introduced in Eric Evans' DDD, has nothing to do with the implementation details, so the implementation will vary according to the specific requirements and needs.

What doesn't vary is the concept. The purpose.

So, based only in the info you provide, I would say that you are doing fairly good.

Related Topic