9 | | Values do not (should not) have such identity. Two values are identical, if they ''behave'' equally. It makes no sense to use values locks in synchronization primitives. |
| 11 | == Objects without identity == |
| 12 | |
| 13 | Values do not (should not) have such identity. Two values are identical, if they ''behave'' equally. E.g., it makes no sense to use values as locks in synchronization primitives. |
| 14 | |
| 15 | == Value example == |
| 16 | |
| 17 | A class for representing matrices with operations "add", "invert", "scalarMultiply" and "matrixMultiply" should serve as example for a typical value class. Two matrix objects should considered identical, if they represent the same mathematical object. |
| 18 | |
| 19 | There are two opposed approaches for implementing value classes. One is the mutable value class and the other is the immutable value class. |
| 20 | |
| 21 | === Mutable value class === |
| 22 | |
| 23 | Let us first consider the mutable value class approach. Typical signatures of the methods would look like in the following figure: |
| 24 | |
| 25 | {{{ |
| 26 | class Matrix { |
| 27 | void add(Matrix that, Matrix result); |
| 28 | void invert(Matrix result); |
| 29 | void scalarMultiply(double factor, Matrix result); |
| 30 | void matrixMultiply(Matrix that, Matrix result); |
| 31 | } |
| 32 | }}} |
| 33 | |
| 34 | When programming in the mutable value class style, the caller of an operation can provide storage for result value. This is considered commonly most efficient, because the client can decide, whether storage allocation is required. This reduces unnecessary temporary storage allocation. |
| 35 | |
| 36 | |
| 37 | === Immutable value class === |
| 38 | |
| 39 | In the immutable value class style, each operation returns a fresh allocated matrix object. This is necessary, because a matrix once created cannot be modified any longer. A matrix class with the same operations but formulated in the immutable value style would look like in the following figure: |
| 40 | |
| 41 | {{{ |
| 42 | class Matrix { |
| 43 | Matrix add(Matrix that); |
| 44 | Matrix invert(); |
| 45 | Matrix scalarMultiply(double factor); |
| 46 | Matrix matrixMultiply(Matrix that); |
| 47 | } |
| 48 | }}} |
| 49 | |