Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two functions, or one function with different params?

This is a very generic 'best practice' question, but here's an example.

Let's say I have a movie cataloging app. I want to give my users the chance to specify, say, IMDb or Metacritic for their synopsis/ rating info.

Do I do this:

if (preferredSupplier == "imdb"){
      getIMDbRating(movieName);
}else{
      getMetacriticRating(movieName);
}

Or this:

getRating(movieName, preferredSupplier);

I like the second one better, but it means that function will have to follow vastly different logic depending on the value of the second parameter (for example Metacritic might require a screen scrape, where IMDb might have a nice API).

Or should I combine them? As in getRating() acts as a wrapper function, and calls getIMDbRating() or getMetacriticRating() depending on the value of the second param.

like image 653
ChristianLinnell Avatar asked Dec 17 '22 08:12

ChristianLinnell


2 Answers

The second one allows you to extend the number of preferred suppliers over time, and you can still (internally) implement these as two seperate methods.

If this were me though, I'd be looking at two classes (Imdb and Metacritic), both derived from a RatingProvider base class, and implementing getRating differently.

Or, if I were getting my Patterns hat on, I'd be looking at the Bridge pattern.

Only you know where the likely change is in your system, and so you know whether you need to go to town on this, but an API where you can getRatings in a uniform way regardless of where they actually came from would, to me, be a better API than one where you have to make those decisions by chosing one method or the other.

like image 131
Martin Peck Avatar answered Dec 19 '22 22:12

Martin Peck


It might be a good idea to have a RatingProvider class with getRating method.

You could have different rating providers as its subclasses, which will have their own implementation of how it would fetch/process the ratings.

like image 36
shahkalpesh Avatar answered Dec 19 '22 21:12

shahkalpesh