两个函数,或一个函数与不同的参数? [英] Two functions, or one function with different params?

查看:145
本文介绍了两个函数,或一个函数与不同的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常通用的'最佳实践'问题,但这里有一个例子。



假设我有一个电影编目应用程序。我想让用户有机会为他们的简介/评分信息指定IMDb或Metacritic。



我是否这样做:

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

或者:

  getRating(movieName,preferredSupplier); 

我喜欢第二个更好,但它意味着函数必须遵循完全不同的逻辑,具体取决于第二个参数的值(例如Metacritic可能需要一个屏幕抓取,IMDb可能有一个很好的API)。

或者我应该将它们合并?因为getRating()充当包装器函数,并根据第二个参数的值调用getIMDbRating()或getMetacriticRating()。 >

第二种方法允许您随时间推移优先供应商的数量,而且您仍然可以(内部)将这些方法作为两种独立方法实施。



如果这不过,我会看看两个类(Imdb和Metacritic),它们都来自一个RatingProvider基类,并以不同的方式实现getRating。



或者,如果我我正在看Bridge模式。



只有您知道系统中可能的更改位置,因此您知道您需要到这个城市去,但是一个可以以统一的方式获得评分的API,无论他们实际来自哪里,对我而言,成为一个更好的API比你必须通过选择一种方法或者其他。


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.

解决方案

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.

这篇关于两个函数,或一个函数与不同的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆