0

Is there any way to convert below function into one function in Java ? I tried cascading it using (TestRow ) but that doesn't work.

public void testWindow (TestRow window, String title) {
    if (window != null) {
        try {
            window.zClose(window);
        } catch (HarnessException e) {
            e.printStackTrace();
        }
        window = null;
    }
}

public void testWindow (TestColumn window, String title) {
    if (window != null) {
        try {
            window.zClose(window);
        } catch (HarnessException e) {
            e.printStackTrace();
        }
        window = null;
    }
}

Here TestRow and TestColumn is custom types.

Calling would be same way but due to custom window names, i need to copy paste same function many times which i think can be avoidable.

2
  • 1
    Do TestColumn and TestRow have common interface / abstract class to which method zClose belongs? Commented Sep 23, 2016 at 21:10
  • How can we know the implementation of zClose()? Commented Sep 23, 2016 at 21:11

2 Answers 2

3

Extract your common logic in a separate method with common windows class as a parameter and call this common method in many places. E.g.

public void testWindow (TestRow window, String title) {
    closeWindow(window);
}

public void testWindow (TestColumn window, String title) {
    closeWindow(window);
}

private void closeWindow(CommonWindowsClass window) {
    if (window != null) {
        try {
            window.zClose(window);
        } catch (HarnessException e) {
            e.printStackTrace();
        }
        window = null;
    }
}

Here CommonWindowsClass is superclass both for TestRow and TestColumn classes.

UPDATE also I suppose you actually don't need this code line window = null; at all

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

1 Comment

Thanks Andriy for the help!
2

You can use inheritance. Something like:

public abstract class Test {
    public abstract void zClose( Teste t );
}

public class TestRow extends Test {
    @Override
    public void zClose( Test t ) {
         // code...
    }
}

public class TestColumn extends Test {
    @Override
    public void zClose( Test t ) {
         // code...
    }
}

public void testWindow (Test window, String title) {
    if (window != null) {
        try {
            window.zClose(window);
        } catch (HarnessException e) {
            e.printStackTrace();
        }
        window = null;
    }
}

1 Comment

Thanks David for the help!

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.