Happy Path Programming is a practice where a programmer assumes that user will always use the program correctly.
That means all inputs will already be valid and that all external systems will work as expected.
Let’s see an example-
Suppose you work at XYZ health company. You have to implement a BMI calculator for their website. So you wrote a simple API that will receive a person’s weight and height as input, and return the BMI value as response.
Then you created a nice little frontend page where users will be able to input their data and get their BMI.
Now your BMI calculator is ready.
Looks like it’s working perfectly!
But wait… What if I put my height as 0?
Yeah, it’s a disaster!
Now what if I input a negative number as my weight?
Well, this is not quite a disaster, but negative BMI is also a bad result.
Now normally you can argue -
“Why would someone’s height be 0! How can someone’s weight be negative! That’s impossible. If people are being stupid, I can’t do anything about it! bla… bla…”!
It’s okay to get frustrated on the users, but it’s not okay to defend a piece of vulnerable code.
Now that you knew all the possible bad inputs, you just went ahead and added some validations in JS method.
And now it looks like this when someone tries to input invalid data
Phew! Major crisis averted!
(But wait…!)
If I ask you, why did you add the validation to the client side only? Why not on the API too?
If you’re a newbie engineer, most likely your answer will be-
“The API will never receive bad data as I’ve prevented it from the frontend”.
Which is not wrong. But it’s a wrong practice for sure.
Here’s why:
Suppose after a year your company XYZ decided to make a Mobile App.
So they asked another junior engineer to design a screen for the mobile app, where users will input their height and weight. And then that data will be sent to your API where BMI will be calculated.
Now what if he forgets to add those input validations on his frontend too?
The system will break again right?
So the ideal thing to do was add the validation on the backend too:
Now no matter who uses your API, if he/she sends wrong data to your API, your API will send out a nice and clean error message like this:
By the way, this approach where you take care of everything that can go wrong is called Defensive Programming.
And in most cases, Defensive Programming will benefit you in the long run.