← Back to Upcase

Is Inheritance the way to go to refactor TextShouts & PhotoShouts Controllers?


(Pablo May) #1

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?


(Gabe Berke-Williams) #2

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: http://www.sandimetz.com/blog/2016/1/20/the-wrong-abstraction

And here’s a Weekly Iteration on why we prefer composition instead of inheritance: https://thoughtbot.com/upcase/videos/composition-over-inheritance