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?