Wednesday, April 16, 2008

Be it in C++, Java, or Scala, I have always been bothered by the fact that an instance of a class has access to the private members of another instance.

Sure, it's mighty useful for copy constructors and other functionalities like adding, but I always felt there should also be a "private read-only" access modifier.

Of course, there is no problem in the case of immutable objects. Here's a Scala example (using Scala version 2.6.1).

class Domino(p: int) { private val points=p

def add(that: Domino) = new Domino(p + that.points)

override def toString() = "Domino: points=[" + points +"]"}

scala> val d1 = new Domino(1)d1: Domino = Domino: points=[1]

scala> val d3 = new Domino(3)d3: Domino = Domino: points=[3]

scala> d1.add(d3)res2: Domino = Domino: points=[4]

But what if, for whatever reason, I am using mutable objects?

In the following code, I have no quarrel with the function addToMe, but I am bothered by the function addToOther. I wish I could specify my special "private read-only" access modifier there, so this function would not compile.

I don't see this as an important feature really. I use private so other people (or I as a user of another class) can not mess with my internal state, because my current mindset should not revolve around the internals of that class.

But while I am working on that particular class I have to understand things anyway, so I don't see how this helps.