In terms of efficiency and elegance, is it better

2019-08-13 11:15发布

To clarify my question, here are two examples in javascript-esque pseudocode. Here are the same examples but with a bit more code to contextualize them: http://pastebin.com/fRjW5qp6

See how I'm using conditionals to prevent sockets from triggering the important event logic after they've already triggered it once (e.g. I set socket.loginBuilt to true after the event listener has been triggered).

socket.on('login screen built', socketLoginScreenBuilt);

  function socketLoginScreenBuilt() {
    // See how I'm using this conditional to prevent sockets from triggering the important event logic after they've already triggered it once (since I set socket.loginBuilt to true in the logic)
    if (!socket.loginBuilt) {
      numberOfSocketsWithBuiltLoginScreens++;
      socket.loginBuilt = true;

      if (numberOfSocketsWithBuiltLoginScreens === io.sockets.sockets.length) {
        app.emit('all login screens built')
      }
    }
  }

  socket.on('login credentials', socketLoginCredentials);

  function socketLoginCredentials(credentials) {
    if (readyForLoginCredentials) {
      socket.username = credentials.username;
      socket.password = credentials.password;

      socket.emit('user stored data', socket.userData);
    }
  }
});

------------------- OR -------------------

Notice how I'm not using the conditionals I used above because I remove the listeners after the functions run for the first time. In that way I'll be certain that a socket won't trigger the important event logic multiple times.

socket.on('login screen built', socketLoginScreenBuilt);  

function socketLoginScreenBuilt() {
  // Notice how I'm not using a conditional here because I remove the 'login screen built' listener after this function is first ran. In that way I'll be certain that a socket won't trigger the important event logic multiple times
  numberOfSocketsWithBuiltLoginScreens++;
  socket.loginBuilt = true;

  if (numberOfSocketsWithBuiltLoginScreens === io.sockets.sockets.length) {
    app.emit('all login screens built')
  }

  socket.removeListener('login screen built', socketLoginScreenBuilt);
}

socket.on('login credentials', socketLoginCredentials);

function socketLoginCredentials(credentials) {

  socket.username = credentials.username;
  socket.password = credentials.password;

  socket.emit('user stored data', socket.userData);
  socket.removeListener('login credentials', socketLoginCredentials);
}

1条回答
姐就是有狂的资本
2楼-- · 2019-08-13 11:48

I want to clarify 2 things:

  • Node.js is event-driven.
  • Global variables are evil (there's a C/C++ tag but they make the point)

So, in order to keep your code clean and, well, up-to-standards, you should use event-driven approach rather than global variables.

BTW in both cases you do use global variable numberOfSocketsWithBuiltLoginScreens.

查看更多
登录 后发表回答