Hi, I want to have :one: Value Object :two: with v...
# announcements
p
Hi, I want to have 1️⃣ Value Object 2️⃣ with validation. Here is what I do usually, on the synthetic example of
Color
class:
Copy code
data class Color private constructor(
        val red: Int,
        val green: Int,
        val blue: Int
) {
    companion object {

        fun of(red: Int, green: Int, blue: Int): Color {
            if (isInvalidPigment(red)) throw IllegalArgumentException("Red pigment is invalid.")
            if (isInvalidPigment(green)) throw IllegalArgumentException("Green pigment is invalid.")
            if (isInvalidPigment(blue)) throw IllegalArgumentException("Blue pigment is invalid.")
            return Color(red, green, blue)
        }

        private fun isInvalidPigment(pigment: Int) = pigment < 0 || pigment > 255
    }
}