Javari's Reference Immutability

Reiner Pope reiner.pope at gmail.com
Wed Jul 26 00:05:42 PDT 2006


Hasan Aljudy wrote:
> I think the question is: what's the point?
> Clearly, Java's lack of const didn't prevent it from the having some of 
> the best libraries there are.
> 

However, it is one of the reasons that Java is so slow. Instead of a 
proper implementation of reference immutability, anything that needs to 
be kept constant is either written as a readonly interface, or is simply 
duplicated. This means either code duplication or data duplication; the 
former leads to more bugs as everyone knows, and the latter leads to 
worse speeds. Although lack of speed due to duplication could be seen by 
some as acceptable, because (a) Java isn't meant for speed and (b) the 
error-catching achieved by duplication is more important than the speed 
of not, these arguments are clearly weak, and (more importantly) 
completely inapplicable for D. Effectively, Java *does* have a const 
mechanism, just a slow and painful one, because it must be enforced by 
the coder, not the compiler, and it is slow because it requires duplication.

Just because Java manages to have good libraries it doesn't mean 
ignoring const is the best solution. Remember also that there is a huge 
company behind Java, so they can afford the extra time required in 
testing and documenting their libraries by hand for const violations. 
However, in D, this is not the case, and even if there were such a 
company, it would be worse for the individuals, who would have trouble 
competing with the error-checking resources of the company.

The benefits of const are:
  - Machine checking of code, leading to higher-level code (eg 'in', 
'out' and 'inout' are much more informative than 'this parameter is a 
class so it can be modified', 'this parameter is a struct so it won't be 
modified', etc.)
  - Saving either developer time or running time. Since most people 
can't be bothered to spend the time checking for const-violations by 
hand, they will tend to create const-safety through duplicates. If they 
are truly masochistic, then they can ensure by hand that it is safe, but 
this is unreliable, and requires extra work.
  - If the const mechanism is trustworthy, other optimizations could be 
explored, such as those possible in functional languages due to the lack 
of side effects (ie, everything being const): in a functional language,

   a = sin(1);
   b = sin(1);

would only evaluate sin(1) once, and cache the answer. In D, however, it 
would be calculated twice, slowing it down. For any argument that this 
could be optimized away by a Sufficiently Smart Compiler, you can make 
arbitrarily hard optimizations that const would fix but the compiler 
would not.

Cheers,

Reiner



More information about the Digitalmars-d-learn mailing list