Search code examples
springkotlinvisibilityaccess-modifiers

Visibility Modifiers in Spring / Kotlin


Is it bad practice to use private to hide the implementation of a contract and not show it even in ide autocomplet. If so, why?

interface MyService {
    fun process()
}


@Service
private class MyServiceImpl : MyService { // Hide implementation
    override fun process() {
        println("Processing...")
    }
}

@RestController
class MyController(private val myService: MyService) {
    @GetMapping("/process")
    fun process() = myService.process()
}


Solution

  • If it is sufficient to access an implementation through its interface then there is no reason to make it more visible than necessary.

    That's basically the whole idea of interfaces. You can abstract away the gory details and only work with clean interfaces. Making all implementations public nonetheless increases complexity and the user is always left to wonder if they shouldn't still access the implementation by its implementation type. The less ambiguous the better.

    As to what the auto-complete feature of the IDE offers, that depends on what the IDE actually sees (it may not be able to see a private type in a library) and what it deeems useful in the current context. But then again, when the type is private that is a strong indicator that you do not even need to know about it, no need for the IDE to show it to you.