编写一个函数来适应两种不同的情况?

Writing a function to adapt for two different cases?

也许我没有认真思考,但可以说我的代码相似度为 99%,为它构建函数的最简单方法是什么?

// this is just an express route, not the function I am building
// doPay() is the function I am trying to build properly
function(req,res) {

  if(req.user) {

    // I can use req.user.id in my function
    doPay(req,res);

  } else {

    passport.authenticate('local-signup', function(err, user, info) {

      // instead of req.user.id I would just need user.id
      doPay();

    });

  }

}

doPay()

// My doPay() function, above I need to pass either req.user.id or user.id
// based on the boolean, so how do I adjust this to adapt to that?
gateway.customer.find(req.user.id, function(err, customer) {

  //do payment stuff for an existing user, if the user is new I need to use
  //user.id above

});

这里有两种替代设计。

你可以让函数接受 3 个参数

function doPay(req, res, user)

然后在该函数中测试 select 可用的内容

var userId;
if (req && req.user && req.user.id) userId = req.user.id;
if (!userId && user && user.id) userId = user.id;
if (!userId) throw "error...";

或者您可以选择将第三个参数设为要使用的用户 ID

 function doPay(req,res,userId)

并将userId源码逻辑放在路由代码中,而不是doPay代码中。 doPay 只会使用它被告知要使用的 userId。我认为这种设计是@Bergi 在第一条评论中建议的。