1

I have a Dao interface which doesn't have any methods defined.

Then I have multiple classes which implement this interface, like PetDao and HouseDao.

For some of the implementation classes, and some of their methods, I need to do an operation.

Let's say this operation is defined in the Operation class, and the method is doOperation().

PetDao has several methods: Pet selectPet(int petId), void insertPet(PetDto pet), and I only want to call doOperation() for insertPet.

HouseDao has several methods: House selectHouse(int houseId), void deleteHouse(int houseId), and I only want to call doOperation() for deleteHouse.

I cannot modify the Dao interface. Neither of these classes are instantiated manually, they are all injected.

I could change PetDao and HouseDao code to statically call doOperation(). But this would mean that the Dao classes would have another responsibility than the originally intended, and that I would have a big impact on the source code (there are multiple Daos with multiple methods that I need to track).

I cannot use the Decorator Pattern because Dao interface does not have any methods.

Are there other options, besides AOP, to achieve this?

3
  • Why don't you just create a new interface with your doOperation method in it, and have each DTO implement that interface? Commented Jul 9, 2021 at 18:57
  • But this would mean that the Dao classes would have another responsibility than the originally intended -- I'm not particularly concerned about this arbitrary distinction, if your proposed solution actually solves the problem you are having in a reasonably good way. Commented Jul 9, 2021 at 18:59
  • Your question is missing some crucial information. E.g.: "Dao interface does not have any methods" - why? "I have multiple classes which implement this interface" - why do they implement it? "I cannot modify the Dao interface." - why? Commented Jul 10, 2021 at 9:58

1 Answer 1

2

Injecting a class isn't really a violation of the Single Responsibility Principle.

The new logic is encapsulated in your Operation class, that's it's responsibility. Calling a dependency doesn't really change what this class responsibile for.

Something like the below isn't really changing the responsibilities of your DAO class.

(forgive the C# syntax)

public class HouseDao:IDao
{
   public HouseDao(Operation myOperation)
   {
      <snip>
      operation = myOperation;
   }

    <snip>

   public void deleteHouse(int houseId)
   {
      //dostuff
      operation.doOperation()   
   }
}

All that said, if you really need an alternative, implementing this as a Visitor (https://www.baeldung.com/java-visitor-pattern) may be more along the lines of what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.