views:

54

answers:

1

I have been making a program that downloads information about movies from the internet. I have a base class Title, which represents all titles. Movie, Serie and Episode are inherited from that class.

To save them to the database I have 2 services, MovieService and SerieService. They in turn call repositories, but that is not important here.

I have a method Save(Title title) which I am not very happy with. I check for what type the title is and then call the correct service. I would like to perhaps write like this:

ITitleService service = title.GetService();
title.GetSavedBy(service);

So I have an abstract method on Title that returns an ITitleSaver, which will return the correct service for the instance. To do this the services would have to implement ITitleSaver

My question is how should I implement ITitleSaver? If I make it accept Title I will have to cast it to the correct type before calling the correct overload. Which will lead to having to deal with casting once again.

What is the best approach to dealing with this? I would like to have the saving logic in the corresponding class.

A: 

I don't understand the purpose of GetService. You only call that method to pass its result to GetSavedBy method? Here is my proposal:

  1. Expose an abstract Saver property on the Title class
  2. Define a concrete method Save on the Title class whose implementation is:

    this.GetSavedBy(Saver);

  3. In each Concrete class either create the required saver or use some dependency injection tool to inject the correct Saver at runtime.

Voila! this solves your problem neatly.

Ikaso
The purpose of GetService is that I can use the service with other objects and perform other tasks without instantiating new objects. The problem, as stated in the question, is that I'm not sure how to implement ITitleSaver. I need to implement it so that it is the same for Series and Movie, which would lead to dealing with Titles and casting which I do not want to.
Oskar Kjellin