DEV Community

Discussion on: Keeping your code clean by sweeping out "if" statements

 
tomazfernandes profile image
Tomaz Lemos

Hi Rasmus!

One thing I’ve learned from this post and all the discussion around it is that it should have been more about tradeoffs. I wrote a new post, about a different pattern, based more around the tradeoffs, and I think it’s a far better approach.

About the flexibility, one thing that came to mind is that this pattern is just as flexible as a switch statements, isn’t it? If something coded as a switch statement has to embrace a more complex condition you’d have to refactor it anyway. And yet I’ve never seen anyone argue that this should be taken into consideration when using switches.

I’m writing a new post with some more examples of pattens such as this, and in my experience once you have a minimal toolset of these patterns you can change pretty much any repetitive-if situation into a declarative one, without much effort.

As for the valid reasons for using the pattern, my point is that it makes the business rules a lot more readable, which in my experience leads to easier maintenance and less bugs.

I’d have preferred that the discussion gravitated more towards the business rules clarity than to the if or not if part, but again that’s on me for the way I’ve written the post.

I do appreciate your feedback a lot, thanks!

Thread Thread
 
khtony profile image
Breton F

@Rasmus

We may not see the problem with the same lens. I ll just try to make my points clearer. Hope we could agree later.

A map is a contract and practically a function. You give it a key it does some magic and return back to you a value. Your map implementation is up to you. So by providing a specific map and boom you can do stuff of your imagination. This for me is flexibility as you pick your map based on your requirements.

Unit tests burden
With the map/function version, I give a key and I get back a value. I do not need to go for all possible keys for my unit tests. Because what I m interesting in is the contract i.e ability here to translate an error code to something else.