Mark Wilden
5/25/2008 2:56:00 PM
On May 25, 2008, at 7:19 AM, Tobias Weber wrote:
> In article <F7E21685-9F99-48F0-A3AC-990A18B0294E@mwilden.com>,
> Mark Wilden <mark@mwilden.com> wrote:
>
>> [Note: parts of this message were removed to make it a legal post.]
>
> ?
Beats me!
>>> I could have 'if gender' in every accessor
>>
>> That seems like the simplest approach. The person object is the one
>> who's creating this restriction - weight shouldn't know about gender
>> and gender shouldn't know about weight. Wouldn't that only affect one
>> accessor - weight?
>
> In the example, yes. In reality it's 3 attributes and writing is
> forbidden as well. I implemented it using one class and an Integer for
> the genders and it got pretty messy as (storage) space needs to
> manufacture persons and therefore write female's weight where it
> normally wouldn't be allowed.
>
> I worked around that using set_instance_variable but felt awful.
>
> So I rewrote everything using the state pattern, but with a Struct
> containing the attributes being passed around between state instances.
> Even uglier code.
>
> I hate Java, but its protected package access would help with this.
To my mind, you've got a "smell" here that's caused by wanting to use
inheritance instead of composition (the State pattern mimics
inheritance, of course). You want a person to be-a gender, not have-a
gender. This is implemented via State by having-a gender-weight
gatekeeper. This is motivated by wanting to localize knowledge of the
relationship between gender and weight, which is a good goal. However,
it's causing you to need to use backdoors like set_instance_variable
or Java's protected package access. To me, that indicates that the
object model may be wrong.
Even though gender conditions access to weight, that doesn't mean that
gender has to know about weight (which it does in your
implementation). Is gender a behavior (or state), or is it an
attribute? I think it's the latter. If you have the person object
mediate access to one of its attributes based on another of its
attributes, you put the responsibility where it truly lies.
But this is me just thinking out loud. It's your model and you know it
better than I do. I think I would give the 'if gender' approach a shot
before resorting to State, especially if the latter forces you to
violate encapsulation. I'm not a big fan of State (or Mediator, for
that matter) when there are simpler, more direct, more obvious
approaches. But that's just my armchair perspective. Good luck! :)
///ark