immutable vs mutable objects
Posted on 2012-09-17
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.