tags:

views:

60

answers:

2

I have a logic where I am building XML data in a method. The XML data is built off either a ArrayList or a ModelClass. For both of these, the logic to build XML is exactly the same. Currently I have 2 separate methods to handle this and thus code duplication. I want to use 1 single method which can take either a collection or a class as a parameter. Is it possible? Do I need to think of some other way to optimize this? Thanks for your help.

A: 

Why not create one method that accepts a collection and then iterate the collection and process each item. This way you can call the method with a collection of many or a collection of one item - they will all be processed the same way.

This assumes that you would rather offset the inconvenience to the caller of the method since they will be required to create a collection in the case of a single item. If that is a concern to you then you should simply create two methods and have the method that accepts the collection call the method that selects the single value so that the implementation is still shared.

Andrew Hare
And Collections.singleton() is an easy way to make a collection with one entry.
ChrisH
+2  A: 

Refactor the 2 methods to a single private method taking an Object argument or whatever global type it is actually expecting and let the both public methods call it. E.g.

public void doStuff(Class<?> c) {
    doGenericStuff(c);
}

public void doStuff(Collection<?> c) {
    doGenericStuff(c);
}

private void doGenericStuff(Object c) {
    // Do whatever you did in each of the original methods.
}

Or maybe is this even possible (I have no idea what the methods are supposed to do and what "global type" they expects).

public void doStuff(Class<?> c) {
    doStuff(Collections.singleton(c));
}

public void doStuff(Collection<?> c) {
    // Do whatever you did in the original method.
}
BalusC