Sunday, October 01, 2006

final by default

When talking about 'good programming practices', one thing that was recommended by a good professor of mine was to declare variables that you aren't going to modify as final. It serves two purposes:
1) A self check for yourself so you don't accidentally modify the variable down the line somewhere
2) Self documents the code: Other's reading your code know immediately of your intent.

While trying to follow this (in Java) I found all these 'final' keywords all over the place. I began to feel that it wasn't really helping. Just cluttering the codebase with 'final's.

So why not just have all variables be final by default?

Along these lines, I feel providing all the abilities of C++'s const to Java's final would be a tremendous boon. Your contracts can be better defined - not just on references but on the objects themselves.

<soapbox>Code maintainability - getting up to speed on a codebase and changing someone else's code is something that is done far more than adding new code. Anything to make readability better by clearly defining contracts/intent can only be a benefit and should be strived for.</soapbox>


SN said...

"While trying to follow this (in Java) I found all these 'final' keywords all over the place. ... So why not just have all variables be final by default?"

Do you mean "static" should also mean "final" by default?

Mohnish Rao said...

I meant that all variables should be immutable by default. You should have to specify which are modifyable rather than the other way round. Nothing to do with "static".

SN said...

Why? Is it that one typically wants most variables to be final?

Unknown said...

Mostly variables are mutable. However being lazy(like me), devs forget to declare variables they wanted by intent to be non-mutable as final. Hence there is a chance of misuse and bugs in the code. I think what Mohnish wanted to say was that the defaults should be stricter.

Similar to the mutability of variables is virtual functions. In Java, all methods are virtual by default. In .NET and C++ the developer has to specify which methods are virtual. So only when the intent is clear, does the dev reduce the strictness. Obviously this also has a performance benefit and others reading the source are sure about what the coder was thinking which is a great thing.

However this will never happen. Simply because the trend is to shift to dynamic languages where rules are more loose.

Unknown said...

Someone else gets the same idea