Empirical data on the effects of immutability?

后端 未结 9 539
长情又很酷
长情又很酷 2021-01-01 19:03

In class today, my professor was discussing how to structure a class. The course primarily uses Java and I have more Java experience than the teacher (he comes from a C++ b

9条回答
  •  时光取名叫无心
    2021-01-01 19:32

    Immutability is a good thing for value objects. But how about other things? Imagine an object that creates a statistic:

    Stats s = new Stats ();
    
    ... some loop ...
         s.count ();
    
    s.end ();
    s.print ();
    

    which should print "Processed 536.21 rows/s". How do you plan to implement count() with an immutable? Even if you use an immutable value object for the counter itself, s can't be immutable since it would have to replace the counter object inside of itself. The only way out would be:

         s = s.count ();
    

    which means to copy the state of s for every round in the loop. While this can be done, it surely isn't as efficient as incrementing the internal counter.

    Moreover, most people would fail to use this API right because they would expect count() to modify the state of the object instead of returning a new one. So in this case, it would create more bugs.

提交回复
热议问题