java - Best practice to avoid side effects -
i have question how avoid side effects on java objects. let suppose have instance myobject of class myobject. process myobject through chain of methods/commands , @ each command level, want enrich myobject method/command has computed.
here class myobject instance of:
public class myobject { private int resultofcommand1; private int resultofcommand2; private int resultofcommand3; private int resultofcommand4; .... .... }
here methods/commands myobject has processed through:
private myobject command1(myobject myobject) { return myobject.setrresultofcommand1(1); } private myobject command2(myobject myobject) { return myobject.setrresultofcommand2(2); } private myobject command3(myobject myobject) { return myobject.setrresultofcommand3(3); } private myobject command4(myobject myobject) { return myobject.setrresultofcommand4(4); }
so design shown above have side-effects , avoid such thing.
could tell me best way avoid side effects? better make of copy of object passed parameter (in case myobject), changes on copy , return it? there best way guarantee multi-thread-safeness?
any appreciated. horace
if want avoid side effects, methods set value must not alter instance, instead return new instance (a copy). within method, use constructor set (final) values.
example:
class c { private final int x; private final int y; public c(int _x) { super(); this.x = _x; this.y = -1; } public c(int _x, int _y) { super(); this.x = _x; this.y = _y; } public c sety(int _y) { return new c(this.x, _y); } }
to prevent side effects, declare fields final
. if fields final
, values (in case of primitive types) , object references immutable. in case of object reference, object must immutable achieve "complete immutability".
so not change copy, construct copy new values.
now it's safe pass immutable instance around; cannot change, it's thread-safe.
Comments
Post a Comment