java - Condition for creating a immutable class? -
to make immutable class , effective java has 1 last condition.
to make class immutable, follow these 5 rules:
5- ensure exclusive access mutable components. if class has fields refer mutable objects, ensure clients of class cannot obtain references these objects. never initialize such field client-provided object reference nor return object reference accessor. make defensive copies (item 24) in contructors, accessors, ,
readobject
methods
public final class immutableclass { private mutableobject mutableobject; // if should not provide getter object. use of variable after have //initalised in constructor }
can explain me point?
it's reasonably simple.
basically, it's saying not...
1- make available reference mutable object object might contain.
so if class
contained java.util.list
1 of it's fields, there should no way client using class
gain reference directly list
field, either via public
deceleration or getter of kind.
for example...
public class badimmutableexample { public list<string> mystrings; // can not referenced client /*...*/ }
would bad, because field mystrings
accessible body make modifications to...
in case had return values in list
either required return copy of list
(not reference it) or return array of values, example.
for example...
public class badimmutableexample { private list<string> mystrings; // can not referenced client /*...*/ public list<string> getmystrings() { return mystrings; } }
would expose list
mystrings
clients, allow them modify it.
in case, use collections.unmodifiablelist(mystrings)
make list unmodifiable, or return new arraylist<string>(mystrings)
or return array of string
instead...
2- never initialise such field client provided object...
basically means if class
requires client seed kind of value or values, should never maintain reference directly them, instead, again, make copy own reference...
for example...
public class badimmutableexample { private list<string> mystrings; // can not referenced client public immutableexample(list<string> clientstrings) { mystrings = clientstrings; } }
would break rule, changes clientstrings
reflected within class.
instead, like...
public class betterimmutableexample { private list<string> mystrings; // can not referenced client public immutableexample(list<string> clientstrings) { mystrings = new arraylist<string>(clientstrings); } }
instead, make copy of client supplied list, no longer reflect changes made (the client supplied list)
Comments
Post a Comment