On 16 February 2011 13:03, Fabrizio Giudici
<[email protected]>wrote:
> On 02/16/2011 01:33 PM, Ricky Clarkson wrote:
>
>> Immutable objects can have behaviour, it's just that they'll tend to
>> return new versions of themselves with a change rather than mutate
>> themselves.
>>
> Yes, indeed I was thinking of:
>
> public class A
> {
> private final B b; // injected in some way
> private final Object prop2 = ... computed in some way
>
> public Object getProp1()
> {
> // return something involving b;
> }
>
> public Object getProp2()
> {
> return prop2;
> }
> }
>
> This is immutable, but it behaviour depends on b too for one of the
> properties. The other is just a read-only-javabean property. For testing it,
> you need to mock b. I wouldn't like seeing prop1 exposed by getter and prop2
> by final field. OF course you might argue that it's immutable if b is
> immutable too, thus we could just pre-compute prop1 and assign to a final
> public field. But this would change semantics (anticipating a computation).
>
>
Turtles all the way down! 'tis a good philosophy :)
Constructor injection is the way to go:
public class A {
public A(final B b) { this.b = b }
public final B b;
public final Object prop = new Object;
}
and already, the implementation has cost you far fewer lines, I certainly
know which one I'd rather maintain!
The real beauty of having everything immutable here is that you can then
start sharing structures:
public class A {
public A(B b, object prop) { this.b = b; this.prop = prop; }
public final B b;
public final Object prop;
public withNewProp(Object newprop) {
return new A(this.b, newprop);
}
}
There's no concerns sharing b like this if it's immutable, so you don't have
to worry about making a defensive deep copy to avoid any risk that the
instance of B might be mutated via the original instance of A.
--
Kevin Wright
gtalk / msn : [email protected]
<[email protected]>mail: [email protected]
vibe / skype: kev.lee.wright
quora: http://www.quora.com/Kevin-Wright
twitter: @thecoda
"My point today is that, if we wish to count lines of code, we should not
regard them as "lines produced" but as "lines spent": the current
conventional wisdom is so foolish as to book that count on the wrong side of
the ledger" ~ Dijkstra
--
You received this message because you are subscribed to the Google Groups "The
Java Posse" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/javaposse?hl=en.