Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it common to replace hard-coded classes with something more dynamic?

Tags:

refactoring

I was reading in "Refactoring" of Fowler, chapter 1.

On page 51 you see a movie with a price class attached. The first approach was: use inheritance to create multiple movies each with their unique getCharge method to calculate the price. On page 38 this approach is abandoned, because it would be too static - changing the classification of a movie would be too hard. However, on page 51 inheritance is used again, this time for the price. Three subclasses of price are added: ChildrensPrice, NewReleasesPrice and RegularPrice. In this design it is easier to change the classification of a movie by changing its price object. But adding new price category here involves adding a new class.

Wouldn't it just be easier to have a class Price based on an interface or abstract class with a name field, so name can be "ChildrensPrice" and you can define whatever other price categories you want, without writing new classes?

Is this a refactoring pattern with a name, for example: "change hard coded classes into a more dynamical representation"?

What would be the pros and cons of such an approach?

like image 865
Michiel Borkent Avatar asked Dec 14 '25 14:12

Michiel Borkent


1 Answers

The approach with price category tags is more “dynamic”, allowing you to easily add new price categories, even at runtime. On the other hand, the “static” approach of having one class per price category lets you express more constraints in the commonly used type systems.

As an example, if there’s an interface that only works with kid’s prices, with the static approach you can express the constraint right in the code. With the dynamic approach the compiler can’t tell the difference between two price categories. (And it’s generally a good idea to express as many constraints in the type system as possible.)

That’s about all I could say about the general case. Which approach is better ultimately depends on the particular requirements.

like image 51
zoul Avatar answered Dec 18 '25 13:12

zoul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!