Thank you for your article. But, there are a couple of issues I’d like to address.
In my first version of the response I started the response with a rather blunt statement. Dan Rosenstark made me aware of that issue. In general I think it is way better to be direct, and I rather like the direct approach. But different people may see this different. So I removed the blunt statement, since the real information can still be transported without the bluntness.
Let's start with the giveMeFood-function. I'l use pseudo-code instead of javascript, since it makes it easier.
The best way to handle the first version is to use a fail-fast approach:
This is in case there is only one situation in which you do not want the function to be executed. So the fail fast checks exactly this situation.
The refactored version, which uses more foods, should not use the if-approach at all. Put the food-answer combinations into a map and use it. this looks like:
So you can avoid this strange if / else-block at all, since It is not really a best practice in such a case where it is obvious that more options will appear to hardcode them.
For your country code function, this is not a question of style, since it contains a hidden error, which is only undetected since javascript allows such things.
The first approach is a function that has a kind of mechanical error. Which means it will not even compile in a proper language, since the default case is not satisfied. And I guess even in javascript this might at least result in a warning.
You have a function that when you call it is expected to return something. Yet your function looks like:
So you have syntactically wrong function and prefer that to the syntactically correct one, which is:
Bear in mind, you wrote the code with the assumption that there are only two countries this code is relevant for: The US and the UK. This is kind of your business contract you wrote the code on. So if the country isn't the US, then it must be the UK. There is no way around this, as your business definition states.
And if you have to expand your code for more countries, then why the heck would you hard code this? It is the same as in the giveMeFood-function above. You put the countries with their country codes into a lookup map. And then your code has to handle the real code, which would be like
But the default should always be to not write unneccesary code. Especially nested if/else clauses are a pita, and so are default else-clauses They are not required at all.