Skip to main content

ReadOnly marker interface

6 replies [Last post]
mthornton
Offline
Joined: 2003-06-10

How about a marker interface "ReadOnly" which would be implemented by the objects returned from methods such as Collections.unmodifiableCollection, Collections.unmodifiableMap, etc.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
hlovatt
Offline
Joined: 2003-11-18

Here is a pattern enforcing compiler that implements the immutable pattern by implementing the interface Immutable.

https://pec.dev.java.net/

The list of patterns supported is here:

https://pec.dev.java.net/nonav/compile/index.html

and the immutable pattern is described here:

https://pec.dev.java.net/nonav/compile/javadoc/pec/compile/immutable/Imm...

The reason for using an interface as a marker is that it is useful to have immutable as a type so that instaceof Immutable and List< Immutable > work.

chandra
Offline
Joined: 2003-06-12

Note that the ReadOnly is not the type of a collection; it is an attribute. Why not decorate readonly objects with an attribute? I propose that ReadOnly should be an Attribute. IMHO, marker interface is an anti pattern in the light of annotations.

jwenting
Offline
Joined: 2003-12-02

but then again, annotations themselves are the worst antipattern of all.

chandra
Offline
Joined: 2003-06-12

I am not sure who is in minority here. Why do you think that annotations are anti pattern? How?

jwenting
Offline
Joined: 2003-12-02

and the use?

Either they're readonly or not already. If not a marker interface won't prevent you from ignoring the program from behaving as if it's readonly even if you yourself misbehave and change it anyway.

Or do you suggest everyone starts writing code like
[code]
if (x instanceof ReadOnly) return;
else
{
// change x
}
[/code]

every time they want to change anything?

mthornton
Offline
Joined: 2003-06-10

I found myself doing something like this

void setReadOnly() {
if (x instanceof HashMap)
x = Collections.unmodifiableMap(x);
}

I didn't want to warp the value more than once, nor am I happy with testing for the modifiable class. OK, I could just use an extra flag variable, but thought that there should be a better way.