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();
}
Which do you prefer and why?
Variables that are declared inside a method are called local variables because they can only be utilized and referenced in the method itself. Take a look at the code below showing the add() method with a local variable inside.
Answer: Yes — the scopes will not overlap so there will be two local variables, one per method, each with the same name.
Final is the only applicable modifier for local variables : The only applicable modifier for local variable is final.
I prefer the first version for all the reasons you've mentioned. In particular (just to spell out your fourth point), it means you're definitely going to get consistent results... you could get horribly nasty results with the second version if getVehicle()
returned a Car
on the first call, then a Bike
on the second...
The performance side doesn't bother me (I'll happily call List.size()
repeatedly, for example) but readability, consistency and non-repeating are all much more important. Essentially the first snippet conveys the idea of "get a value, then use it" much more effectively than the second does.
So yes, I'm with you... is anyone recommending the second form to you?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With