Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

immutable vs mutable objects

I was reading as below but I have not clearly understood how we can set wothout setter methods and concept behind immutable vs mutable objects.Any ideas, suggestions, sample code, links, source code highly appreciated. Thanks in advance







There's no need to have setting methods on UserDetail.  It's designed to be "set" through the constructor:

UserDetail oldDetail = new UserDetail("my-name",'mypassword") ;

so to change it you do something like:
UserDetail newDetail = new UserDetail(oldDetail.getUsername(), "my-new-password") ;


 The UserDetail class and setter methods not being required.

 "immutable vs mutable objects" and that will give you more info on why the UserDetail class is the way it is.


Basically though, it you don't NEED setter methods, don't put them in.
In this case you are only ever setting the username/password once, so your use case is a good fit for an immutable object. Also, if your needs ever do change, it is easy to add the setter methods at that point.
Avatar of imladris
imladris
Flag of Canada image

You "set without setter methods" by only allowing data to be set during construction. So technically it is "set once".
If you do need to change it, you can do so by creating a new object instead.

This is the way that the String class works. It is a final, immutable, class. You can create a new string. But once created, it cannot change. You can, instead, create a different String and use that.
ASKER CERTIFIED SOLUTION
Avatar of imladris
imladris
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial