这是一个简单的问题,但只是想获得一些建议。
我正在使用 Angular 构建一个简单的税务计算器应用程序,目前所有计算都运行良好,但是当涉及到代码设计时,我不知道我是否以正确的方式进行。所以...
第一次下蛋的时候有一些代码,我用它来计算退休金金额
this.superAnnuationAmount = (this.incomeAmount / 100) * this.superAnnuationPercentage
非常简单。但现在我开始清理我的代码,我认为如果我这样做的话,它看起来和阅读起来会更好......
this.superAnnuationAmount = this.getSuperannuationAmount(this.incomeAmount, this.superAnnuationPercentage);
private getSuperannuationAmount(income: number, percentage: number): number {
return (income / 100) * percentage;
}
现在我知道这几乎没有任何区别,除了我猜它更具可读性之外。我还将采用这种方法来处理更复杂的功能。然而,在我的 IDE 中,我出现了 Method can be more static
的 linting 错误。 。
如何才能更加静态?将大函数放入更具可读性的小函数中是正确的方法吗?
最佳答案
由于您的函数不使用对象上的实例变量(它不使用 this
),因此您可以将其设为静态
private static getSuperannuationAmount(income: number, percentage: number): number {
return (income / 100) * percentage;
}
不过你不必这样做 - 这只是你的 linter 向你袭来。
我认为更简洁的方法是使用 getter:
public get superAnnuationAmount(): number {
return (this.incomeAmount / 100) * this.superAnnuationPercentage;
}
现在您可以使用常规的superAnnuationAmount
,它将使用实例变量进行计算。
关于Javascript 代码可读性 - 是否拆分成更小的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49893417/