Keep your class OCP compliant by using enums instead of booleans

Open for extension closed for modification. This means that our code is written in such a way that our class can have new behaviour without changing its structure.

Lets say that we have a Task and this task can have a description, a status and a couple of on/off characteristics like the fact that can be edited, shared or tracked.

Using flags

One way to depict this in code is by using flags in the form of booleans:

class Task(
val description: String,
val status: Status,
val isEditable: Boolean,
val isTrackable: Boolean,
val isSharable: Boolean
)

This means that every time we need to add a new characteristic we have to modify the Task class and add a new boolean property. This violates the open close principle making the code difficult to scale.

Using a list of enums

Another way is to replace all these flags with a list of enums:

class Task(
val description: String,
val status: Status,
private val characteristics: List<Characteristic>
) {
fun hasCharacteristic(characteristic: Characteristic): Boolean {
return characteristic in characteristics
}
}
enum class Characteristic {
Editable,
Trackable,
Sharable
}

Now if we need to add a new characteristic we simply add a new enum entry and the entire project can keep using the hasCharacteristic method to query a task for its characteristics.

Bonus benefit: this way we also avoid the wall of properties that sometimes hides information instead of revealing it!

Leave a comment