Search code examples
oopdaosolid-principles

DAOs and SOLID design principles


I've been reading up about SOLID design principles, currently looking at the 'Single Responsibilty Principle', but I was curious on the use case for this principle. At the company I work at, we have DAOs which have methods of read, insert & update to manage a record in the database.

Would something like this break the 'Single Responsibilty Principle'? If so, would you then need classes for each inserting, reading & updating?

Example DAO:

class UserDAO {
    public function read(where: object) {
        // read code
    }

    public function insert(user: User) {
        // insert code
    }

    public function update(user: User) {
        // update code
    }
}

Solution

  • Single Responsibility Principle states that

    A class must have only one reason to change.

    Let's say we have UserDAO with methods read, save, delete, update. So, this class will only be changed when there will be changes related to User. So, it has a single reason for a change i.e User.

    So, I think it doesn't violate SRP (Single Responsibility Principle) if implemented correctly.

    void save(User user){
    //user related logic
    }
    
    void save(User user){
    // user related logic and address logic encapsulated inside address class
    //eg: address.getAddress(user.getId);
    }
    

    In the above case, it doesn't violate SRP because the save method will only be changed when there is a change in User logic. The address logic is handled by Address class per se.

    For eg: if save method looks like:

    void save(User user){
    Address address = new Address();
     //Address logic
     Payment payment = new Payment();
     //Payment logic
    }
    

    In the above code, any changes in Address or Payment logic will make this DAO save method change as well. It violates SRP.

    So, it really depends on the implementation.