-2

This is a theoretical question, I haven't figured a straight well explained answer yet, about object oriented design. Let's say we have a class of a Music Event, and we would like to implement a Rating class with maybe one int member(stars 1-5) and maybe one getter and one setter function. Maybe I haven't thought some bigger picture yet?

If we want our Music Event class to have ratings (just one not an array), why is it better -if it is- to inherit from the Rating class, and not to add a Rating class member inside the Music event class?

in coding:

//why is this better...
class MusicEvent:public Rating {
  string name;
  string duration;
  //and other stuff here
}


//...than this 
class MusicEvent {
  string name;
  string duration;
  Rating rating;
 //and other stuff here
}
stefaanv
  • 14,072
  • 2
  • 31
  • 53
user2211216
  • 375
  • 2
  • 8

3 Answers3

3

It's not better. You answered the question yourself - it has a rating, it isn't a rating. Ergo, composition is better (i.e. a member).

Inheritance signifies an is-a relationship. Composition signifies a has-a relationship.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 1
    I would alter the term composition to aggregation because composition inferes some sort of existence criteria. A Music event can exist without a rating. – fyr Feb 11 '14 at 07:49
  • @fyr "composition" is the usual term here, and indeed in this model the music event _can't_ exist without a rating (although it may of course be `null`) – Alnitak Feb 11 '14 at 07:50
  • @Alnitak it is not. "Composition" refers to "part of" ... "Aggregation" refers to "has a" .. and its clearly defined by UML. Sorry for being so picky. – fyr Feb 11 '14 at 07:54
0

The rating should be a member - it is an attribute of the event (i.e. something that belongs to it).

Deriving from Rating would only ever make sense if you wanted to treat many sorts (or "classes") of rateable events as a common set without caring what sort of event they were.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

Clearly a MusicEvent is not a Rating, a MusicEvent has a Rating, so that gives you your answer.

However, what you might want to do later is to have an interface called Rateable, or something like that, with setRating() and getRating() abstract methods. This might be useful if you at some point in future have lots of different classes, some of which carry a rating and some don't.

Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82