views:

321

answers:

5

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?

+2  A: 

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

Carl Manaster
+1  A: 

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.

Torbjørn
How the concept of attribute accessors (that will be probably be used for implementing `name` in this case) fits into that behaviour/data rule? BTW, can you clarify the relation of the Liskov principle with the question here, I don't see any?
Mladen Jablanović
A: 

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.

Cosmin Prund
+1  A: 

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.

paradigmatic
+2  A: 

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
molf
Amen to that. Using mixins would also prevent quite common case when you have classes `A`, `B`, and `C`: let's say `A` and `B` share common functionality `F'`, and `A` and `C` functionality `F''`. With class inheritance you're pretty much stuck there.
Mladen Jablanović
@Mladen Jablanović: The inheritance Eiffel would handle that situation quite nicely, although I agree that mixins are often a better solution anyhow.
Arkku
+1. You could maybe expand this answer with a couple methods in the module. (I can't think of any myself ATM…)
John