Java编码风格,局部变量vs重复的方法调用 [英] Java coding style, local variables vs repeated method calls
本文介绍了Java编码风格,局部变量vs重复的方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我喜欢使用局部变量而不是多次调用同一个方法。
/ *
*我更喜欢这个
* /
车辆= person.getVehicle ()
if(vehicle instanceof Car){
Car car =(Car)vehicle;
car.openSunroof();
} else if(vehicle instanceof Bike){
Bike bike =(Bike)vehicle;
bike.foldKickstand();
}
/ *
*而不是
* /
if(person.getVehicle()instanceof Car){
Car car = person.getVehicle();
car.openSunroof();
} else if(person.getVehicle()instanceof Bike){
Bike bike =(Bike)person.getVehicle();
bike.foldKickstand();
}
- 我相信第一种方法是
- 我认为第二种方式违反了DRY原则
- 我发现第一种方式更易读,更容易调试。
解决方案
是的,第一个是绝对更好。我永远不会去第二种方法。
但是你应该考虑更多地使用多态性。依靠 instanceof
这么重的是不好的OO设计。
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?
解决方案
Yeah the first one is definitely better. I would never go for the second method.
But you should think of using polymorphism more. Relying on instanceof
so heavyly is not good OO design.
这篇关于Java编码风格,局部变量vs重复的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文