我的课堂上有很多参数,其中许多彼此相关。
首先,我有类似以下内容:
public class MyClass {
private int[] filterA = {4,40};
private int filterAPasses = 3;
private String dataFilePath = "...";
private int dataChannels = 4;
private int dataFreq = 300;
private int[] timeRange = {30,40};
}
嗯,我不是很满意,在声明本身中也不容易理解,也不太方便使用,因为我有很多
filterA[0]
,我必须记住索引0
和索引1
的含义。因此,我改为:
public class MyClass {
private interface filterA {
int left = 4;
int right = 40;
int passes = 4;
}
private interface dataFile {
String path = "...";
int channels = 4;
int frequency = 300;
}
private interface timeRange {
int from = 30;
int to = 40;
}
}
这是更好的方法,它允许我做一些不错的事情,例如
filterA.left
,甚至可以将javadoc添加到left
但是以某种方式,我很难用
interface
来做到这一点。那是个好方法吗?有更好的做法吗?编辑:
好的,我完全错了,因为我不知道使用
interface
这些参数将是最终的。绝对不是一个好方法。那么什么是好方法呢?
最佳答案
如果您觉得更简单,则可以使用嵌套类。
public class MyClass {
static class FilterA {
int left = 4;
int right = 40;
int passes = 4;
}
private final FilterA filterA = new FilterA();
static class DataFile {
String path = "...";
int channels = 4;
int frequency = 300;
}
private final DataFile dataFile = new DataFile();
private interface TimeRange {
int from = 30;
int to = 40;
}
private final TimeRange timeRange = new TimeRange();
}
或仅使用注释和有意义的名称。 (我的偏好)
public class MyClass {
// fliter settings
private int filterALeft = 4;
private int filterARight = 40;
private int filterAPasses = 3;
// data path attributes
private String dataFilePath = "...";
private int dataChannels = 4;
private int dataFreq = 300;
// time range
private int timeRangeFrom = 30;
private int timeRangeTo = 40;
}