ma11hew28
ma11hew28

Reputation: 126457

Ruby Abstract Class Design

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?

Upvotes: 2

Views: 1541

Answers (5)

molf
molf

Reputation: 74985

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

Upvotes: 3

paradigmatic
paradigmatic

Reputation: 40461

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.

Upvotes: 1

Cosmin Prund
Cosmin Prund

Reputation: 25678

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.

Upvotes: 0

Torbjørn
Torbjørn

Reputation: 6503

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.

Upvotes: 2

Carl Manaster
Carl Manaster

Reputation: 40356

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

Upvotes: 2

Related Questions