Currently, in a utility class I have methods like so:
public static String getNextAvailableNumber(List<MyObject> currentObjects)
{
int nextNumber = UtilClass.getNextAvailableNumberAsInteger(currentObjects, null);
return UtilClass.formatNumber(nextNumber); //formats number as string
}
public static int getNextAvailableNumberAsInteger(List<MyObject> currentObjects, List<String> otherUnavailableNumbers)
{
//returns nextNumber as int.
}
I now find myself wanting to add another method...
public static String getNextAvailableNumber(List<String> unavailableNumbers)
{
int nextNumber = UtilClass.getNextAvailableNumberAsInteger(null, unavailableNumbers);
return UtilClass.formatNumber(nextNumber);
}
You may notice that I would end up with a List argument in both places, causing a method has same erasure compiler error.
I'm considering the following solution..
//replace old getNextAvailableNumber() with generic version
public static String getNextAvailableNumber(List<?> objects)
{
List<MyObject> objectList = new ArrayList<MyObject>();
List<String> stringList = new ArrayList<String>();
if (objects.get(0) instanceof MyObject)
{
objectList = (List<MyObject>) objects;
}
else if (objects.get(0) instanceof String)
{
stringList = (List<String>) objects;
}
int nextNumber = UtilClass.getNextAvailableNumberAsInteger(objectList, stringList);
return UtilClass.formatNumber(nextNumber);
}
From what I've read, using instanceof
is generally a sign that something can be done in a better way. Is there a better way? How should I go about refactoring this?
MyObject
lacks realistic details. \$\endgroup\$