Thanks for getting the time to read and interact !
No hate at hall, your solution is actually straightforward and decent. I use it a lot...
It depends on the context, the cons of putting your "specifications" inside your class are the following:
- SOLID principles advise you to not edit existing code and rather add and extend functionalities (like building Legos)
- If your specifications does depend on the context, for example if in our use case, the UserRole may not be in the User object. You will need to parameterize this function.
But what if in some other place in your code you have another validation to test?
So as your code scale, your class will be huge and full of validation code and that does take you an effort to understand your code flow and where each specification is called.
- Reusability
Because your Specification may be type agnostic, you can have common rules for different classes and behaviors.
At the end of the day, it depends on the context. I use your solution a lot if I have a "general truth" functionality or behavior. That surely belongs to the object itself and does not and will not change in the future so yes.
I hope you found my response useful !