假设我想读取以下文件:
TestFile;100
进入全班的字段:
public class MyReader {
String field1;
Integer field2;
}
阅读内容有两种稍微不同的方式:
公共类MyReader {
public void loadValues(File file) throws IOException {
//a generic method that reads the content file to a string throwing an IOException
String line = readFileToString(file);
String[] values = line.split(";");
field1=values[0];
field2=Integer.parseInt(values[1]);
}
//then i'll have well known getters:
public String getField1() {
return field1;
}
public Integer getField2() {
return field2;
}
现在第二个成语是:
private String[] values; //made the values a class field
public void loadValues(File file) throws IOException {
//a generic method that reads the content file to a string throwing an IOException
String line = readFileToString(file);
values = line.split(";");
}
public String getField1() {
return values[0]
}
public Integer getField2() {
return Integer.parseInt(values[1]);
}
最大的区别在于异常管理。我故意忽略了在这两种情况下可能发生的两个运行时异常:
如果文件包含少于两个fields
NumberFormatException
(如果整数解析失败),则为
优先逼近
所有字段都在启动时加载。只要其中一个不能被解析,我就得到了NumberFormatException
。如果字段少于所需的字段,我将得到超出界限的异常。这听起来不错,尤其是如果我想确保所有字段值的正确性,我将使用特定的字段值:失败快速范例。假设我有100个字段,该记录包含一个错误,该错误将被记录到一个文件中以进行故障排除。实际上,这段代码提供了如下内容:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
也就是说:我得到了错误,导致错误的值,给出错误的行号,而不是字段名。对开发人员有好处,对通常无法访问源代码的系统engeneer没有好处。
第二次逼近
字段只有在通过getter访问时才被“提取”并从数据字符串中解析。在相同的情况下,每个getter可能返回上述两个错误。有一定程度的“容错”,而不是“快速失败范式”。如果记录的第100字段包含不正确的值,但类的客户端不调用它的getter,则永远不会抛出异常。另一方面,当调用不正确值的getter时,记录的异常将包含导致问题的字段的信息(在堆栈跟踪中):
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:449)
at java.lang.Integer.parseInt(Integer.java:499)
at com.test.MyReader.getField2(MyReader.java:39)
at com.test.MyReader.test(MyReader.java:33)
at com.test.MyReader.main(MyReader.java:16)
问题
这两种方法各有优缺点,人们可以说,所采用的决定取决于环境。问题如下:
。
发布于 2012-06-15 02:00:10
首先,当您将values[]数组存储为局部变量时,第二种方法将无法工作,其他函数也无法访问它(在您的示例中是getter)。
第二,不要将异常抛出在getter中,因为您公开的api将具有误导性,并且不符合任何约定。
第三,与其自己解析字符串,不如考虑使用准备好的库进行csv解析,而不是重新发明轮子,例如。http://opencsv.sourceforge.net/
第四,为csv记录创建一个简单的POJO对象,您可以在为每个字段分配值的同时检查错误,然后抛出异常,提供默认值等等。
希望这有帮助
https://stackoverflow.com/questions/11048399
复制相似问题