Using only 1 'if' statement and no 'else' & no switch & no shorthand notation for if-else?
// Original function
func Wheel(WheelPos uint32) {
if WheelPos < 85 {
fmt.Println("WheelPos < 85",Color(WheelPos*3, 255-WheelPos*3, 0))
} else if WheelPos < 170 {
WheelPos -= 85
fmt.Println("WheelPos >= 85",Color(0, WheelPos*3, 255-WheelPos*3))
} else {
WheelPos -= 170
fmt.Println("WheelPos > 170",Color(0, 255-WheelPos*3, WheelPos*3))
}
}
The above function is called in the main inside a for loop like so:
func main() {
var i uint32
for i = 0; i < 255; i++ {
Wheel(i)
}
}
The Color function is defined as such:
func Color(r uint32, g uint32, b uint32) uint32 {
return (r << 16) | (g << 8) | b
}
I have started off with something like so:
func Wheel(WheelPos uint32) {
if (WheelPos < 85) || (WheelPos >= 85) || (WheelPos > 170) {
// logic....
}
}
I don't see how you would refactor the code, and somehow keep it clear and expressive enough.
If you have only three cases to consider, making them in three separate if/else is the easiest way to code those cases.
It is technically possible: you could create an if statement for the >170
case, then define an array of 170 function pointers and use an index operation for the other two cases. I can't think of a reasonable case where this solution is actually better than the one you already have though.