我想在java中编写干净的代码,而且我很不安全放置我的attriutes。
我经常无法决定,如果我将它们放在类的顶部,构造函数中或直接放在方法中。那里有一些规则吗?对我来说唯一的逻辑是,当在多个方法中使用这些属性时,将属性放在类的顶部。
您可以根据干净的代码评估此代码吗?我应该在构造函数中放置常量货币属性吗?我还可以在方法中放入一些类属性吗?感谢您的建议
public class CsvFileReader {
private SimpleDateFormatStringToDate formatter = new SimpleDateFormatStringToDate();
private IataExchangeRateDataSet exchangeRateDataSet= new IataExchangeRateDataSet();
private final String SEMICOLON_DELIMITER = ";";
// Currency attributes index
private final int CURRENCY_VALUE = 1;
private final int CURRENCY_ISO_CODE = 2;
private final int CURRENCY_PERIOD_START = 3;
private final int CURRENCY_PERIOD_END = 4;
public CsvFileReader(IataExchangeRateDataSet exchangeRateDataSet) {
this.exchangeRateDataSet = exchangeRateDataSet;
}
public void readCsvFile(String fileName, final int maxLengthOfColumn) {
BufferedReader fileReader = null;
try {
String line = "";
fileReader = new BufferedReader(new FileReader(fileName));
while ((line = fileReader.readLine()) != null) {
String[] tokens = line.split(SEMICOLON_DELIMITER);
//TODO: Noch auf Vollständigkeit der Zeile, Korrektheit der Datumsformate und ähnliches überprüfen
if ( tokens.length== maxLengthOfColumn && DateFormat.checkDateFormat(tokens[CURRENCY_PERIOD_START]) && DateFormat.checkDateFormat(tokens[CURRENCY_PERIOD_END])) {
//format currency value in csv
tokens[CURRENCY_VALUE]=tokens[CURRENCY_VALUE].replace(",", ".");
IataExchangeRateData iataExchangeRateData = new IataExchangeRateData(
new BigDecimal(tokens[CURRENCY_VALUE]), tokens[CURRENCY_ISO_CODE],
formatter.parseStringToDate(tokens[CURRENCY_PERIOD_START]),
formatter.parseStringToDate(tokens[CURRENCY_PERIOD_END]));
exchangeRateDataSet.getExchangeRateDataSet().add(iataExchangeRateData);
}
}
}
catch (Exception e) {
System.out.println("Error in CsvFileReader");
e.printStackTrace();
} finally {
try {
fileReader.close();
} catch (IOException e) {
System.out.println("Error while closing fileReader !!!");
e.printStackTrace();
}
}
}
}
答案 0 :(得分:1)
interface
中。有点像这样的东西
public interface CurrencyConstants {
int CURRENCY_VALUE = 1;
int CURRENCY_ISO_CODE = 2;
int CURRENCY_PERIOD_START = 3;
int CURRENCY_PERIOD_END = 4;
}
然后我只是导入界面并使用像这样的常量..
CurrencyConstants.CURRENCY_VALUE
如果常量用于多个类,这会有所帮助。干杯!
答案 1 :(得分:1)