I’m developing for a minecraft server written in Kotlin. The current issue I’m running into is if there is a better programming pattern than if/else blocks for mechanics that can be controlled/configured by the user.
Here’s a snippet, it was suggested that one of the controller mechanics (drifting) be able to be toggled by the user.
fun setDirectControlEnabled(enabled: Boolean) {
isDirectControlEnabled = enabled
if (enabled) {
sendMessage(dcMessage)
val player: Player = (controller as? PlayerController)?.player ?: return
player.walkSpeed = 0.009f
val playerLoc = player.location
directControlCenter = playerLoc.toBlockLocation().add(0.5, playerLoc.y.rem(1)+0.001, 0.5)
if(!PlayerCache[player].playerConfig.dcDrift) { // the configuration to check
player.teleport(directControlCenter!!) // the code to run
}//skipping the teleportation causes the user to drift
// more code
The suggested snippet isnt too bad, but as more settings are added, or there are nested settings, Im worried that the codebase will be become muddled with code that mostly covers setting control than actually handling the intended mechanic.
if (configOne) {
// do something
if (configTwo) {
// also do
}
} else {
//do this instead
}
Is there a code style/pattern that minimizes obfuscation?
I’ve tried looking into decorators and annotations, although both of those things don’t seem like the thing I want.
I don’t know how to avoid nesting in your case, but maybe it will be enough for you if no one comes along with better idea.
If you want the code to be easy to read, you can extract implementation for each condition into different methods and call those methods in those nested ifs.
For example:
fun main() {
val configOne = true // just to initialize the variable for this demo
val configTwo = false // just to initialize the variable for this demo
if (configOne) {
doSomething1()
if (configTwo) {
doSomething2()
}
} else {
doSomething3()
}
}
fun doSomething1() {
//do sth
}
fun doSomething2() {
//do sth
}
fun doSomething3() {
//do sth
}