Reputation: 2922
I'm in a bit of a pickle with designing an OO application using Pharo.
I have a class Household
, this class has an attribute named tvConnection
. This object is an instance of either Digital
or Analog
. Both these classes inherit from the super named TVSubscription
.
If I want to add a television to my analog cable subscription I can simply call addTV: aTelevision
on my tvConnection
property, which will then properly call the addTV:
method I have implemented in my Analog
class.
A digital connection can not have televisions connected. These have to be SetTopBox
devices, which in turn can have a television connected to them.
Now, I have to throw an error/show some output in case a user tries to add a television to a household which has a digital connection.
I figure I can do two things:
1)
I can implement the addTV: method in the Digital
class, which will simply perform the action wanted (eg. show a message "YOU CAN NOT DO THIS!"). But this seems wrong in so many ways..
2)
I can just not implement the method and catch the MessageNotUnderstood
error that gets thrown.
This would happen when I do the following:
**Adding a TV**
--> call `addTelevision` in `Household`
----> this `addTV:` on the `tvConnection` property
----> catch error if any, which implies that a TV was being added to a digital connection
Both of these solutions look REALLY dirty to me.
Upvotes: 2
Views: 107
Reputation: 5125
Maybe you should rethink your design. In my opinion the tvConnection
should be a connection object, let's say TVConnection
. TVConnection
could have two subclasses DirectConnection
and SetTopBoxConnection
. Digital
and Analog
would know their connection type and the connection type knows how to addTV:
or more conveniently, Digital
and Analog
implement addTV:
and simply delegate to their TVConnection
object.
Upvotes: 2
Reputation: 13386
If I were you I'd probably implement addTV:
in digital which would either add TV to a box or say that box is missing.
This looks quite nice. Think about it like:
TVSubscription>>addTV: aTV
self subclassResponsibility
TVSubscription>>tvs
self subclassResponsibility
Analog
has tvs
var.
Analog>>addTV: aTV
tvs add: aTV
Analog>>tvs
^ tvs
Digital
has box
var.
Digital>>box: aBox
box := aBox
Digital>>box
^ box
Digital>>addTV: aTV
box
ifNil: [ Exception signal: 'Connect box' ]
ifNotNil: [ box addTV: aTV ]
Digital>>tvs
^ box tvs
This is just a first best thought. Now I'll go to sleep and maybe I'll dream about some better solution
Upvotes: 2