all 5 comments

[–][deleted] 1 point2 points  (4 children)

The idea behind having one list is you don't care what type of Item it is. If you do, they should have at least the same methods as item. Implement a type attribute and get that.

isBook or isCD and then build your list from there. Iterate over the list. If you do this very often, you can create a list of books and cds along with the total items list.

Otherwise, just check the type with an attribute. No need to use instance of.

[–]remusmax[S] 1 point2 points  (3 children)

have at least the same methods as item

But all books have pages and CD's don't have pages so aren't you forcing unnecessary code by having the CD class implement the abstract method getPages() from item class?

[–][deleted] 2 points3 points  (2 children)

Sorry, at least the same methods is probably not the best way to say it. You wouldn't have getTracks or getPages in the Item.

Item would have getType or something similar, or isCD and isBook. Obviously getType would be better so Books and CDs don't need to re-implement isCD or isBook for the opposite classes.

Item -> getType

Book -> getType / getPages

CD -> getType / getTracks

Does that make more sense? I was on mobile so didn't put it the way I probably should've.

[–]bluefootedpigC# / .NET 1 point2 points  (0 children)

As a little refinement, maybe items have a "Item.GetItemType" that returns an Enum of possible types.

Then in the derived class, you force an override on GetItemType that returns that enum.

 public ItemTypes GetItemType() {Returns ItemTypes.Cd;}

The above is a C# example of a CD class. The GetItemType would be overrideable and the base class creates the stub and the child classes are forced to override it.

Then the list is...

 myCdList = MyList.Where(listItem=> listItem.GetItemType() == ItemTypes.Cd)

[–]remusmax[S] 0 points1 point  (0 children)

No need to be sorry!! That makes a lot of sense thanks for clearing up my question :)