Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News Opinion: Final should be default, not deprecated

Opinion: Final should be default, not deprecated

Elliotte Rusty Harold has joined a growing discussion across some blogs and lists about the topic of deprecating the final keyword in Java, saying that final should be 'default' unless explicitly marked otherwise, at least for methods. According to Elliotte (from an earlier post), the lack of finality has created a huge, brittle, dangerously breakable infrastructure in the world of Java class libraries.

Elliotte starts off putting design by contract in context to inheritance, saying that the the subclasses must maintain the class invariants and postconditions of their superclasses.   Subclasses can relax a parent classes preconditions but not over ride them, as that would make it impossible to guarantee the behavior of the sub classes.  Therefore, "it follows that most methods should be fina ...Failing to mark them final risks postcondition, precondition, and class invariant violation."

So Final should not be deprecated, but used all the time, UNTIL Java the language could be modified, in order to:

make preconditions, postconditions, and class invariants language level constructs. Then make them automatically inherited by all subclasses. This would allow subclasses to override methods from the superclass, but would not allow them to change the superclass’s defined behavior. They could only change things the superclass did not explicitly promise.

They’re a lot of other benefits to this scheme as well. First of all it would mean more people would use design by contract, and thus write better code. For those of us who already use design by contract, it would make our code much simpler. But what interests me for the moment is that it would dramatically reduce the need for final. final is really overkill for 90% of the uses to which it’s put.

Elliotte concludes his entry criticizing the over-use of Interfaces:
They’re a lot of high-powered theorists who just love interfaces and abstract factories; and it’s not a coincidence that these are the same people who hate final. They’re wrong about this too, and for the same reason. Java interfaces have no ability to enforce preconditions, postconditions, and invariants. This means they’re appropriate only when a type really doesn’t have any of those, which is rare.

Rate this Article