作者:王德筠宛吟玟华 | 来源:互联网 | 2024-11-02 09:00
在Java编程中,为了提高代码的可读性和执行效率,建议优先使用局部变量来存储方法的返回值,而不是多次调用同一个方法。这样不仅可以减少方法调用的开销,还能避免潜在的性能问题。此外,使用局部变量还可以增强代码的可维护性和调试便利性。
I prefer to use local variables rather than multiple calls to the same method.
我更喜欢使用局部变量,而不是多次调用同一个方法。
/*
* I prefer this
*/
Vehicle vehicle = person.getVehicle()
if (vehicle instanceof Car) {
Car car = (Car) vehicle;
car.openSunroof();
} else if (vehicle instanceof Bike) {
Bike bike = (Bike) vehicle;
bike.foldKickstand();
}
/*
* Rather than this
*/
if (person.getVehicle() instanceof Car) {
Car car = (Car) person.getVehicle();
car.openSunroof();
} else if (person.getVehicle() instanceof Bike) {
Bike bike = (Bike) person.getVehicle();
bike.foldKickstand();
}
- I believe that the first way is going to perform a tiny bit faster
- 我相信第一种方法会更快一点。
- I think the second way violates the DRY principle
- 我认为第二种方法违反了干原则
- I find the first way more readable and easier to debug (... OK negligible because I could step over)
- 我发现第一种方法可读性更好,而且更容易调试(……)可以忽略,因为我可以跨过去)
- I don't want to have to deal with the possibility of changed object state
- 我不想讨论对象状态改变的可能性
Which do you prefer and why?
你喜欢哪一种,为什么?
7 个解决方案