【发布时间】:2017-11-02 01:13:14
【问题描述】:
为了不创建不必要的变量,并且避免在方法范围内变得杂乱无章,否则我会创建一个临时文件来保存我将要处理的所有文件在整个方法的其余部分中进行引用。
我不喜欢这个解决方案,因为它每次运行时都会创建一个数组对象,而无需创建数组对象。
我也不能使用变量数组或变量墙,而是直接引用 get 方法,但这会造成很多冗余,因为我重复执行相同的方法,我更不喜欢这样。
public void savePrices() {
MFilePrices file[] = {AutoEcon.files().getPrices(), AutoEcon.files().getIntangibles(), AutoEcon.files().getGroups()};
for (String price : sellPrices.keySet()) {
if (EconItem.fromString(price) != null) {
file[0].setPrice(price, sellPrices.get(price).getExpression());
file[0].setBuyRate(price, sellPrices.get(price).getBuyRate());
} else if (file[1].getLabels().contains(price)) {
file[1].setPrice(price, sellPrices.get(price).getExpression());
file[1].setBuyRate(price, sellPrices.get(price).getBuyRate());
} else if (file[2].getLabels().contains(price)) {
file[2].setPrice(price, sellPrices.get(price).getExpression());
file[2].setBuyRate(price, sellPrices.get(price).getBuyRate());
}
}
}
public Double setExpression(String id, String expr) {
savePrices();
MFilePrices file[] = {AutoEcon.files().getPrices(), AutoEcon.files().getIntangibles(), AutoEcon.files().getGroups()};
if (EconItem.fromString(id) != null)
file[0].setPrice(id, expr);
else if (file[1].getLabels().contains(id))
file[1].setPrice(id, expr);
else if (file[2].getLabels().contains(id))
file[2].setPrice(id, expr);
else return null;
sellPrices.clear();
total=0;
loadPrices(AutoEcon.plugin());
return sellPrices.get(id).getPrice();
}
另一种解决方案可能是在我从中获取文件的 FilePool 类中创建一个数组,其中包含这三个配置文件,或者一个将它们放入数组并通过数组发送的方法。但是,后者只是将问题转移到另一个类,而前者仍在创建一个并非完全必要的单个数组。 这两种解决方案都只是将问题从一类转移到另一类。
public class FilePool {
private Config config;
private Prices prices;
private Intangibles i;
private Groups groups;
private Logs econLogs;
private ItemAliases a;
public FilePool(AutoEcon pl) {
config = new Config(pl);
prices = new Prices(pl);
i = new Intangibles(pl);
econLogs = new Logs(pl);
a = new ItemAliases(pl);
new ReadMe(pl);
}
public Config getConfig() {
return config;
}
public Prices getPrices() {
return prices;
}
public Groups getGroups() {
return groups;
}
public Intangibles getIntangibles() {
return i;
}
public Logs getLogs() {
return econLogs;
}
public ItemAliases getAliases() {
return a;
}
}
(忽略 FilePool 类中的愚蠢变量名称,我只是喜欢它们都排列得如此完美的事实。将在发布前适当命名) 我知道我对这个根本不会影响正在运行的程序的小东西有点过分了,但是在过去我的代码的每一个小细节一直被我的同事骚扰之后,我已经成长为做一个完美主义者。
感谢所有花时间阅读本文的人。
【问题讨论】:
标签: java optimization code-formatting conventions