Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java coding style, local variables vs repeated method calls

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?

like image 487
crowne Avatar asked Feb 09 '10 10:02

crowne


People also ask

Are method variables local?

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.

Can local variables in different methods of the same class have the same name?

Answer: Yes — the scopes will not overlap so there will be two local variables, one per method, each with the same name.

Which modifiers are used with local variable in Java?

Final is the only applicable modifier for local variables : The only applicable modifier for local variable is final.


2 Answers

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?

like image 157
Jon Skeet Avatar answered Oct 20 '22 20:10

Jon Skeet


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.

like image 44
fastcodejava Avatar answered Oct 20 '22 21:10

fastcodejava