views:

363

answers:

4

When I pass an immutable type object(String, Integer,.. ) as final to a method I can achieve the characters of a C++ constant pointer. But how can I enforce such behavior in objects which are mutable?

public void someMethod(someType someObject){
 /*
  * code that modifies the someObject's state
  * 
  */
}

All I want is to prevent someMethod from modifying the state of someObject without making any change in someType. Is this possible?

+2  A: 

No, you can not prevent the object being modified via its setXXX() (or similar) methods. You could hand in a clone or a copy of it, though.

Bombe
but cloning is one such expensive option that I dont want to do for really huge objects
sarav
Well, then wrapping is about the only option left to you.
Bombe
+1  A: 

No, it's not possible. You have to either pass in a copy of the object, or just rely on knowing what actions make state changes to the object and avoid calling them - the compiler won't help you.

Nathaniel Flath
+5  A: 

In the general case, no, it's not possible. In a very limited case, you can wrap someType in a class that provides the same interface (see Collections.unmodifiableList() for an example).

However, there's no equivalent to "pass a const pointer and the compiler will only allow you to call const functions on it".

kdgregory
yes. wrapping is a good option though its a work around
sarav
+1  A: 

No, I don't think this is possible. The normal approach is to create an adapter for SomeType where all the methods changing state throws UnsupportedOperationException. This is used by for instance java.util.Collections.unmodifiable*-functions.

There are several approaches to this:

  • you can let SomeType be an interface, and when you need it to be read only, just create a wrapper delegating all the read-methods to the original object and implementing all the write-methods to throw an exception.
  • or you can create a subclass of SomeType overriding all the write methods

This will of course only give you run-time checking, not compiletime. If you want compile-time, you can let SomeType be an interface (or a superclass) with no write-methods, only read.

Rolf Rander