简体   繁体   中英

Nested functions vs. chaining methods vs. a && sequence of functions

Good evening/morning (depending of your place),

I'm a newbie 'developer' (JS/Meteor platform), and every day I discover a new thing about JS. Knowing my low level, It is not that hard...

I'm currently wondering the best way/practice to code a switch(true) . More precisely I have a Switch statement with something like 20 cases .

Currently, I decide not to nest some cases together, I find it less easy to read. So my statement looks like something like this:

switch()
  case 1
  case 2
  case 3
  case 4
  case 5
  case 6
  ...
  default

Instead of something like:

switch()
  case 1
    if
    elseif
    else
  //or
  case 2
    switch()
      case 2.1
      case 2.2

My question is: each case tests something like 5+ functions. So a case is basically written this way:

case ( function1()
       && function2()
       && function3() == null
       && typeof abc[1] === 'undefined'
       && function4() === 'xyz') : //etc...

Is there a better way to chain functions?

I'm currently looking at chaining method in a jQuery way: function().function2().function3()... But I don't know if it exits a better way to deal with this kind of situation.

I will be delighted to get your feedback/advice and any reading/lecture you would recommend. I also hope this question is "right" for SO.

Thank you very much.

You shall always strive against small functions to increase readability. It might be a good idea to group function calls in new functions. The faster you can determine what a function does the better. Try to only have things relevant to the current function, for example:

You are supposed to fetch a lot of information about a person but the information is spread into different sources forcing you to have one function for name, one for age, one for shoe size and so on.

Instead of writing it like

case 1:
    var person = {
        name: getName(),
        age: getAge(),
        showSize: getShowSize()
    };

You could write it like

case 1:
    var person = getPerson();

And the the getPerson function

function getPerson() {
    return {
        name: getName(),
        age: getAge(),
        showSize: getShowSize()
    }
}

In your 20 cases I'm sure there are logical groups of functions that is used in several cases. Try to group them together if they have any logical connections. With a switch as large as with 20 cases I would try to not write to much code in every case since it would probably make it difficult to see what the function does.

I hope I got your problem and at least gave you some advices you find useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM