Tengo varios métodos que hacen lo mismo hasta el momento, al interconectarse con la base de datos MySQL, guardar o cargar un tipo diferente de parámetro. Actualmente, tengo un método diferente para cada tipo. ¿Cómo puedo combinar estos métodos para que sean compatibles con diferentes tipos?Métodos de refactorización que usan el mismo código pero tipos diferentes
A continuación se muestra un ejemplo de dos métodos que son muy similares pero utilizan diferentes tipos:
public static void saveLongArray(Connection con, int playerID, String tableName, String fieldName, long[] array, long[] originalArray) {
try {
for (int i = 0; i < array.length; i++) {
// Check for change before running query
if (array[i] != originalArray[i]) {
if (array[i] != 0 && array[i] != -1) {
PreparedStatement updateQuery = con.prepareStatement("REPLACE INTO `" + tableName + "` (`player_id`, `index`, `" + fieldName + "`) VALUES(?, ?, ?)");
updateQuery.setInt(1, playerID);
updateQuery.setInt(2, i);
updateQuery.setLong(3, array[i]);
updateQuery.execute();
} else {
PreparedStatement deleteQuery = con.prepareStatement("DELETE FROM `" + tableName + "` WHERE `player_id` = ? AND `index` = ?");
deleteQuery.setInt(1, playerID);
deleteQuery.setInt(2, i);
deleteQuery.execute();
}
originalArray[i] = array[i];
}
}
} catch (SQLException ex) {
Logger.getLogger(PlayerSaveHandler.class.getName()).log(Level.SEVERE, "SQL Exception while saving a long array!", ex);
}
}
public static void saveIntArray(Connection con, int playerID, String tableName, String fieldName, int[] array, int[] originalArray) {
try {
for (int i = 0; i < array.length; i++) {
// Check for change before running query
if (array[i] != originalArray[i]) {
if (array[i] != 0 && array[i] != -1) {
PreparedStatement updateQuery = con.prepareStatement("REPLACE INTO `" + tableName + "` (`player_id`, `index`, `" + fieldName + "`) VALUES(?, ?, ?)");
updateQuery.setInt(1, playerID);
updateQuery.setInt(2, i);
updateQuery.setInt(3, array[i]);
updateQuery.execute();
} else {
PreparedStatement deleteQuery = con.prepareStatement("DELETE FROM `" + tableName + "` WHERE `player_id` = ? AND `index` = ?");
deleteQuery.setInt(1, playerID);
deleteQuery.setInt(2, i);
deleteQuery.execute();
}
originalArray[i] = array[i];
}
}
} catch (SQLException ex) {
Logger.getLogger(PlayerSaveHandler.class.getName()).log(Level.SEVERE, "SQL Exception while saving an int array!", ex);
}
}
nota en ese ejemplo los tipos son tanto numérica. En un caso donde los tipos son completamente diferentes (por ejemplo, int y String), ¿qué podría hacer para evitar tener métodos near-duplicate?
He estado investigando este patrón de diseño, pero nunca habría pensado en usarlo en este caso. ¡Gracias! – jSherz
Lo único que agregaría aquí es que, dado que las matrices ahora transportarán objetos en lugar de primitivas, deberían compararse usando 'equals()' (por ej. '! Array [i] .equals (originalArray [i])' o 'compareTo()'. Además, parece que se supone que las matrices solo contienen tipos numéricos, por lo que no necesitamos un comportamiento para String, y el argumento de tipo probablemente debería ser '' solo para estar seguros –
jpm
¿Es una buena idea agregar en Java la implementación en interfaces? ¿No sería mejor que una clase abstracta? – flurdy