Photo by Scott Rodgerson on Unsplash

Call super code smell (Kotlin)

Alessandro Persiano
2 min readJul 28, 2021

I have recently encountered a problem with my codebase.

An overridden method that applies a background color to a TextView has to call the super method to ensure that the right color was applied…a coworker forgot to add the super method…and boom the problem rises up.

Let me show this in code:

Suppose that you have a base abstract class that runs a very important task…you cannot paint a gate without pass the rust inhibitor, right?

abstract class BaseGatePainter{
open fun paintGate(){
println("Pass the rust inhibitor")
}
}
class WhiteGatePainter() : BaseGatePainter(){
override fun paintGate(){
println("Paint with white color")
}
}
fun main() {
WhiteGatePainter().paintGate() //Oh no...what a mess :(
}

We forget to call the super.paintGate() method. Now we have to add it but is very important to add it to the right place to avoid any problems with our gate.

class WhiteGatePainter() : BaseGatePainter(){
override fun paintGate(){
super.paintGate() //this is the right place! :)
println("Paint with white color")
}
}

This is a minor code smell!

Call super is a design pattern in which a particular class stipulates that in a derived subclass, the user is required to override a method and call back the overridden function itself at a particular point.

The overridden method may be intentionally incomplete, and reliant on the overriding method to augment its functionality in a prescribed manner.

The solution

The solution is quite simple but effective: we need to define a method that follow our template of steps and when it need call the hook method (prepareGateColor in this case)

fun main() {
WhiteGatePainter().paintGate()
}
abstract class BaseGatePainter{
abstract fun prepareGateColor()

open fun paintGate(){
println("Pass the rust inhibitor")
prepareGateColor()
}
}
class WhiteGatePainter() : BaseGatePainter(){
override fun prepareGateColor(){
println("Paint with white color")
}
}

Happy Coding!

References

https://en.wikipedia.org/wiki/Call_super

--

--

Alessandro Persiano
Alessandro Persiano

Written by Alessandro Persiano

Android Engineer && Google Developer Group Milano Organizer

No responses yet