Inheritance Question

  • Thread starter Thread starter Neils Christoffersen
  • Start date Start date
N

Neils Christoffersen

Hey Group,

I have an abstract base class and four child classes that inherit from it.
All child classes have a data member called _changeAmount. In two class
this member is an int and in the other two it is a float.

I'd like to somehow move _changeAmount to the base class, because all the
child operations that use it are the same. I know this would be simple to
do if each child used the same data type, but I'm not sure how to go about
it seeing that they are not the same.

How can I accomplish this?

Thanks in advance,
Neils Christoffersen
 
Neils,
How can I accomplish this?
You can use the Pull Up Field refactoring to move the common field from each
child class into the parent class.

http://www.refactoring.com/catalog/pullUpField.html

However before you do that, or while you do that you will need to ensure
that the field is the same type or compatible type (same base type) in each
class. Seeing as an int will fit in a float, I would make the field float
when I pulled it up.

I would consider having a virtual property that the two classes where the
value is an int can override the property to ensure the value stored is
stored as a whole number. This property would be of type float, like the
field. (this would be based on actual business rules).

Closely related to the Pull Up Field refactoring is the Pull Up Method
refactoring:

http://www.refactoring.com/catalog/pullUpMethod.html

To effectively use Refactoring, Martin Fowler's book "Refactoring -
Improving the Design of Existing Code" from Addison Wesley is a must, as he
goes into details on the how & why of each refactoring.

http://www.refactoring.com

Hope this helps
Jay
 
Doh!
This may not be as clear as I would have liked:
I would consider having a virtual property that the two classes where the
value is an int can override the property to ensure the value stored is
stored as a whole number. This property would be of type float, like the
field. (this would be based on actual business rules).
The check to ensure the value is a whole number would be based on actual
business rules.

The fact the virtual property is a float is because two of the classes
needed it to be a float. If you do not need to ensure its a whole number,
then making the property virtual is not needed.

An alternative to a virtual property would be a Template Method Pattern. The
concrete property in the base class would call a protected virtual method
(the Template Method). This protected virtual method would ensure the value
is 'within range', the classes where the value needs to be an int, would
override the template method to do what needed to be done.

Hope this helps
Jay
 
Back
Top