I have a Request class based on the same Entity in my Domain. It currently only has property definitions. I’d like to add a method for checking a duplicate Request which I’ll call from my controller. Should I add a method called CheckDuplicate in the Request class? Would I be violating the SRP? The method will need to access a database context to check already existing requests. I’m thinking creating another class altogether for this logic that accepts a datacontext as part of its constructor. But creating a whole new class for just one method seems like a waste too. Any advice?
1
I’d go ahead and create it.
As you mentioned, adding a new responsibility to what’s currently a DTO would violate the SRP. The question arises, what happens when the next requirement comes along? Would you add another method? What happens when you add a new attribute to the DTO? Would that necessary change add the risk of messing up your duplicate checking logic? Part of the idea of the SRP is that there should only be one reason to modify your class.
Moreover, a DuplicateChecker may turn out to be useful for other domain classes as you move forward.
It’s not like classes are particularly expensive.
As per the question, you just need to validate if the entry is a duplicate? If thats the case that is like validation, so you can go ahead and create a method isValid() or isDuplicate() which would return a boolean value on checking the validations that you have.
2