Tags

Const methods are evil?

April 9th, 2006

The C++ folks complain about a feature Java is lacking, the “constness”.

For the younger readers: The keyword const can be added to a method to make it promise not to modify the status of the object, as the same keyword for a variable means that you are only allowed to call const-methods on it.

Thus a const-type is a supertype of the type. Some types in Java are actually const: Number and String are immutable that is even stronger (they never change at all, while a const-object restricts only the reference holder to modify its state).

The Problem with Java is simple to explain: Imagine you had MutableString extends String. When implementing an interface do(String) just implementing do(MutableString) is not sufficient because there are MutableStrings that are not mutable - being plain Strings. When you design the interface of your class carefully, you can have constness: Create a const-interface and extend it by an interface defining all other methods. This is cumbersome and really hard to maintain. The implementation of a getter - see below - can call some non-const method; slicing the class creates problems down the road because of Java’s restriction to single inheritance.

My point here is that I argue that the concept of constness is of any good use in OOD at all.

Let aside the documentary benefit of a const method ( you should be concious about what a method does when you plan to use it), the const is used mainly for return-values of functions and one could view the need of const methods just a by-product of this modifier since otherwise the object at hand would be 100% useless (there are some subtleties with operator overloading, but this doesn’t apply to Java and the C++ syntax is questionable there anyway).

Read the rest of this entry »