Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to better organize the hierarchy of classes

I have an abstract class Image Filter:

abstract class ImageFilter {
    internal abstract val size: Int
    fun applyForImage(image: BmpImage) {
        //here size is used to calculate the boundaries
        //somewhere here applyForOnePixel(data) is called
        //...
    }

    abstract fun applyForOnePixel(data: Array<Array<RGBColor>>): RGBColor
}

There is no problem implementing the child class, however, in order to call applyForImage, it is necessary to create an instance, for example, in this way

GrayscaleFilter().applyForImage(img)

However, I want to do it this way

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

GrayscaleFilter.applyForImage(img)

I understand that I have to use companion object, but how do I get child classes to implement applyForOnePixel and specify size if you can’t use abstract inside the companion object?

>Solution :

If your GrayscaleFilter should not be modifiable in any way, you can define it as an object instead of a class.

object GrayscaleFilter: ImageFilter() {
    override val size: Int = TODO("Not yet implemented")
    
    override fun applyForOnePixel(data: Array<Array<RGBColor>>): RGBColor {
        TODO("Not yet implemented")
    }
}

This way a single instance is available during runtime, which can be accessed as you desire, namely:

GrayscaleFilter.applyForImage(img)

Note however, that this has implications. You’re basically dealing with a singleton. Thus, if you can modify the instance in any way, e.g. by having accessible var fields, these changes are global!


On a side node, maybe you want to rotate the call order, to ease reading of the calls, e.g.:

fun BmpImage.applyFilter(filter: ImageFilter) = filter.applyForImage(this)

fun main() {
    val image: BmpImage = TODO("Not yet implemented")

    image.applyFilter(GrayscaleFilter)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading