Naming pattern for Exceptions
Sure, you’ve heard it before: naming is hard. I’m also confident that this isn’t the first time that someone tells you to drop technical patterns from your naming strategies. But have you ever tried it? And if you did; have you applied yourself to take it beyond the obvious?
Can you use the names of classes and methods in a conversation without modification? Would you like it if your domain experts immediately recognize what pattern you’re talking about when you’re discussing the model? Because when that happens a new world will emerge, and you’ll be one step closer to Domain Driven Design.
Over the past year I’ve been experimenting with applying as much natural language to naming as possible and today I want to share that experience.
My office is located in Amsterdam city center. Transport by bike is the best way to go from A to B in this city. I usually borrow the bikes of other people since I haven’t had a decent one in the past decade. Last year I was stupid enough to misplace the bike of my girlfriend.
For days I was checking all the places I had been… And then again… And again. I spoke with the authority responsible for removing bikes. I spoke to the cops. I even spoke to the local junkies. But none of them had seen her bike.
After a few days I had to face the music when my girlfriend asked me about it:
Marijn, where is my bike parked? I need it tomorrow.
What else could I do than to tell her the truth?
I’m sorry, I have not been able to locate your bike since I used it last saturday.
She wasn’t happy, but the apology helped. Albeit that I had to pad it with a diner to truly make up for the loss of her bike.
It made me wonder why we don’t apologise in our code when we cannot comply with the contract of our interface.
You know something bad is coming your way when someone starts to tell you a story that begins with the words “I am sorry”.
So why not rely on natural language like that in our code?
Since then I prefix the names of my exceptions with
It’s short, it’s explicit, and it’s easy to spot; I love it.
It’s so obvious that I don’t know why I haven’t seen anyone else do it.
You’re not convinced? I dare you to try it.
Go and prefix an exception class name with
Sorry right now!
Don’t forget to remove the
Exception suffix for an optimal result.
That reads better right?
You no longer have to read the entire class name before you know what’s going on.
It’s a feature I call Immediate Feedback™.
Every time you read that class name you’ll immediately understand its purpose. Success guaranteed.
Plus most domain experts will understand
SorryBikeCouldNotBeLocated a lot better than
It may even help you to build up more empathy throughout your codebase and within your team.
At the very least it is a shorter alternative and more understandable for non-programmers.
Have I told you the best part yet? You can start using it today. That’s right. It’s not even violating any of the PSRs.