Before concretizing my question, let me provide some background: My main programming languages are C++ and Java. When working with C++ I find it important to apply const correctness, that is declaring functions like this:
A::DoSomething( const B& arg ); // guarantees that arg is not modified
A::DoSomething() const; // guarantees that the object of type A is not modified
A::DoSomething( const B& arg ) const; // both of the above
In fact, I often wish that const would be the default and objects that are modified have to be marked somehow.
My main reasons for using constare:
- Communication with other developers: It makes code more expressive.
- Communication with the compiler: It helps to find issues at compile time and sometimes makes additional optimizations possible.
It is well-known that Java has no const keyword (you can't do the above with final) and this fact has been discussed here before, see for example here: Equivalent of const(C++) in Java.
The Java alternative that is usually proposed is to make your classes immutable. While this is not a full replacement of const because it works per class and not per context in which a class is used, it would work fine for me in most cases.
But there is one big issue with immutable classes: Immutability is not obvious. To find out if a class really is immutable, as far as I know, you basically have to check the full source code. Any method could have a backdoor through which the object could be modified.
So is there an easier way to check immutability? Or is there any best practice to somehow mark a class as being immutable?
Note: I know that both languages provide 'evil tricks' to bypass constness or immutability: C++ has const_cast and Java has reflection. But for the context of my question, let's assume that these are not used.