首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尽可能减少使用if...else构造来获得具有某种设计模式的对象属性的正确值

尽可能减少使用if...else构造来获得具有某种设计模式的对象属性的正确值
EN

Stack Overflow用户
提问于 2022-03-22 08:20:56
回答 1查看 78关注 0票数 0

在根据大量条件创建对象时,我希望为属性分配一个值。目前,我正在使用一个单独的函数来获取属性的值,如下所示:

代码语言:javascript
复制
function getLocationId(currency, storeCode, isBundle) {
  if (currency === 'MYR') {
    if (storeCode === 'store-1') {
      return 1;
    } else if (storeCode === 'store-2') {
      return 2;
    }
  } else if (currency === 'SGD') {
    if (storeCode === 'store-1') {
      return 3;
    } else if (storeCode === 'store-2') {
      // This function can return the same value for a different condition
      return 2;
    } else if (!storeCode && !isBundle) {
      return 8;
    }
  }
  .
  .
  .
  // More conditions, with some involving `isBundle`
}

function getAccountId(currency, storeCode, paymentMethod) {
  // Function definition similar to getLocationId
  // with checks for currency, storeCode, paymentMethod
}

function getRequestObject(event) {
  return {
    .
    .
    .
    location: getLocationId(event.currency, event.storeCode, event.item.isBundle),
    account: getAccountId(event.currency, event.storeCode, event.paymentMethod),
    .
    .
    .
  };
}

我觉得在嵌套检查中再次使用了很多if...else结构。这样做是个好主意吗?是否有任何设计模式可用于基于getRequestObject中的参数getRequestObject构建具有正确位置ID和帐户ID的请求对象?

PS:我不会在实际的代码库中返回整数值,而是使用这个名为node-config的库,并将这些in存储在一个JSON文件中,稍后我可以用config.get('propertyName')检索该文件。

EN

回答 1

Stack Overflow用户

发布于 2022-03-22 08:48:32

一种在else语句之后不使用return语句的稍微简洁的方法。

代码语言:javascript
复制
function getLocationId(currency, storeCode, isBundle) {
    if (currency === 'MYR') {
        if (storeCode === 'store-1') return 1;
        if (storeCode === 'store-2') return 2;
        // other if or return a default value for this currency
    }
    if (currency === 'SGD') {
        if (storeCode === 'store-1') return 3;
        if (storeCode === 'store-2') return 2;
        if (!storeCode && !isBundle) return 8;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71568845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档