Sonarqube函数只允许7个参数。我有一个函数,它用8个参数组成字符串。
fun example(
context: Context,
a: Int,
b: Int,
c: String,
d: Int,
e: String,
list: List<String>,
dat: String
) {
a = d+b
var f = a+b+d
if (list >0){
f = f+ "example"
}
return c+ e + f + dat
}为了使这个函数只有7个参数。我通过删除最后一个参数dat来拆分函数,但是为了计算dat变量,我还需要b和d变量的值。所以在函数返回后,我需要b和d的值来计算dat,然后连接dat来返回函数。如下所示
fun example(
context: Context,
a: Int,
b: Int,
c: String,
d: Int,
e: String,
list: List<String>
) {
a = d+b
var f = a+b+d
if (list >0){
f = f+ "example"
}
return c+ e + f
}
// i call it like below
example(context, 1, 1, "c", 1, "e", listOf('list1', 'list2')) + exampleConcat("dat text")
fun exampleConcat(dat: String) {
val t = d + b + dat // here i need the latest value of 'd' and 'b'
return t
}如何获得d和b的最新值在函数返回后这些局部变量将被销毁?如何通过传递7个参数来提高此函数的效率。
发布于 2021-05-10 20:20:54
您可以创建一个可以接受多个值的自定义数据模型。
像这样
data class CustomModel(
var list:List<String>
var dat:String
)因此,您的解决方案将是这样的。
fun example(
context: Context,
a: Int,
b: Int,
c: String,
d: Int,
e: String,
customModel:CustomModel
) {
a = d+b
var f = a+b+d
if (customModel.list >0){
f = f+ "example"
}
return c+ e + f + customModel.dat
}现在调用函数example()并将列表( customModel,dat)传递到示例函数的customModel参数中。
发布于 2021-05-10 20:30:02
让我们从一个问题开始-为什么一个函数中超过7个参数是一件坏事?
答案很简单--都是关于可读性的。那么,我们能做些什么呢?
对象1. Opts
data class ExampleOpts(
public val p1: String,
...
public val p10: Int = 0
)
fun example(opts: ExampleOpts) {
}这种方法的可读性更好--函数签名表明它有很多参数,所以将它们提取到自己的结构中是一件好事。
2. Builder
当我们达到这么多参数时,以某种方式在方法之外验证数据可能是很好的。我们可以使用构建器来做这件事。这在kotlin中并不常见,因为我们可以使用简单的数据类(如默认参数等)来获得许多生成器的优点。然而,有时它可能是有价值的,特别是当我们需要验证数据的时候。
Read more about Builder Pattern in Kotlin
3.忽略这个问题:)
事实上,我们不应该将SonarQube (或任何其他linter)中的所有问题都视为必须修复的问题,因为它只是静态分析的结果。有时候,有更多的参数是很正常的事情。例如:
example of functions with up to 22 parameters
正如我们在这个库中看到的,我们有比7更多的参数,这是完全,完全没有问题的。
4.这不是关于减少参数的数量,而是关于增加可读性。
如此多的参数表明某个实现可能存在问题。快速浏览一下实现,就会发现它是这样的。
fun example(
context: Context,
a: Int,
b: Int,
c: String,
d: Int,
e: String,
customModel: CustomModel
) {
a = d + b
var f = a + b + d
if (customModel.list > 0) {
f = f + "example"
}
return c + e + f + customModel.dat
}context -未使用
a -不会编译,因为在第一行(val cannot be reassigned)重新声明了a
因此,参数的数量并不总是一个问题-这只是一个建议,可能有问题。这取决于你来验证它,并在需要的时候修复它。
https://stackoverflow.com/questions/67469482
复制相似问题