It's something that's bugged me in every language I've used, I have an if statement but the conditional part has so many checks that I have to split it over multiple lines, use a nested if statement or just accept that it's ugly and move on with my life.
Are there any other methods that you've found that might be of use to me and anybody else that's hit the same problem?
Example, all on one line:
if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true) {
Example, multi-line:
if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true) {
Example-nested:
if (var1 = true && var2 = true && var2 = true && var3 = true) { if (var4 = true && var5 = true && var6 = true) {
You could maintain a mapping of strings to enums elsewhere in the program, pull out the enum associated with the returned string from the map (with a default NO_MATCH in case the string isn't in the map) and write a switch statement on the enums.
Nested IFs are powerful, but they become complicated quickly as you add more levels. One way to avoid more levels is to use IF in combination with the AND and OR functions. These functions return a simple TRUE/FALSE result that works perfectly inside IF, so you can use them to extend the logic of a single IF.
Separate the condition in several booleans and then use a master boolean as the condition.
bool isOpaque = object.Alpha == 1.0f; bool isDrawable = object.CanDraw && object.Layer == currentLayer; bool isHidden = hideList.Find(object); bool isVisible = isOpaque && isDrawable && ! isHidden; if(isVisible) { // ... }
Better yet:
public bool IsVisible { get { bool isOpaque = object.Alpha == 1.0f; bool isDrawable = object.CanDraw && object.Layer == currentLayer; bool isHidden = hideList.Find(object); return isOpaque && isDrawable && ! isHidden; } } void Draw() { if(IsVisible) { // ... } }
Make sure you give your variables name that actualy indicate intention rather than function. This will greatly help the developer maintaining your code... it could be YOU!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With