Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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".

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top