2
\$\begingroup\$

I have an existing overloaded set of functions that I cannot change and need to be tested:

object Validator {
    fun validateRange(min: Int, max: Int): Boolean = true
    fun validateRange(min: Long, max: Long): Boolean = true
    fun validateRange(min: Double, max: Double): Boolean = true
    fun validateRange(min: String, max: String): Boolean = true

    fun validateRangeInput(min: Int, max: Int, input: Int): Boolean = true
    fun validateRangeInput(min: Long, max: Long, input: Long): Boolean = true
    fun validateRangeInput(min: Double, max: Double, input: Double): Boolean = true
    fun validateRangeInput(min: String, max: String, input: String): Boolean = true
}

The test data for validateRange() contain each of the various types. Here is a sample of the input data:

val inputs = listOf(
        Pair("1", "1"),
        Pair(1, 1),
        Pair(1L, 1L),
        Pair(1.0, 1.0)
)

Of course, I cannot simply do this:

inputs.forEach { (min, max) -> Validator.validateRange(min, max) }

My current solution implements a helper using generics and a when block with the is operator and smart casting:

fun <T> validateRangeHelper(min: T, max: T): Boolean {
    return when {
        min is Int && max is Int -> Validator.validateRange(min, max)
        min is Long && max is Long -> Validator.validateRange(min, max)
        min is Double && max is Double -> Validator.validateRange(min, max)
        min is String && max is String -> Validator.validateRange(min, max)
        else -> throw UnsupportedOperationException()
    }
}

inputs.forEach { (a, b) -> validateRangeHelper(a, b) }

This approach grows cumbersome with each additional argument, such as for the validateRangeInput() functions.

fun <T> validateRangeHelper(min: T, max: T, input: T): Boolean {
    return when {
        min is Int && max is Int && input is Int -> Validator.validateRangeInput(min, max, input)
        min is Long && max is Long && input is Long -> Validator.validateRangeInput(min, max, input)
        min is Double && max is Double && input is Double -> Validator.validateRangeInput(min, max, input)
        min is String && max is String && input is String -> Validator.validateRangeInput(min, max, input)
        else -> throw UnsupportedOperationException()
    }
}

Is there a way I can improve the helper or avoid it all together without changing Validator?

\$\endgroup\$
  • \$\begingroup\$ I'm afraid we'll need more context. Can you provide the real code please? It's off-topic otherwise. \$\endgroup\$ – t3chb0t Jun 28 at 19:24
  • 1
    \$\begingroup\$ @t3chb0t thanks for the request, I have added more context. \$\endgroup\$ – ordonezalex Jun 28 at 19:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.