4 ms·
Because numbers are, by their nature, immutable. I think an object should reflect the externally visible properties of the thing being modeled. To me, that is t
by geophile 10y ago
Because numbers are, by their nature, immutable. I think an object should reflect the externally visible properties of the thing being modeled. To me, that is the whole point of OO. If I have two variables pointing to the same mutable Number, then some very non-intuitive things can happen when the value of the Number is changed through one variable.
> That thing has internal state, so why am I forced to continuously assign the results of each operation to a completely new object vs simply having those operations update state?
The abstract idea of an integer is immutable. Changing 3 to 4 is nonsensical. (It is not analogous to modeling a bus by a Bus object with operations reflecting the coming and going of passengers.) That's why the Java object named Integer should be immutable, and similarly for all the other Number classes, including BigDecimal.
Now if there were an IntegerBuffer class, then sure, there should be methods to change state.
Your argument is that there is internal state, state can be mutable, therefore every object should be mutable. My argument is that the nature of some objects is immutable, and designing a class to reflect that nature is preferable, and not at all at odds with OO.
- unclebucknasty 10y agoWell, we basically agree. I grant that there's a better case for numbers being immutable than buses. However, I would say that number "objects" are not meant to model real world numbers as objects per se. Because, sure, you don't morph a 3 into a 4 in the real world, but in code you don't generally require numbers as objects for the purpose of representing such constants. Rather, they are variables with some meaning. In other words, you don't generally need: BigDecimal three = new BigDecimal(3); but BigDecimal sum = new BigDecimal(0); Followed by some operation(s). Sure, depending on naming, you can create confusion with mutable numbers, but that's true for immutable objects as well. At the end of the day, I am not saying that immutables have no use and one immutable class outright destroys your OO design. I am saying that there is a tension that exists between the two that can easily be seen if you envision a design with 100% immutable classes in the context of OO's raison d'etre. Bringing it back to the OP, my bigger point was that all of the work involved and "side effects" of layering on immutability are an example of how people assess OO's success through the lens of things that were later added, but were not an intrinsic part of the OO paradigm in the first place.