Tutorial :Ruby Abstract Class Design



Question:

I'm creating a video game. It has Characters & Items. Since I want Characters & Items to each have a name, should I make another class called NamedObjects with just a name field and have Characters & Items extend that? Or is that going overboard?


Solution:1

For something as simple as a name attribute, it may not be worth it to write modular code, because the only line you may need is:

attr_accessor :name  

Of course, if you foresee that named things will share more functionality in the future, your concern is quite a valid one. Rather than using inheritance, it's better to use modules in Ruby:

module Nameable    attr_accessor :name      # To be expanded.  end    class Item    include Nameable  end    class Character    include Nameable  end  


Solution:2

If all that they share is a name, that's probably overkill.


Solution:3

Classes should in general share base class when they have the same behaviour, not same data. OOP should always be about behaviour. You should also think about/study the Liskov substitution principle when creating base classes.


Solution:4

In java I would create the NamedObject interface as you said. However Ruby is a dynamic ducked-typed language. There are not interfaces. So just define a name attribute and use it where you need it.


Solution:5

Will you ever need to loop over a bunch of NamedObjects and display the name? If so, you need the NamedObjects class. If you don't, you don't...

You can't make a catastrophic mistake on such a small issue anyway: If you don't make a base class for the name and you need it later you'll just restructure your classes later, no big deal. If you add the base class and don't actually need it, it's not a big problem, it may safely be ignored.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »