8 ms·
I love this response because it's helping me formulate my objections a little better. I don't think a User class should be directly validating the zip lives in
by ninkendo 9y ago
I love this response because it's helping me formulate my objections a little better.
I don't think a User class should be directly validating the zip lives inside the state in some sort of setter method... which one do I set first to make it work? It looks like once I change one I can't change the other any more... I'd need to have a method that changes both at once. And this is a perfect example of your data not matching your encapsulation: your encapsulation would want to express that you need to provide a zip/state pair via some setLocation(zip, state) method, which does not correspond to any private property you actually have.
But I definitely would prefer the set,set,set,validate approach more, and I would even say the validate() belongs in a different class altogether, ideally as a side-effect-free standalone method. (Basically, I should be able to set an invalid state and zip property in a vacuum, it's only when I go to validate it that it returns invalid.)
Going further I would implement any form submission system as taking some Validatable interface, where the Validatable object in this case would store your Address object via composition, and would represent the specific logic for validation for these purposes... but it would all live separately from a User struct, which would just be a dumb struct.
- acdha 9y ago> I don't think a User class should be directly validating the zip lives inside the state in some sort of setter method... which one do I set first to make it work? It looks like once I change one I can't change the other any more... I'd need to have a method that changes both at once. The idea I had in mind for that admittedly contrived example was roughly that you'd have an address class and some logic along the lines of setting a field automatically clears the lower-level fields, but that's not really a practical design as much as an illustration of the pattern of having complex logic in a setter. I should note that this isn't my preference, either – either set,set,set,validate or updateLotsOfFields(dataStructure) – but I've seen people who felt otherwise and had reasonable arguments for this kind of behaviour.