Call Me Maybe
Let’s imagine your typical code.
You might say, “So what, Sandae? Here to say we’re doing it wrong again?”.
I’m afraid yes.
findOne
is dishonest
We’re expecting a $user
but then we got a null
value. findOne
should return one, right? Not null
.
Should we rename the method to findOneOrNull
so that consumers of the method will not forget to check for null return?
That’s a bit ugly so we need a better way.
Fixing dishonesty with Maybe
Let’s write our Maybe
class
Usage:
Our code now is honest 🎉. Our editor would caught it and give us a nice hint that the function might or might not return a user.
But!
I don’t like the nested if/else
and it is still verbose to me. Let’s fix it with a mouthful word so that I will sound smart.
Enter, Railway-Oriented Programming. We’re going to add some extensions to our Maybe class.
Usage:
Thank you for reading. Hope this will enhance your code base. Happy coding!