Very simple question. Imagine are designing library API, where you want to provide way to switch boolean flag. Typically to disable or enable a functionality. For argument's sake, let's say it's enabling/disabling sounds and I will be using kotlin in my code samples, but language doesn't really matter. I see 2 ways to put that into interface:
- Use toggle/set style:
fun setSound(enabled: Boolean) //or toogleSound
- Use explicit method or each functionality:
fun enableSound()
fun disableSound()
Now I can map those way easily between each other so in a sense they are equal:
fun setSound(enabled: Boolean) {
if (enabled) {
enableSound()
} else {
disabledSound()
}
}
Or opposite direction:
fun enableSound() {
setSound(true)
}
fun disableSound() {
setSound(false)
}
First method is more friendly for programming, because you can just pass boolean variable, which can sometimes be convenient. One feedback I got here is, that in languages, that are not type-safe, this can be broken/unpredictable by passing non-boolean type.
Second method is on the other hand more explicit, easier to read and feels better overall from designing API perspective.
API should obviously contain only one of the options because of the DRY principle and even though I can create mapping (and extension methods in kotlin
world), I have to choose only one. I know there are some specific things to consider (ex: what kind of library, what is likely usage of it - if there are hundreds of flags, then "setter" methods is most likely better), but I am looking for general guidance without many specifics.
Which option would you choose and why? If there is another 3rd option, I'd like to hear about it too, but nothing comes to mind.