DEV Community

Discussion on: Which would you prefer and why?

Collapse
 
bgadrian profile image
Adrian B.G.

Either way I'll not use if for more than 2 options, and because the devs are usually lazy and do not refactor and just add a new option, I tend to never use it.

The answer depends a lot on the size of the do stuff code blocks.

  1. 1-2 liners I suggest using a switch

  2. If there are more I would suggest using a map, similar to your 2nd version but it can be replaced with other functions. This is how actually some compilers transform the switch.

const handlers = {};
handlers[`option1`] = function(){ //do a lot of stuff }
handlers[`option2`] = function(){ //do a lot of stuff }
function (arg) {
  //if arg doesnt exists in handlers ..
  return handlers[arg]();
}

Because of the size of the function (now in the x * 10s) I would transform this function to a module, and declare the option functions outside of the main function.

The code can grow independently, the functions will not be "compiled" until they are called for the first time and they can be tested independently, if needed.

3 . 2 can be future extended, if needed to one of Plugin/Services/Inversion of control pattern, mainly to inject new functionalities in the map as more modules are active in your project.

Collapse
 
codevault profile image
Sergiu Mureşan • Edited

This is a great improvement over the second version.

The only issue I find is that the code for the function is no longer inside the function itself but outside. Maybe this will solve the issues:

let handlers;
function (arg) {
  if (!handlers) {
    handlers[`option1`] = function() { //do a lot of stuff }
    handlers[`option2`] = function() { //do a lot of stuff }
  }
  return handlers[arg];
}
Collapse
 
bgadrian profile image
Adrian B.G.

Functions in functions I would say is smelly code, anyway if there are 5 options each with 7+ LOC then the main function will become too big, that is why I said to make a distinct object/module, with a size of 50+ LOC would probably required its own module. Then the functions being outside is ok, because they are encapsulated by the module.