Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance or enum

I must structure new model for application and I don't what is better:

using inheritance or using enum as type of object:

For example :

Books

class Book
{
public string Name {get;set;}

public string Author {get;set;}

public int NumberOfPages {get;set;}

}

public class Encyclopedie:Book
{

}

public class Novel:Book
{

}

or better use:

class Book
{

public BookType Type {get;set;}

public string Name {get;set;}

public string Author {get;set;}

public int NumberOfPages {get;set;}

}

public enum BookType
{
Encyclopedie = 0,
Novel = 1,
...
}
like image 886
user278618 Avatar asked Jun 24 '10 07:06

user278618


3 Answers

Use inheritance if the different types have significant differences (how you process them and treat them). That is, if you are going to use polymorphism at all, you should use inheritance.

If you only need a way to distinguish different types of books, go with the Enum.

like image 84
Oded Avatar answered Oct 13 '22 01:10

Oded


In true object oriented systems, the type of the object is transparent to the client. So the code which handles books should not know what the type of the book is, but only invoke methods on books.

So if you need to implement different behaviour within the book in response to the method invocation, extend Book and override some of its methods. If you don't, then don't.

It appears, given the empty bodies of your subclasses, that they behave in every way the same as books. So you are merely tagging the book with some additional data - the difference between Encyclopaedia and Novel is no more essential to the book than hardback or softback or large print or standard print - a client may use these differently, and each book either is a large print book or it is a standard print book, but these are all attributes of the book rather than essential differences.

I wouldn't necessary use an enum for the book kind, since you may want to add more data - I'd either use a loose tagging system, so you can tag a book with a collection of kinds - so you would have a book tagged as { 'children's', 'ornithological', 'encyclopaedia', } - or allow structure in the roles - so there is a role for 'children's ornithological encyclopaedia' created when it is required, but no fixed enumeration.

like image 34
Pete Kirkham Avatar answered Oct 13 '22 00:10

Pete Kirkham


I would say that the 2nd would be better as you are not really extending the book class in your Encyclopaedia, there are no additional properties or functionality you need to give one book type over another.

like image 36
Phill Duffy Avatar answered Oct 12 '22 23:10

Phill Duffy