我知道硬編碼任何東西都不好。通常我們通過配置文件來完成大部分的環境變量。例如,數據庫屬性,項目配置,log4j,輸入,輸出。今天這種編程風格太多了嗎?
但我見過有人寫這樣的代碼:
public void updateExistedRecord(SgsnMapping sgsnMapping) throws Exception {
PreparedStatement ps = null;
try {
String updateSql = "";
updateSql += "UPDATE " + schema + "." + tableSgsnMapping + " SET ";
//other where clause
ps = dbConn.prepareStatement(updateSql);
ps.executeUpdate();
} catch (Exception ex) {
logger.error("Error when update an existing record on " + tableSgsnMapping + " table.\n" + ex.getMessage(), ex);
throw ex;
} finally {
SqlHelper.close(ps);
}
}
的重點是放在桌子上 - tableSgsnMapping,它是寫在這樣的方式與其他地方:
private String tableSgsnMapping = ConstantManager.TABLE_SGSN_MAPPING;
反過來,該TABLE_SGSN_MAPPING是定義其它地方:
public final static String TABLE_SGSN_MAPPING = "OBDUA_SGSN_MAPPING";
是不是太多了?該表不會改變它的名字,它會一直存在。爲什麼不在程序中硬編碼?爲什麼?
表不會改變它們的名字,但是在代碼中可以有多個表名的引用,即常量可以用在多個地方。你真的不需要私人String tableSgsnMapping = ConstantManager.TABLE_SGSN_MAPPING和ConstantManager.TABLE_SGSN_MAPPING可以被直接使用,並且通過使用靜態導入可以進一步使用,你可以將它縮減爲TABLE_SGSN_MAPPING – 2011-05-16 07:28:24
最適合回答爲什麼問題的人是誰寫了那個代碼。你爲什麼不問他?你們倆都比我們以往任何時候都更瞭解這個項目的特殊情況。 – meriton 2012-02-11 16:00:32