1

so I have this part of a code on a finished project:

        if (mode == 1) {                    
        repeats = 2;
        columns = 6;
        size = 24;
    }
    else if (mode == 2) {               
        repeats = 2;
        columns = 8;
        size = 48;
    }
    else if (mode == 3) {               
        repeats = 3;
        columns = 6;
        size = 36;
    }

I'm just messing with it and I was wondering if there is a better way to write this part using the ? operator or any other way.

ChrySo
  • 15
  • 2
  • 3
    Ever heard of a `switch` statement in Java? [Java language basics](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html). – prasad_ Nov 07 '18 at 01:55
  • Im aware of the switch statement , sorry for not being clear , I just liked the way the ? operator worked and I was just wondering If I could put the code in a format like " if mode 1/2/3 , repeats 2/2/3 and so on... – ChrySo Nov 07 '18 at 02:00
  • Look for the topic in the same Java tutorial: _Equality, Relational, and Conditional Operators_. The `?:` is called as _ternary operator_. – prasad_ Nov 07 '18 at 02:02
  • 2
    _Could you_ rewrite this logic using `?:` operators? Yes. _Should you_? IMHO, No. `?:` operators become unwieldy and unreadable if you try to cascade them. `if`s and `switch`es are much prettier and easier to follow. – Kevin Anderson Nov 07 '18 at 02:04
  • 1
    @DawoodibnKareem Feel free to recommend the OP post on CR but in the future, please don't use Code Review as a reason to close a question. Evaluate the request and use a reason like *too broad*, *primarily opinion-based*, etc. Then you can mention to the OP that it can be posted on Code Review if it is [on-topic](https://codereview.stackexchange.com/help/on-topic). Please see the section **What you should not do** in [this answer to _A guide to Code Review for Stack Overflow users_](https://codereview.meta.stackexchange.com/a/5778/120114) – Sᴀᴍ Onᴇᴌᴀ Nov 07 '18 at 16:23

7 Answers7

4

I would define an int[][] with the values for each mode as a key. Like,

int[][] modes = { {}, { 2, 6, 24 }, { 2, 8, 48 }, { 3, 6, 36 } };
if (mode > 0 && mode < 4) {
    repeats = modes[mode][0];
    columns = modes[mode][1];
    size = modes[mode][2];
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

Using the ternary ? operator would not work because you have too many variables that you want to update depending on the value of mode. If you used ? then you could only use it on one variable at a time and the code would be very cumbersome and hard to read. Switch is the best option

PumpkinBreath
  • 831
  • 1
  • 9
  • 22
1

The best way to wipe if is using polymorphic. For your given code you can abstract a class or an interface and implement the method in different ways. The example code is like following.

public class Test {
    public static void main(String[] args) {
        int modeValue = 1;//2,3 ...
        ModeFactory modeFactory = new ModeFactory();
        Mode mode = modeFactory.generateMode(modeValue);
        mode.fillData();
        System.out.println("mode info:" + mode.toString());
    }
}

abstract class Mode {
    int repeats;
    int columns;
    int size;

    abstract void fillData();

    @Override
    public String toString() {
        return "Mode{" +
                "repeats=" + repeats +
                ", columns=" + columns +
                ", size=" + size +
                '}';
    }
}

class Mode1 extends Mode {

    @Override
    void fillData() {
        repeats = 2;
        columns = 6;
        size = 24;
    }
}

class Mode2 extends Mode {

    @Override
    void fillData() {
        repeats = 2;
        columns = 8;
        size = 48;
    }
}

class Mode3 extends Mode {

    @Override
    void fillData() {
        repeats = 3;
        columns = 6;
        size = 36;
    }
}

class ModeFactory {
    Mode generateMode(int modeValue) {
        if (modeValue == 1) {
            return new Mode1();
        }
        if (modeValue == 2) {
            return new Mode2();
        }
        return new Mode3();
    }
}

design patterns may help you solve these problem.

xxy
  • 1,058
  • 8
  • 14
0

You cannot use here the ? operator, because it returns a value in each branch. In this case you can use a switch:

switch (mode) {
            case 1: 
                repeats = 2;
                columns = 6;
                size = 24;
                break;

            case 2: 
               repeats = 2;
               columns = 8;
               size = 48;
                break;

            case 3:
            case SUNDAY: 
                ...
                break;

            default:
                System.out.println("No default value");
                break;
        }
developer_hatch
  • 15,898
  • 3
  • 42
  • 75
  • Commenting this here aswell I dont know how notifications work im new here.Im aware of the switch statement , sorry for not being clear , I just liked the way the ? operator worked and I was just wondering If I could put the code in a format like " if mode 1/2/3 , repeats 2/2/3 and so on... – ChrySo Nov 07 '18 at 02:01
  • @ChrySo sadly is not the right tool for the job you want to do. You cannot use it in this example – developer_hatch Nov 07 '18 at 02:05
0

Best alternative of multiple if block is go via switch case. It will be more readable code.

int mode = 1;
  switch (mode) { 
        case 1:
            //your logic
            break; 
        case 2: 
             //your logic
            break; 
        case 3: 
            // your logic
            break; 
         default: 
            // When anything doesnt match 
            break; 
        } 
kris
  • 979
  • 11
  • 15
  • 1
    Sorry @kris but this does not add anything to the already posted answers regarding `switch/case` blocks – Scary Wombat Nov 07 '18 at 02:10
  • 1
    you are right @ScaryWombat. I read the post when there were no answers, I am new to platform, took some time to post the answer, in mean time similar answers were posted . – kris Nov 07 '18 at 02:16
  • 1
    Yes, I am not sure why you did not simply edit your deleted answer – Scary Wombat Nov 07 '18 at 02:17
0

I like the if statement. Easy to read and debug. But I think enums are better suited for this type of situation. Even if it is only used in your class you can declare private enum and only use inside a single method:

     private enum Mode{
        ONE(2, 6, 24),
        TWO(2, 8 , 48),
        THREE(3, 6, 36);

        int repeats;
        int columns;
        int size;

        Mode(int repeats, int columns, int size){
            this.repeats = repeats;
            this.columns = columns;
            this.size = size;
        }

        public int getRepeats() {
            return repeats;
        }

        public int getColumns() {
            return columns;
        }

        public int getSize() {
            return size;
        }  
    }

And the nice thing is that you can use Enum.values and avoid creating separate array.

    int mode = 1;
    Mode m = Mode.values()[mode - 1]; //m will be ONE
tsolakp
  • 5,858
  • 1
  • 22
  • 28
-1

Java has the switch statement which you can use like follows:

switch(mode)
     case 1:
        repeats = 2;
        columns = 6;
        size = 24;
        break;
     case 2:
        repeats = 2;
        columns = 8;
        size = 48;
        break;
     case 3:
        repeats = 3;
        columns = 6;
        size = 36;
        break;
      ...

Note: Don't forget to include the breaks in your case statements. Otherwise, the behaviour is fall through to the next case statement until it hits the end or a break.

Technically, you could use the ? operator, however it's really better to use it for 2 cases (condition is true or condition is false). You would also need to change your logic slightly. In this case it would make your code worse.

if(mode == 1) ? repeats = 2; columns = 6; size = 24 : (if(mode == 2) ? repeats = 2, columns = 8; size = 48 : (if(mode == 3) ... ) )
richflow
  • 1,902
  • 3
  • 14
  • 21