gudii9
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",'mypa ssword") ;
so to change it you do something like:
UserDetail newDetail = new UserDetail(oldDetail.getUs ername(), "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.
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",'mypa
so to change it you do something like:
UserDetail newDetail = new UserDetail(oldDetail.getUs
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.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.