• Post Reply Bookmark Topic Watch Topic
  • New Topic

When to use final variables  RSS feed

 
Nick Petas
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are there any rules about when to use final variables in a class?
Thank you.
 
Saket Barve
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

You'll want to consider using final if logic demands that the value not be modified from its original. Were you asking about the grammar around it?
 
Kevin Workman
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nick Petas wrote:Are there any rules about when to use final variables in a class?
Thank you.


What do you think the rules are? What happened when you tried to use it in different scenarios? What did google tell you?
 
Vinod Vinu
Ranch Hand
Posts: 217
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Final variables means its value cannot be changed throught out compilation. It remains final.
like
private static final float pie=3.14;

it depends on your application requirements. If you see, today the value of a pie is 22/7 or 3.14 which is a constant value. so make it final because this value should not be changed as lot of calculation would have been done using that in an application. But in future, it is possible that the value could be changed from 3.14 to say 3.20, then in that case you just need to change the value of this final variabel to 3.20 without altering your business logic. I hope it is clear to you now
 
Stephan van Hulst
Saloon Keeper
Posts: 7987
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use final as much as you possibly can. Make all your variables final, unless they have to change. Usually references to collections (lists, maps, sets, etc) are prime candidates to be made final.

Make all your classes final, unless you explicitly design them for inheritance.

Every final that you use makes it easier for someone to understand your code. In some cases it will even enhance performance (although it shouldn't be very noticeable).

These are the guidelines I code by. Maybe someone else can make a more convincing case to not do things this way, but I've had good experiences with it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!