Let's say I have a social media website. On this website, users can upload several pieces of information about themselves, including their phone number. To implement this, I have a class called
PhoneNumber that represents the users phone number. But phone numbers are optional. I have this
PhoneNumber class which is supposed to guarantee access to a users phone number, but it can't. How do I handle this?
My current approach is to, whenever there's a problem, assign a value to an
error variable inside
PhoneNumber that represents the problem in question (this could be an exception, a string, or an error code, it's irrelevant for this question). I also added a method to
isPhoneNumberAvailable() that should be called before any of the accessors are used. If one of the accessors is called and the user hasn't added their phone number, I throw an
IllegalStateException. But this doesn't seem like a good solution. I'm not sure why, I'm too new at this to explain it, but it seems like this could cause me some problems down the road.
Note that this question is language agnostic, the existence of an
IllegalStateException in Java is purely coincidental.
EDIT: The solution is improving the model. I have guaranteed access to something I can't guarantee access to, which is bad design. My other problem was with the use of an
error variable in class scope but that's beyond the scope of this question. See my follow up question here.