Even Uncle Bob has addressed the subject. In npm alone, countless packages have been released to provide an alternative. People tend to think that the catch with Contact and if-then-else is that the more branches in your code, the more opportunities for untested and unexpected behavior. Each branch requires different use cases to be thoroughly tested, and although some tools, such as Istanbul, provide an indication of how many branches have been performed, in addition to the traditional feature coverage. But branches are part of the nature of programming, there is nothing we can do about it.
In this brief statement, I would like to give a new spin on when to use control structures and when to use some functional alternatives.
Ever since I discovered Dr. Lamport’s Temporal Logic of Action, my programming style has changed to become more explicit about tasks versus mutations of the application mode and more aware of temporal logic. For me, there are three core patterns in programming: object-oriented programming, functional programming, and temporal programming. One developer should master all three and use them accordingly, no pattern wins over the other. We can not write good programs with only one pattern.
One of the key concepts in temporal programming is the concept control mode: when the light is off, and if the switch is in the off position, I can trip the light is on Or else check the switch (in bold we have actions as expected in a given control mode). These are extremely familiar concepts we use every day, but for some reason we rarely come across control mode in the code we write. My view of this is that the situation arose due to the lack of alternative constructions with a good enough developer experience, and partly due to the ease of use of the switch and if-so-otherwise, over the stringency required to use temporal programming constructions, but that discussion is for another article. I would like to focus here on something that is much simpler and more practical.
First, we must absolutely stop using these control structures for (complex) tasks, it leads to some pretty ugly code that is hard to read and debug. How many times have you written such a code? plain on, tell me in the comments …
How about a functional alternative?