java - cloning or unmodifiableCollection -


during university classes on java learned concept of privacy leak, public getter returns reference private mutable object.

the example gave follows: (forgive me if syntax isn't quite right, i'm working memory)

private hashset<*> priv = new hashset<*>  public collection<*> getpriv () {     return this.priv; } 

now problem object's client has opportunity corrupt private hashset, intentionally or otherwise.

on course, suggested solution use following:

public collection<*> getpriv () {     return collections.unmodifiablecollection (this.priv); } 

this seems solution me, because not internal state of object protected external modification, attempt modify returned unmodifiablecollection trigger exception. problem though, works collections. there doesn't seem equivalents other mutable java classes.

most books on java i've read since suggest following:

public collection<*> getpriv () {     return this.priv.clone (); } 

this works on clonable object, returned object can modified client object's content. internal state of object still protected, don't exception if try modify data can't modified. means make mistake private collection, modify it, , left mystified why changes aren't reflected in object, i've swapped 1 class of errors (modifying private state) (modifying clone should immutable).

is there more generalized way of doing return collections.unmodifiablecollection (this.priv); work class (or @ least class meets prerequisite such implementing cloneable), or option implement mutable , immutable versions of private classes might want make publicly available through getter?

i'm afraid answer yes.

note collections.unmodifiablecollection returns view. essentially, collections contains adapter class takes in collection , forwards method calls it. 'dangerous' methods, throws exception instead. relies on underlying collection passed in implement things in sane manner of course. if getsize() mutates object, calling getsize() on adapter still forward underlying class, modified.

you can reduce amount of work limiting number of different classes (or interfaces) return clients. can make more of classes immutable default, common paradigm in functional languages makes things simpler. unfortunately, java makes working immutable objects unnecessarily ugly.

there possibilities generating immutable views automatically, that's complicated , requires have way of deciding methods forward anyway.

lastly, none of protects setaccessible or like. in case, they're deliberately violating standard vm constraints, it's not should worry about. if you're worried security, you'll need run untrusted code in securitymanager anyway.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -