This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I'm concerned I may be going about something incorrectly. I have an interface, and an implementation, but I need to extend the implementation and add on some more member variables to the subclass. Seems easy enough, but these extensions are bundled up into Collection objects, and that is where my headache begins.
What is the best way to create a list of my subclass objects, from a list that is returning a superclass of said objects?
Here is code that illustrates the issue:
Implementation of the interface:
This class extends the "Details" object, and simply adds one or two new member variables
Now for the part that is causing me some confusion. I have a service method, that returns an ArrayList of IType objects:
In another class (like a form class for a web app), I need to convert the IType list into a list of the *extended* class (MoreDetails).
So, long story short, I have a service that returns a list of IType objects, but I need to put them into a list of MoreDetail objects. What is the best or most appropriate way to do this?
The only way I came up with, was to loop through the collection one by one, cast each IType element to a MoreDetail, and generate a new collection that way. Seems like it's not the most elegant solution....
In the program, I call the service method, and need to populate my list:
Is the for loop that I used to extract the IType, then cast it to MoreDetails the correct approach?
If you need to get the MoreDetails type back from the getDetails() method, then the correct thing to do is to make the getDetails() method return a List<MoreDetails> instead of List<IType>. Part of the questions you have to ask is - why do you need the MoreDetails Object itself? Why can't you use the IType interface? If it is because you need access to more methods then you have to ask if those methods should be moved to the interface, or if a new interface should be created which has the additional methods.
There are a number of things you can do instead, though, depending on the situation. For example, you could take the 'responsibility' for knowing about what methods are needed out of the hands of the caller, and move them into the IType implementation. Not knowing anything about your situation, you might do this...
A different approach relies on Generics - if you know you want a List of some type which implements IType, and you can tell the getDetails() method the particular implementor you want, you could do something like this: