Java中的代码重构,声明和操作多时,哪个更好?

Code refactoring in Java, which one is better when there are multiple declarations and operations?

我在写一个有很多声明和操作的方法时有一个问题,哪个更好以便以后我参考它时我会更好地掌握,或者这两种方法在技术上是不是一样。

-- 第一种方式(先写好所有的声明再依次操作):

Map<String, String> transferToStation1 = new HashMap<>();
Map<String, String> transferToStation2 = new HashMap<>();

transferToStation1.put(MetroUtil.LINE, line2Name);
transferToStation1.put(MetroUtil.STATION, station2Name);
transferToStation2.put(MetroUtil.LINE, line1Name);
transferToStation2.put(MetroUtil.STATION, station1Name);

var json1 = new JsonParser().parse(new Gson().toJson(transferToStation1)).getAsJsonObject();
var json2 = new JsonParser().parse(new Gson().toJson(transferToStation2)).getAsJsonObject();

station1.add(MetroUtil.TRANSFER, json1);
station2.add(MetroUtil.TRANSFER, json2);

-- 第二种方式(一声明一个变量,就写它的所有操作):

Map<String, String> transferToStation1 = new HashMap<>();

transferToStation1.put(MetroUtil.LINE, line2Name);
transferToStation1.put(MetroUtil.STATION, station2Name);

Map<String, String> transferToStation2 = new HashMap<>();

transferToStation2.put(MetroUtil.LINE, line1Name);
transferToStation2.put(MetroUtil.STATION, station1Name);

var json1 = new JsonParser().parse(new Gson().toJson(transferToStation1)).getAsJsonObject();

station1.add(MetroUtil.TRANSFER, json1);

var json2 = new JsonParser().parse(new Gson().toJson(transferToStation2)).getAsJsonObject();

station2.add(MetroUtil.TRANSFER, json2);

一般建议是尽可能晚声明变量,或尽可能接近它们的使用

换句话说,不要预先声明变量。相反,在声明后立即初始化并使用它们。

因此,第二种方式更好。

话虽如此,为不同的变量复制本质上相同的代码也是一种潜在的代码味道,可能受益于重构和删除冗余。将变量命名为 thing1thing2 几乎 从来都不是 一个好主意,这表明您可能想要使用数组或循环,或两者兼而有之。