Search code examples
javabooleanpass-by-referencepass-by-value

Automatically updating boolean value


Context: https://www.reddit.com/r/dailyprogrammer/comments/4wqzph/20160808_challenge_278_easymed_weave_insert_part_1/

Full Code: http://pastebin.com/UghV3xdT

I have 2 practically identical methods that can only different by one if-statement: if (k % 3 != 1) and if(k % 2 == 0).

int k = 0;
while(k<50){
    if(k % 3 != 1){ // OR if(k % 2 == 0)
        // Code logic goes here
    k++;
    }
}

The use of each cases is determined by the length of an Array which means the specific case only has to be determined 1 time. 'k' represents the index of another array and 50 is the length of this Array.

I could write something like if(foo > 1 ? k % 3 != 1 : k % 2 == 0) but that requires the program to do the action every time the loop runs.

In a way I would like a sort of updating boolean. Is there any way to do this, or is this the downside of pass-by-value? Should I keep two seperate methods or am I better of with using the ternary operator?

In essence I'm looking for a type that contains the expression rather than the value.


Solution

  • In Java 8 there is nice functional interface called IntPredicate. If you combine it with lambda expressions, you can achieve your goal with no duplication, extra code or any slow downs:

    public final class Example {
        public static void main(String[] args) {
            //Instead of randomly choosing the predicate, use your condition here
            Random random = new Random();
            IntPredicate intPredicate = random.nextBoolean() ? i -> i % 2 == 0 : i -> i % 3 != 1;
    
            int k = 0;
            while(k<50){
                /*
                 *At this point the predicate is either k%2==0 or k%3!=1,
                 * depending on which lambda you assigned earlier.
                 */
                if(intPredicate.test(k)){ 
                    // Code logic goes here
                    k++;
                }
            }
        }
    }
    

    PS: Please not that I use the random boolean value to switch between the predicates, but you can use whatever condition you have