Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress an 'If' Statement

Hoping that this one doesn't cause much trouble in answering, but when writing this out in my Sudoku project, I knew there must be a better way of phrasing this if condition.

Thanks in advance guys.

public static void modVal(int r, int c, int x) {
    if((r>=1 && r<=9) && (c>=1 && c<=9) && (x>=1 && x<=9)) {
        sudoku.set(r,c,x);
    }
}
like image 255
taylanu Avatar asked Jul 28 '26 01:07

taylanu


2 Answers

You could pull out the logic into Boolean values and just test those instead e.g.

boolean validRow = r >= 1 && r <= 9;
boolean validColumn = c >= 1 && c <= 9;
boolean validValue = x >= 1 && x <= 9;
if (validRow && validColumn && validValue) {
    sudoku.set(r, c, x);
}

Or, given that the limits are identical for each (row, column and value all inclusively 1-9), then you could extract that to a method called withinLimits(value) that checks for the value being between 1 and 9.

public boolean withinLimits(int value) {
    return value >= 1 && value <= 9;
}

Then...

if (withinLimits(r) && withinLimits(c) && withinLimits(x)) {
    sudoku.set(r, c, x);
}

Not a great deal better than what you have though, just a little more terse syntactically speaking. And you don't require the additional parentheses either. Just drop them.

like image 123
ManoDestra Avatar answered Jul 29 '26 16:07

ManoDestra


java-8

If you're using java 8, there is a way using an IntStream. The advantage is that you could use this with any number of parameters.

public static void modVal(int r,int c,int x){
    if (IntStream.of(r,c,x).allMatch(i -> i>=1 && i<=9)) {
        sudoku.set(r,c,x);
    }
}

Explaination

Instream.of(r,c,x) // This will just stream over the data given in parameters.
        .allMatch(Predicate) // This will return true if all the data entered as parameter has been tested within Predicate and returned true.
like image 35
Yassin Hajaj Avatar answered Jul 29 '26 16:07

Yassin Hajaj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!