Reputation:
I'm learning DDD (Domain Driven Design) and reading Clean Architecture. I found out about Value Objects and have been reading more about them and have implemented some in my application which could be found https://gist.github.com/Tyler0722/73ec826be814b8e54b9f6ae6ae836409.
Value Objects are created by calling the factory method which performs validation and follows the separation of concerns principle. The problem is I have two Value Objects where the validation logic is duplicated. Username and QuizTitle where the only difference is MAX_LENGTH
which violates the DRY principle. I was wondering if anyone knew anyway I could make this DRY.
Upvotes: 0
Views: 138
Reputation: 51353
If you want to remove repetition you must be very careful.
The first question you should ask yourself is
What is the same and what is different?
Maybe you will find the same or similar structure like
props
If you found out what you think the same is you have to ask yourself more questions:
Do the things that are (look) the same have different responsibilities?
Do they change for the same or for different reasons?"
These are the questions that are about the single responsibility principle. Sometime things look the same by accident. They look the same but are different, because they change of different reasons. If you eliminate the "duplication" in this case you will have more problems then you solve.
E.g. if you consolidate the validation logic of QuizTitle
and Username
into one method and later you get a change request for the QuizTitle
validation you can easily break the validation behavior of Username
. I guess it should not change if the QuizTitle
validation changes.
You might also want to read the good article by Martin Fowler about Avoiding Repetition
Upvotes: 1
Reputation: 104
Well, I agree with Darius Mann, that these value objects have similar business logic is ocasional, if they are different concepts in your app, keep them separated and independently, it is my opinion.
Upvotes: 1
Reputation: 733
My suggestion is to not do it. In this case it's just not necessary.
But if you want to do it anyway, you can build a Validation class with static functions. At my work we use Webmozart/Assert and if you take a look at its implementation you will understand what I mean. In my opinion there are very handy. Also you can pass the MAX_LENGHT
as an argument.
Upvotes: 2