-1

I was reading about immutable classes, and the ways to make a class immutable were said to be:

  • 1 - Make the class final to prevent inheritance
  • 2 - Make the mutable variables final
  • 3 - Don't provide setter methods.

I think the third condition is unnecessary. When we make a variable final and provide any value to it, after that new value can't be assigned to it even through a setter method (because final variables can't be changed once a value is assigned to it). So why do we need the third condition of not having setter methods?

Am I understanding something in a wrong way?

1
  • Comments are not for extended discussion; this conversation has been moved to chat. Jun 11, 2019 at 12:06

5 Answers 5

1
public class Person{
  private String name;
  public Person(String name){
    this.name = name;
  }
  public String getName(){
    return this.name;
  }
  public void setName(String name) {
    this.name = name;
  }
}

Now, it is clear that Person is not an Immutable class. This doesn't mean, an instance of Person can't be a member of another class that is (supposedly) immutable.

public final class MyImmutableClass {
  // p is final, so it can't be re-referenced
  private final Person p;

  public MyImmutableClass(Person p) {
    this.p = p;
  }
  // it can be altered, though
  public void setPersonName(String name) {
    this.p.setName(name);
  }
  public String toString() {
    return "Person: " + p.getName();
  }
}

Now, we have an immutable class, but, it does contain a setter. This setter actively changes a member of the (final) field p.

public static void main(String[] args) {
  MyImmutableClass c = new MyImmutableClass(new Person("OriginalName"));
  System.out.println(c);
  c.setPersonName("AlteredName");
  System.out.println(c);
}

And .. there you have it. The member is changed, through the setter (even though the variable was final). Do understand, a 'final variable' is NOT necessarily a constant, in most cases it's state can be changed. The point of a final variable, is that it can not be re-referenced. Note, we could also have a method like this:

public void setPerson(Person p) {
  this.p.setName(p.getName());
}

A final variable itself is only a constant in case the type itself is an immutable type, or if it's a primitive, but you should understand that most types out there are mutable. Is the type immutable or a primitive and it's declared final? Sure, add a setter. But, to what end? Misleading people who use your class?

5
  • You are confusing the immutable value of a final reference with the mutability of the object the reference refers to.
    – user207421
    Jun 11, 2019 at 10:39
  • @user207421 No, I don't. If a member of a class can be altered, the object containing said member is mutated.
    – Stultuske
    Jun 11, 2019 at 10:40
  • No it isn't. It is still referring to the same object. Its own state consists of the values of its own non-static primitive and reference variables.
    – user207421
    Jun 11, 2019 at 10:43
  • @user207421 This just explains why something being final in java does not imply that is also "immutable", Compare this to C++, where you have constness for references (this is roughly what final is in java), as well as constness for objects (where there is no counterpart in java). Jun 11, 2019 at 10:53
  • This is why one should make defensive copies when adding other objects to immutable classes. And when getting those objects, it should also return a copy and not the one maintained in the immutable class.
    – WJS
    Jun 11, 2019 at 12:42
1

You are sort of right. A setter, by definition, replaces a field with the given value. If all of the fields are final then you couldn't possibly provide a setter anyway.

My description of how to write an immutable class would be:

  • Make all fields final
  • Make sure the type of every field is itself immutable

It's possible to write an immutable class with fields that are mutable if you take great care to ensure that they never change but you need to be very careful in this case.

5
  • I still say that normal practices make it easy to define an object that, under normal usage, provides no way to modify its contents. This requires no 'final' qualifications. Any such object is "immutable" in my book, regardless of what you might do with questionable code that goes against convention and common sense. - and I'm still not seeing in my head how a class can modify an instance variable. If you're talking about a class variable, then my logic still holds. Don't provide a way to modify the class variable and that variable would not need to be marked 'final' in the class def
    – CryptoFool
    Jun 11, 2019 at 10:38
  • @Steve It's easy to define an object that provides no way to manipulate the data directly but it's more difficult to ensure that it cannot be manipulated indirectly. Even introducing one mutable argument to the constructor effectively requires you to deep copy the entire thing.
    – Michael
    Jun 11, 2019 at 10:43
  • I don't disagree. So 'final' is a tool that CAN be used, depending on your implementation. Not providing mutable arguments to the constructor that you don't then copy is another. - and can you mark an immutable variable passed in to a constructor as 'final' such that it can't be modified? I don't think so. The 'final' will just say that the object reference can't be updated. It says nothing about what can be done within a mutable object, even if its reference is marked 'final'.
    – CryptoFool
    Jun 11, 2019 at 10:44
  • 1
    @Steve final is never necessary. It's just a nice constraint which makes code easier to reason about. If a class has a couple of fields, all defined as final, all clearly value types, (Integer, String...) then I can quickly determine that it's immutable without even reading the doc. If even one is not final, I need to check the entire class to make sure it's not changed. So while it is not a requirement for a class to be immutable, any good immutable class implementation should use it (IMO).
    – Michael
    Jun 11, 2019 at 10:50
  • I totally agree. In fact, I just realized that I misread the OP. It says "ways to" rather than "way to", as in "these are tools", not "THIS IS THE WAY". I was responding to the latter, which is not what was going on to begin with.
    – CryptoFool
    Jun 12, 2019 at 1:38
0

Yes, it could be reduced to

  1. Make the class final to prevent inheritance;
  2. Make the mutable variables final, and so don't bother providing any setters;

However for education purposes the shorter bullet points probably work better - even if slightly redundant.

0

The variable mentioned in item 2 can be a reference, which can be mutable (like a list or set) even when the variable itself is final.

This is why we have utilities like Collections.unmodifiableList to make mutable classes virtually immutable.

So the prohibition on setters is to prevent accidentally changing a final variable's state.

0

Making fields final is not sufficient (or even required) to guarantee immutability. You need to make defensive copies of mutable objects within the immutable class.

class Foo {
   private String str;
   public Foo(String str) {
      this.str = str;
   }

   public String getString() {
       return str;
   }
}

The above class is immutable because:

  • String is immutable.
  • The field 'str' is private and can't be altered.

Now considering the following MyDate class.


public class MyDate {
    private Date; // date is not immutable
    public  MyDate(Date date) {
        this.date = date;
    }

    public Date getDate() {
        return date;
    }
}

The MyDate class above is not immutable because the user can do the following:

Date d = new Date(<someDate>);
MyDate md = new MyDate(d);
d.set(<someDate>);  // oops, just changed value in MyDate via external reference.

The same could also be done via getDate().

To make MyClass immutable, make defensive copies of Date in the constructor and getter. These prevent the user of the class from changing the date field either:

  • Using a reference to the constructor argument.
  • Upon retrieving the date field via a getter
public class MyDate {
    private Date; // date is not immutable
    public  MyDate(Date date) {
        this.date = new Date(date);
    }

    public Date getDate() {
        return new Date(date);
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.