Thursday, April 7, 2011

Final is my favorite Java keyword

Final is my favorite keyword and modifier in Java.  For fields, love it even more than private.  Think about it, you don't even need private on your field if it's final.  Not with a truly non-mutable data type at least, so collections and things of that nature excluded of course.

In fact I wish final was the default modifier for all my fields, variables, and parameters.  You should have to announce your intention to overwrite an already initialized object reference.  After years, I find it is a rarity.

There is nothing worse that digging through a large 500 line function and not being able to see what is changed and where.  Even more frustrating when you go to extract a method from said too-large codeblock and cannot do so easily because of the sprawled out variable declarations and initializations and the occasional "I like this variable name so I'll reuse the reference" laziness.

The trouble is it looks so terrible when used properly, which should be almost everywhere!  It looks pretty satisfying on fields, but over all parameters and variables it gets to be a little much.  It can actually make it harder to find the non-final object references.  And if you find one, was it intentional or just overlooked? Change it and find out I guess.

That is why one of my biggest wishes for the Java language is that final be the default and there to be a mutable or similar keyword for the handful of times you need it.  It would be an excellent aid to readers of your code, "watch out this thing is going to change." Compilers could even check to see if you have flagged something mutable and aren't actually mutating it.  That should be a compile error for variables and parameters, perhaps not for fields though.

Obviously we can't exactly do that ... not so directly.

We have some advantages now we didn't have when Java was created.  Annotations.  When Java was created there had to be long and deliberate thinking as to what the defaults should be.  Everyone would have to live with them and they'd last forever.  These days, however, a simple annotation or two on a Java source file could serve as a clean way to change such defaults in an obvious and documented way that can make the code in question far easier to read.  It would be syntactic sugar of course and that annotation and the defaults it specifies would compile away just as imports do.

A small bit of sugar with big payoff in ease and readability.


Ortwin said...

Cool, and if all your variables are final, you don't even need to run the code! You can optimize it away completely in the compiler and reduce it to its (constant) result.

tug said...

I agree completely.

Adam Rabung said...

Two little nits - a private final field is still better than a final field, because it encapsulates/hides the field - minimizes api surface area. Also, "mutable" keyword would not be good because final Objects _are_ mutable, they're just not reassignable.

David Blevins said...

@Adam Good point. Perhaps 'assignable' is the better keyword. In terms of a get method for a final reference to a non-mutable object, was more making a statement of technical necessity rather than one of best practices. Likely high on the list of things we do that hotspot will remove because it isn't technically necessary.

Viktor Klang said...

Ortwin: Well, I kinda need branching, so your fold-into-constant-result will have to wait.

Brian Goetz said...

This is exactly the sort of thing you can do for yourself with JSR-308 and the Checkers framework. Write your own @FinalByDefault class annotation and @Mutable field annotation, write a checker to verify your rules, and you're done.

You can start on this today using the JSR-308 prototype now!

timothymattie said...

more or less into collaboration. Wow! Right now probably weigh over head but what do you guess(ebaan) is direction of a WLAn Coova Hotspot is it worth looking up related. API's, FBML's,FBTS'S,and FQL's.Coova has good Open source, and Java credentials! Appreciated!!

Narender Godara said...

Packers and movers Coimbatore
Packers and movers Dehradun
Packers and movers Delhi
Packers and movers Dwarka delhi

Mary Brown said...

Java EE article is practical oriented and real time examples. How Java EE address the enterprise development is very important. for that you need a practical orieneted Java Training you need.

Online Java EE Training
Online Java Training from India
Java Training Institutes in Chennai
Java Training in Chennai
Java Training

The Ahir said...

Happy New Year 2016 Messages

Happy New Year 2016 Images

New Year Wishes

IPL 2016 Schedule

IPL Schedule 2016

IPL 9 Schedule

IPL 2016

IPL 2016 Schedule

IPL Fixtures 2016

IPL 2016 Live Score

IPL 2016 Live

2016 IPL Schedule

ICC T20 World Cup 2016 Schedule

T20 World Cup 2016 Live Streaming

T20 World Cup 2016

Cricket World Cup 2016 Schedule

T20 Cricket World Cup 2016 Schedule

National Flag of India

indian national flag

indian flag pictures

national flag images

indian flags

Govt Jobs Jobs Recruitment Govt Jobs

Latest Jobs Jobs Latest Recruitment Govt Jobs

Anna said...

Great Explanation with appropriate example.
Online Java Training
Online Java Training India

Ranveer Patil said...

Thanks you for this post… great information.
Watch Live Cricket Streaming Online Free Score
Live Cricket score crickinfo
Watch live Matchs South Africa vs India test

Amrish Singh said...

icc t20 world cup
icc t20 world cup 2016
icc t20 world cup 2016 live
icc t20 world cup 2016 live streaming
icc t20 world cup live
t20 world cup 2016
t20 world cup
t20 world cup 2016 live
t20 world cup 2016 live streaming
t20 world cup live

icc t20 world cup
icc t20 world cup 2016
icc t20 world cup 2016 live
icc t20 world cup 2016 live streaming
icc t20 world cup live
t20 world cup 2016
t20 world cup
t20 world cup 2016 live
t20 world cup 2016 live streaming
t20 world cup live

IPL t20
IPL t20 2016
IPL t20 2016 live
IPL t20 2016 Streaming
IPL t20 2016 live Streaming
IPL t20 2016 Streaming
IPL t20 live Streaming
IPL live Streaming
IPL live
IPL t20 live
mobiles phone

Mothers Day said...

Thankful Happy Mothers Day Messages From Husband
Long Happy Mother Day Messages From Husband
Cute Happy Mothers Day Poems & Sayings For Friend
Mothers Day Poems
Mothers Day Poems 2016
Happy Mothers Day Poems
Happy Mothers Day Poems 2016

Mothers Day 2016 Poems
2016 Mothers Day Poems
Happy Mothers Day 2016 Poems
2016 Happy Mothers Day Poems

Poems Mothers Day
Poems Mothers Day 2016
Poems Happy Mothers Day
Happy Mothers Day Poems 2016
Court Marriage Procedure In Thane
Poems For Mothers Day 2016
Poems For 2016 Mothers Day
Poems For Happy Mothers Day 2016
Poems For 2016 Happy Mothers Day
2016 Happy Mothers Day

Riya Malhotra said...

very nice blog
RRB Bilaspur NTPC Result
RRB Bhubaneswar NTPC Result
RRB Ahmedabad NTPC Result
RRB Bangalore NTPC Result
RRB Bhopal NTPC Result

Lisa.M. Henry said...

Hotmail is an email account of Microsoft Corporation. Like Google's Gmail, it is full of features usually xuyen.Neu of an email you want to register an account please follow these basic steps:
Hotmail login

Hotmail review

Sign in to hotmail

Login to hotmail

Recover hotmail password

Tank Trouble is a very interesting flash game about tanks, about war and about destruction

One Penguin Takes it personally when he is surfing the web and stumbles upon a web site telling him that he cant fly, after that he sets his mind to research and practice flying until he can prove the world that he can..

Strike Force Heroes is a new game action-packed shooter from the creators of Raze; with 3 game modes, 15 campaign missions and over 65 weapons.
Strike Force Heroes 4

Strike Force Heroes

Rohit Roy said...

Want to watch the live streaming of the first semi final of Euro Cup 2016, just check out Wales Vs Portugal Live Streaming

appu said...

Public Holidays 2017
Happy New Year 2017 SMS
enem 2016 resultado
cat 2016 result
new year 2017 wallpapers
resultado enem 2016
Happy Diwali Messages
Happy Onam Images Happy Onam Merry Christmas Christmas Whatsapp Status

Zheng junxai5 said...

cheap rolex watches
fit flops
coach outlet
oakley sunglasses
cheap toms shoes
louis vuitton purses
louboutin sale clearance
christian louboutin sale
true religion outlet
louboutin femme
cheap basketball shoes
louis vuitton bags
polo shirts
rolex watches outlet
oakley outlet
mont blanc pen
michael kors outlet
oakley sunglasses wholesale
michael kors handbags
kd 7 shoes
michael kors outlet
adidas nmd
coach factory outlet online
concords 11
longchamp outlet
louis vuitton outlet
rolex watches for sale
michael kors handbags
coach outlet store online
coach outlet online
coach factory outlet online
michael kors outlet
cheap jerseys
mont blanc pens outlet
vans sneakers
air jordan 4
basketball shoes
lebron 13
cheap rolex watches
lebron 13 shoes

Hua Cai said...

christian louboutin uk
michael kors canada
ugg boots sale
hermes bags
michael kors uk
adidas nmd
mbt shoes outlet
louis vuitton neverfull sale
football shirts
michael kors outlet online
ugg boots
michael kors outlet
longchamp outlet
michael kors outlet clearance
lululemon pants
michael kors uk
tiffany and co
ugg boots
lacoste polo shirts
ugg australia
true religion outlet
iphone case
omega outlet
michael kors outlet
mulberry handbags sale
tiffany jewellery
uggs outlet
mulberry uk
michael kors outlet
mac cosmetics sale
michael kors uk
rolex watches outlet
tiffany outlet
michael kors handbags clearance
ray ban sunglasses sale

Somnath Brahma said...

Have you heard about National Black Cat Day which is two days prior to National Cat Day.
Check out my blog to get all the latest information about it and stay updated.

Unknown said...

Never decide on long-term issues are short-term emotional moment
Friv 2 Games | Unblocked Gammes 77 | Yepi 2 | Unblocked Games | Unblocked at School | Unblocked Games 66 | Unblcoked Minecraft | ABCya | Pbs

Meiqing Xu said...

louis vuitton outlet
true religion outlet
nike air force 1
michael kors outlet
ugg boots
christian louboutin shoes
louis vuitton handbags
rolex daytona
converse outlet
coach outlet

Meiqing Xu said...

timberland boots
vans outlet store
longchamp handbags
hermes birkin
birkenstock shoes
christian louboutin shoes
cheap jordans
ralph lauren outlet online
cheap ugg boots
louboutin uk

Tokecash said...

We prefer to honor several other net sites around the internet, even when they arent linked to us, by linking to them. Below are some webpages worth checking out.

always a huge fan of linking to bloggers that I love but dont get a whole lot of link appreciate from :)

Agen Poker Online Indonesia Terbaik Terpercaya Terbesar 2017

Unknown said...

the north face jackets
coach outlet clearance
louis vuitton handbags
adidas trainers
cheap jordans
michael kors handbags
nba jerseys
coach outlet online
toms shoes
oakley sunglasses

Simuka Rafeal said...

A child asked God: "If everything was written in fate so why should the convention?".
Xbox One

Thomas pedro said...

Banks may think about the previous history of installments and credit encounters of potential borrowers, yet they don't think around a candidates work, ways of managing money, individual notoriety, and achievements. cash advance chicago

Thomas pedro said...

No wage confirmation secured credits are a great approach to get advance without irritating for course of action of salary explanation; in the event that you are a duty payee and have any sort of expense installment receipt then likewise you can display it as a substitute of pay detail. cash advance

Thomas pedro said...

A PC graduate and adores to travel. Perusing current news in the web is one of his past circumstances. Taking photos of the things around him completely fulfills him. He cherishes to play badminton and his most loved pets are felines and stroll with them in the recreation center with a few mutts. auto title loans

chenmeinv0 said...

louis vuitton
true religion outlet
michael kors outlet online sale
ray ban sunglasses
ray ban sunglasses
louis vuitton
adidas nmd
adidas outlet
michael kors outlet
dallas mavericks jerseys

caiyan said...

seattles eahawks jerseys
coach outlet
christian louboutin shoes
cheap mlb jerseys
nike roshe
ralph lauren
polo ralph lauren
coach outlet online
huston texans jerseys
louis vuitton outlet online

chenmeinv0 said...

michael kors handbags
lebron 12 shoes
coach outlet
ray ban outlet
kd 8 shoes
calvin klein jeans
adidas nmd xr1
caterpillar boots
levis jeans outlet
reebok outlet

Karthika Shree said...

Finding the time and actual effort to create a superb article like this is great thing. I’ll learn many new stuff right here! Good luck for the next post buddy..
Java Training in Chennai