Alex Rivera | Logout

Unit testing for object immutability

Asked 2011-07-19T07:50:02.343
12

I want to make sure that a given group of objects is immutable.

I was thinking about something along the lines of:

  1. check if every field is private final
  2. check if class is final
  3. check for mutable members

So I guess my question is: is 3. possible ?

I can check recursively whether every member of a class has its fields private final, but this is not enough since a class can have e method named getHaha(param) which adds the given param to an array for instance.

So is there a good way to check if an object is immutable or is it even possible ?

Thanks,

Edit
Report

1 Answer

1

Pretty sure it is impossible. Consider this function:

public void doSomething() {
    if (System.currentTimeMillis() % 100000 == 0) {
        this.innerMember.changeState();
    }
}

First, you won't be able to detect it by running every class function, as this function changes the state of object precisely only once in 100 seconds.

Second, you won't be able to detect it by parsing code, as you do not know if changeState() function changes the state of innerMember or not.

answered 2011-07-19T07:56:57.813

Your Answer