3 ms·
”A somewhat contrived example but say you had a user address with state and zip code values and you wanted to prevent setting a zip code outside of that state.”
by Someone 9y ago
”A somewhat contrived example but say you had a user address with state and zip code values and you wanted to prevent setting a zip code outside of that state.”
So, you’re thinking of an address class that says “I know what zip codes go with what states” _and_ “if you don’t know what zip codes are valid with what states, I’ll throw an exception”? That’s cruel. Changing a user’s address would be quite the challenge, if (s)he moved to a different state (you have to change the state and the zip code in one go)
A better design has some kind of oracle that, given possibly incomplete address info, returns an ‘address’ that you then can atomically set on a user:
user.address = streetMap.find(“123 Main Street, USA”)
- acdha 9y agoNote that it was described as “a somewhat contrived example”. I was just trying to get the idea of a relationship where some people would want to prevent you from setting incompatible values and others might have a separate step. I tend to prefer the latter approach but I've worked with people who felt differently for reasons which I'm unwilling to entirely reject. Both can be made to work[1] and there's enough variation between languages, projects, and environments that I think the choice is at least understandable. 1. To answer your last point: something along the lines of obj.setZip() raising an exception but obj.setState() automatically cleared the related value on a change.