Benten
Benten

Reputation: 1039

How to organise model that consists of several lists

I have a model that consists of several lists that are used in a news feed. For example, there are different lists for sport stories and car stories. I am wondering how I should organise these.

class  NewsFeed{

    public List<SportStory> sportStories;
    public List<CarStory> carStories;
    public Map<int, String> storyType;
    public Map<int, int> storyPositions;

    public String getType(int position){
        storyType.get(position);
    }

    public String getPositionInList(int position){
        storyPositions.get(position);
    }

}

class SportStory{

    public String sportName;
    public String imageUrl;
    public String notablePlayer;
    public int favourites;

}

class CarStory{
    public int storyType;
    public String carName;
    public String carType;
    public String carColor;


}

The view then renders the stories in the model with the correct template by checking what type the story is using the getType function. It gets the story position using the getPositionInList.
For example say the view was rendering the fifth story. It would use the getType function and find out it was a car story. It would then use the getPositionInList to see that the fifth story in the news feed corresponded to the second item in the car story list.
Another problem I have is that if different types of stories are added then this class has to be changed.

If an event is triggered on the view a callback is in invoked on a controller.

   public void onSportStoryFavourited(int id){
        SportStory story = getSportStoryById(id);     
        story.favourites = story.favourites + 1;
        dao.updateSportStory(story);
        view.onStoryFavourited(id);       
   }

I don't really think this approach is sound at all.

Upvotes: 0

Views: 35

Answers (1)

under_the_sea_salad
under_the_sea_salad

Reputation: 1834

I would suggest making a new Story class. It could be an almost empty class, but it could contain something useful like dateWritten that would apply to all kinds of Storys. Then, you could simply have your CarStory or SportStory extend your parent class Story.

Then, your newsfeed wouldn't contain cumbersome List<SportStory> and List<CarStory>, but only List<Story>.

If you needed to check what type the story is, then you could use instanceof instead of keeping track of a map from int to the description. For example, you could do someStory instanceOf SportStory which would return true if someStory is of type SportStory.

Upvotes: 1

Related Questions