Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the innermost nested statements, but keep the outer statements?

Tags:

java

This is a bit of a confusing question so I'll do my best in asking it.

Say I have a bunch of code before and after a specific code block. The code surrounding the code block always stays the same but the code inside the block can change. For simplicity, consider that the surround code is a doubly nested for loop:

for(int i = 0; i<width; i++){
    for(int i = 0; i<height; i++){

        // changing code block

    }
}

Now, I want to tell the compiler to insert different bits of code into the code block at different instances in my program. How would I go about doing something like this?

like image 734
BigDru Avatar asked Dec 11 '25 21:12

BigDru


2 Answers

If I understand you right, you have to declare an interface with a method and send an object reference of a class that implements the interface that holds the logic to implement. Basic code example:

interface Foo {
    public void doFoo(int i, int j);
}

class Bar implements Foo {
    @Override
    public void doFoo(int i, int j) {
        System.out.println(i + j);
    }
}

class Baz implements Foo {
    @Override
    public void doFoo(int i, int j) {
        System.out.println(i - j);
    }
}

In your current code block:

public void doXxx(Foo foo) {
    //...
    for(int i = 0; i<width; i++){
        for(int j = 0; j<width; j++){
            // changing code block
            //solved using interfaces
            foo.doFoo(i, j);
        }
    }
    //...
}

Now you can call doXxx using an implementation of Foo, like an instance of Bar or Baz:

doXxx(new Bar());
doXxx(new Baz());
like image 65
Luiggi Mendoza Avatar answered Dec 13 '25 10:12

Luiggi Mendoza


I would use external services to run the needed code, and use IOC (or whatever you like) in order to configure the proper service for each instance.

private MyService myService;

for(int i = 0; i<width; i++){
    for(int i = 0; i<width; i++){

        myService.myMethod();

    }
}

And use:

public interface MyService {
    public void myMethod();
}

public class MySimpleService {
    @Override
    public void myMethod() {
        // Do whatever...
    }
}

public class MyOtherService {
    @Override
    public void myMethod() {
        // Do whatever...
    }
}
like image 41
BobTheBuilder Avatar answered Dec 13 '25 11:12

BobTheBuilder



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!