I wouldn’t. Not from this example anyway. YAGNI is an important paradigm and introducing plenty of classes upfront to implement trivial checks is overengineering…
Classes, functions, methods… pick your poison. The point is to encapsulate your logic in a way that is easy to understand. Lumping all of the validation logic into one monolithic block of code (be it a single class, function, or methods) is not self-documenting. Whereas separating the concerns makes it easier to read and keep your focus without mixing purposes. I’m very-engineering (imo) would be something akin to creating micro services to send data in and get a response back.
Edit: Your naming convention isn’t the best either. I’d expect
UserInputValidator
to validate user input, maybe sanitize it for a database query, but not necessarily an existence check as in the example.
If you go back to my example, you’ll notice there is a UserUniqueValidator
, which is meant to check for existence of a user.
And if you expect a validator to do sanitation, then your expectations are wrong. A validator validates, and a sanitizer sanitizes. Not both.
For the uninitiated, this is called Separation of Concerns. The idea is to do one thing and do it well, and then compose these things together to make your program — like an orchestra.
That’s fair. How would you go about implementing the service? I always love seeing other people’s perspectives. 😊