2

I have the following pattern repeated many times:

for() {
    //Same Code Here
    for() {
        //Same Code Here
        if() {
            //Only Part That Is Different
        }
    }
}

I was thinking they way not repeat myself would be to beak in into it's own method and return something inside the if:

public MyObject myMethod(MyObject myObject) {
    for() {
        //Same Code Here
        for() {
            //Same Code Here
            if() {
                return myObject;
            }
        }
    }
}

That way I can call myMethod(), assign the returned value to a variable and do what I want with it. This won't compile because nothing is returned when the if condition isn't met. I don't want anything to happen when the if condition isn't met.

Am I going down the right path, or is there a better way to remove my duplicate code?

6
  • 1
    return inside the if will break the loop, not sure if that's what you want. Can you add a more "realistic" code? Commented Mar 24, 2019 at 7:03
  • 1
    If method return type is present then you must need to return something from the method, here you are returning only from the if condition, and if condition is not satisfied then method is not returning anything and because of that JVM shows compilation error. add return statement at end of method will solve the problem Commented Mar 24, 2019 at 7:03
  • How is the code in the if "different"? If everything in the method is the same except that you're returning a different object that you passed in, a) how is that code "different', and b) what's the point of any of this...why pass an object in just to return it to the caller unchanged? Or is this method using the passed in value somehow? I have no idea what you're really asking here. - as @molamk said, can you provide something realistic for us to look at? Why don't you show us two blocks of code that are mostly the same, that you want to refactor into a method. Commented Mar 24, 2019 at 7:09
  • I understand why it isn't compiling. It expects a return value and nothing is returned when the if condition isn't met. I really don't want anything to happen when the if condition isn't met though. I just don't want code in my for loops repeated 20 times. I'm just asking the best way to not repeat all the duplicate code in the for loops. Commented Mar 24, 2019 at 7:18
  • @AjAnderson read the answer you got. It's the proper way. You want to pass "a piece of code to execute inside the if" as argument to a method. That's what lambdas, and thus functional interfaces like Consumer, Runnable, etc., are for. Just like, when you want a Thread to execute something, you pass it a Runnable. Commented Mar 24, 2019 at 7:26

3 Answers 3

3

If you are using at least java 8 you do the following:

public void myMethod(MyObject obj, Consumer<MyObject> action) {
  for() {
    for() {
      if() {
        action.accept(obj)
      }
    }
  }
}

Now you can call this method with different actions passed into it :

myMethod((obj) -> System.out.println(obj))

Sign up to request clarification or add additional context in comments.

Comments

1

If you are using Java 7 or before, you can use an interface as a parameter to myMethod. Then in the code where you want something different to happen, call an abstract method on the interface. Different implementations of the abstract method will cause something different to happen.

public interface DoSomething {

    public void doingSomething();
}
public class DoX implements DoSomething {

    public void doingSomething() {
        System.out.println("doing x");
    }
}
public class DoY implements DoSomething {

    public void doingSomething() {
        System.out.println("doing y");
    }
}
public class MyObject {
    
    public void myMethod(DoSomething doSomething) {
        for(int i = 0; i < 3; i++) {
            System.out.print(i);
            for(int j = 0; j < 3; j++) {
                System.out.print(j);
                if(i == 1 && j == 2) {
                    doSomething.doingSomething();
                }
            }
        }   
        System.out.println("");
    }
}

Then pass the concrete implementations of the abstract method as arguments where you want something different to happen

public class MyApp {
    public static void main(String[] args) {
        
        MyObject myObject = new MyObject();

        myObject.myMethod(new DoX());
        myObject.myMethod(new DoY());

    }
}

Comments

-1

This is a one of the ways to solve the problem:

public MyObject myMethod(MyObject myObject) {
    for() {
        //Same Code Here
        for() {
            //Same Code Here
            if() {
                return myObject;
            }
        }
    }
    MyObject myObject2 = null
    return myObject2;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.