Hello, I’m on part 3 of Intermediate Ruby on Rails. And wanted to know if Inheritance is the way to go to refactor TextShouts & PhotoShouts Controllers. Is it ok, to extract repeated code into a parent class?
Hi Pablo!
Thanks for your question. We try to avoid inheritance in our apps, instead opting for small pure-Ruby objects that we can re-use.
If you find that there’s duplicated logic in the create
methods for example, we recommend extracting an object like a ShoutCreator
to handle that. We’ve found that having create
and show
methods in the expected places for controllers is helpful when other people read your code. In other words, we extract things inside the create
or show
methods, but we don’t factor out the create
/show
methods themselves to a parent class.
Here’s an excellent blog post on why duplicated code can actually be good: The Wrong Abstraction — Sandi Metz
And here’s a Weekly Iteration on why we prefer composition instead of inheritance: Composition Over Inheritance | Online Video Tutorial by thoughtbot