I learned to use enum class to constantize the constants involved.
I also learned that using when when using enum class is very effective.
I think I heard that you may not use else.
Case1 may not use else in isMovable. However, we still have to use the else in fromConditionOf() and the when is redundant twice.
Am I misunderstanding something?
Should I use else when using enum class?
Case 0 is the code when no enum class is used
To briefly explain the code, when the car gets a random value (0-9), it stops if it's 0-3, and moves forward if it's 4-9.
Case 0:
data class Car(
val name: CarName,
) {
init {
require(name.isNotBlank()) { "[ERROR] Name is empty or blank" }
require(name.length <= 5) { "[ERROR] Car names longer than five letters" }
}
fun move(randomValue: Int) =
when (randomValue) {
in 4..9 -> true
in 0..3 -> false
else -> throw IllegalArgumentException("[ERROR] When a random value is invalid")
}
}
Case 1:
enum class Movement(val range: IntRange) {
STOP(0..3),
GO(4..9);
companion object {
fun fromConditionOf(randomValue: Int): Movement =
when (randomValue) {
in STOP.range -> STOP
in GO.range -> GO
else -> throw IllegalStateException("[ERROR] When a random value is invalid")
}
}
}
data class Car(
val name: String,
) {
init {
require(name.isNotBlank()) { "[ERROR] Name is empty or blank" }
require(name.length <= 5) { "[ERROR] Car names longer than five letters" }
}
fun isMovable(randomValue: Int): Boolean =
when (Movement.fromConditionOf(randomValue)) {
Movement.STOP -> false
Movement.GO -> true
}
}
Case2:
enum class Movement(val range: IntRange) {
STOP(0..3),
GO(4..9);
companion object {
fun fromConditionOf(randomValue: Int): Boolean =
when (randomValue) {
in STOP.range -> false
in GO.range -> true
else -> throw IllegalStateException("[ERROR] When a random value is invalid")
}
}
}
data class Car(
val name: String,
) {
init {
require(name.isNotBlank()) { "[ERROR] Name is empty or blank" }
require(name.length <= 5) { "[ERROR] Car names longer than five letters" }
}
fun isMovable(randomValue: Int): Boolean =
Movement.fromConditionOf(randomValue)
}