I had an interesting discussion at work today regarding how to handle the behavior of a particular function. In our underlying code, we wanted to be able to call a simple ‘getter’ to retrieve the name of some object. However, sometimes the object in question won’t exist, so the question came up of how to act in this case. Since we cannot access this property itself (it’s all handled in underlying C#/C++ code) we couldn’t just reference it’s name directly, and instead needed this ‘getPropertyName()’ function.
We got stuck on two implementations for this – simply return ‘None’, or raise an exception. We discussed this for at least 30 minutes, arguing the pros and cons of requiring a ‘try:except’ block around the call in question versus retrieving the property and using an ‘if’ statement to see if we got the name. However, neither side seemed to really stand out as the ‘best’ option.
After a while I came up with what the team thought was a clever solution to this problem. One of the members of the team is an only child and so I asked them the following question:
What is your sister’s name?
The response to this question wasn’t just awkward silence. It also wasn’t ‘None’. They instead told me that they don’t have a sister. I knew exactly what to do after receiving this response, and so did everyone else.
This, to myself and the team, seemed quite a lot like raising an exception… (perhaps a SisterDoesNotExistException()?) If I was trying to compile a list of siblings and I got that response, I’d have to change my behavior, and that was very similar to the purpose of the function we were discussing.
We discussed the necessity of additional functions, such as (to continue using the example) ‘doesPersonHaveSister()’ to check first before requesting the name, but we felt it was an extra step that was solved by simply having the exception being raised. I think the signature we came to more closely matched the behavior we wanted. If we were compiling that list of sisters around the room, it feels more natural to simply ask:
What is your sister’s name?
Do you have a sister? If so, what is her name?
If someone gives a name, then we’re all set. If someone instead replies that they don’t have a sister, then we’ll take care of that
exception case when we reach it. Obviously this isn’t a perfect example, such as if someone had multiple sisters, but as far as our needs it worked great.
Thinking like this really allowed us to step back from the code and come up with a more natural solution that matches what we’re trying to do. I believe programming isn’t just instructions with the computer, it’s a conversation with yourself, the machine, and other developers on the project. Sometimes we find ourselves worrying so much about the code that we lose track of how we already handle this problem on a daily basis.