0

To start: this question is already kind of resolved for me. But the discussion might be interesting.

I like code so let's look at this function:

    fun foo(path: Path) {
        val absPath = path.normalize().absolute() // sanitizing
        doSomethingWith(path) // this is unsafe use because path is not sanitized
        doSomethingWith(absPath) // this is safe because we are using the sanitized absPath value
    }

Kotlin function parameters are always val, therefore we are required to create a new variable if we want to derive from it's value. We can choose between using a new name or using an old name and annotating it with @Suppress("NAME_SHADOWING") to not get the Name shadowed: ... warning.

I'm looking for something like

    fun foo(path: Path) {
        val absPath = path.normalize().absolute()
        @DoNotUseAnymore path
        doSomethingWith(path) // should give a warning/error
        doSomethingWith(absPath) // is fine
}

Do you know something like that? Or do you think I'm fiddling around at the wrong end of the equation and should just learn to not feel like doing bad stuff when using the @Suppress-annotation? Since I like to code, this is what I mean:

    fun foo(path: Path) {

        @Suppress("NAME_SHADOWING")
        val path = path.normalize().absolute() // sanitizing

        doSomethingWith(path) // there is only one sanitized variable so we are safe
    }

In some way this method is the cleanest one... I probably stick to that... Should I publish this question now? Well... maybe :)

Stefan
  • 1
  • 1
  • Are you worried about someone editing the code in future? Could you rename the `path` to something like `unsanitizedPath` to make its purpose clear? Sometimes simpler seems better to me. – matt freake Oct 27 '22 at 07:10
  • @mattfreake The problem with renaming the parameter is that it's visible to the caller, which doesn't always make sense. However, I think a better solution would need a change to the language. – gidds Oct 27 '22 at 07:39
  • @gidds exactly! :) – Stefan Oct 28 '22 at 05:17
  • The cleanest solution without any annotations I found is to refactor the actual code into a private method and letting the public one only do the sanitizing stuff... – Stefan Oct 28 '22 at 05:18

0 Answers0