Subbu Lakshmanan

Functions should not have too many parameters

Use best practices to avoid a lot of parameters in a function

Why

As we add new functionality to an existing codebase, we tend to add more and more parameters to existing functions. Often, We want to minimize the changes to the current code and wrap the feature/bugfix quickly. While the intention is good, it can lead to many problems in the future.

Depending on the project, this number can vary. As per sonarlint, this number should be less than 7. Anything more than that indicates that either,

  1. Function is doing too much
  2. Parameters can be grouped to form a new class

While one can suppress this warning using @Suppress("LongParameterList"), it's better to refactor the code to avoid this warning.

What to do

Depending on the function, there are different ways to refactor the code to avoid this warning.

  1. Check the usage of the parameters inside the function and see if you can
    1. Remove parameters that may serve the same purpose
    2. Split the function into multiple functions
  2. Group related parameters into a new class and pass the class instance as a parameter

How to do

 fun showErrorDialog(
  title: String? = null,
  message: String? = null,
  positiveTitle: String? = null,
  negativeTitle: String? = null,
  val positiveButtonTextColor: Int? = null,
  isCancelable: Boolean = true,
  isSingleButtonDialog: Boolean = true,
  val inCompose: Boolean = false
) {
  ...
}

One way to fix this is to group the parameters into a new class and create a new overloaded function that takes the new class as a parameter.

data class DialogParams(
  val title: String? = null,
  val message: String? = null,
  val positiveTitle: String? = null,
  val negativeTitle: String? = null,
  val positiveButtonTextColor: Int? = null,
  val isCancelable: Boolean = true,
  val isSingleButtonDialog: Boolean = true,
)

fun showErrorDialog(
  dialogParams: DialogParams, 
  val inCompose: Boolean = false
) {
  ...
}

Replace the function call with the new function and pass the parameters as a new class instance.

fun showLoginFailed() {
  showErrorDialog(
    DialogParams(
      title = "Login Failed",
      message = "Please try again",
      positiveTitle = "Retry",
      negativeTitle = "Cancel",
      positiveButtonTextColor = R.color.green,
      isCancelable = false,
      isSingleButtonDialog = true
    )
  )
}

You can remove the old function once you replace all the usages with the new function.

Note: The code examples are simplified for brevity. Ideally, use string resources instead of hardcoded strings.


All rights reserved