https://kotlinlang.org logo
#codereview
Title
# codereview
t

therealbluepandabear

02/26/2022, 3:46 AM
How good is this?
Copy code
import java.util.UUID

enum class Color {
    RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE, TRANSPARENT
}

interface Shape {
    val name: String
    val uuid: UUID
        get() = UUID.randomUUID()
    val width: Int
    val height: Int
    val fillColor: Color
    val strokeThickness: Int
    val strokeColor: Color
    fun draw()
    fun erase()
}

class Square(
    override val width: Int,
    override val height: Int,
    override val fillColor: Color,
    override val strokeThickness: Int,
    override val strokeColor: Color
    ) : Shape {
    init {
        if (width != height) {
            throw IllegalArgumentException("Length must be equal to width.")
        }
    }

    override val name = "Square"

    override fun draw() {
        println("$name has been drawn.")
    }

    override fun erase() {
        println("$name has been erased.")
    }
}

class Rectangle(
    override val width: Int,
    override val height: Int,
    override val fillColor: Color,
    override val strokeThickness: Int,
    override val strokeColor: Color
    ) : Shape {
    override val name = "Rectangle"

    override fun draw() {
        println("$name has been drawn.")
    }

    override fun erase() {
        println("$name has been erased.")
    }
}

class Canvas(
    private val width: Int,
    private val height: Int,
    private val shapeData: MutableList<Shape>
    ) {
    init {
        for (shape in shapeData) {
            if (shape.width > this.width || shape.height > this.height) {
                throw IllegalArgumentException("Shape of ${shape.uuid} is too large.")
            }
        }
    }

    fun eraseContents() {
        for (shape in shapeData) {
            shape.erase()
        }
    }

    fun drawContents() {
        for (shape in shapeData) {
            shape.draw()
        }
    }
}
k

Klitos Kyriacou

02/27/2022, 1:24 PM
Just some random thoughts: 1. The
Shape.uuid
property returns a new random UUID each time it's accessed. You need to generate a random one only at construction. 2. You can replace the precondition checks in
init
with require(boolean, lazymessage). 3. Why not allow drawing shapes bigger than the canvas, but just crop them at the edges? 4. Your
eraseContents
doesn't actually remove the shapes from the canvas; did you mean to delete the shape from the list? 5. Your canvas is conceptually mutable because you can erase its contents (which is why you're using a mutable list). In that case, why don't you also allow resizing? You can do so by using
var
for width and height.
l

LeoColman

03/01/2022, 2:34 AM
I particularly don't like SCREAMING_SNAKE_CASE variables. I'd rather have
Copy code
enum Color {
  Red, Yellow, Purple, ...
}
t

therealbluepandabear

03/01/2022, 5:43 AM
Ok, thanks for the feedback guys.
16 Views