具有非静态默认值的默认参数合法吗?

时间:2019-03-15 11:58:41

标签: angular typescript

我目前正在重构一些内部Angular库,并遇到了一个看起来像这样的样机服务函数:

private createRandomItem(property: PropOne,
                        anotherProperty: PropTwo,
                        yetAnotherProperty: PropThree): Item {
    const rand = Math.floor(Math.random() + 0.5);
    const part = rand === 0 ? null : {
        id: AnotherClass.generateId(),
        prop2: anotherProperty,
        prop3: yetAnotherProperty
    };
    return {
        part: part,
        prop1: property
    };
}

我将其更改为:

private createRandomItem(property: PropOne,
                        anotherProperty: PropTwo = AnotherClass.getRandomPropTwo(),
                        yetAnotherProperty: PropThree = AnotherClass.getRandomPropThree(),
                        isPartEnabled: Boolean = Math.random() > 0.5): Item {
    const part = isPartEnabled ? null : {
        id: AnotherClass.generateId(),
        prop2: anotherProperty,
        prop3: yetAnotherProperty
    };
    return {
        part: part,
        prop1: property
    };
}

基本上,我在签名中引入了默认值,从而使函数调用更短:

// Before
const item = createRandomItem(prop, 
                              AnotherClass.getRandomPropTwo(), 
                              AnotherClass.getRandomPropThree())
// After
const item = createRandomItem(prop)

如果有人想自己设置属性,则可以使用两个签名而不会出现问题,甚至可以随意传递随机化器(我认为在大多数情况下,只会使用第一个参数)。

我的问题是这样: 如果默认值取决于其他函数的返回值,使用参数默认值是否是一个好主意?同样,在我们试用时,我真的很想知道这是否可以提高代码质量。我认为它使签名有些难看,但我也认为它值得。

由于这并不完全是客观的,所以我想在答案中添加我要查找的内容:

  • 讨论此问题的编码约定(未找到任何内容)
  • 更好的方法来声明此功能
  • 支持和反对在参数默认值声明中使用函数的争论

0 个答案:

没有答案