Jitesh Sojitra Jitesh Sojitra - 2 months ago 8
Java Question

Coverting same named function into single function using cascading in Java

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.

Answer

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