views:

98

answers:

3

I'm using CodeIgniter and I got a model that fetches let's say all recipes where you can set the offset and the limit. Should I extend that function for retrieving a single recipe? Is it good practice?

+2  A: 

Your goal should be to minimize code duplication while maximizing understandability. These two are often at odds. You can end up with minimal code duplication but have 12 optional parameters to a function. So some general tips:

  • Consider packaging common functionality into a third function and then the two functions can both call that as needed;
  • Using an object or array of arguments if have more than 3-4 parameters to a function;
  • Code duplication is to be minimized not completely eliminated. Sometimes the clearest solution involves a certain amount of code duplication;
  • The purpose of a function or object should be clear. If what it does completely changes based on a parameter then you're likely going to confuse people.

With your specific case, I imagine you'd want to end up with something like:

function get_recipes($offset, $limit) {
  // execute query and get resource
  $ret = array();
  while ($row = mysql_fetch_assoc($rs)) {
    $ret[] = build_recipe($row);
  }
  return $ret;
}

function get_recipe($id) {
  // execute query and get row object
  return build_recipe($row);
}

function build_recipe($row) {
  // construct a recipe object from the row
}
cletus
Actually I've combined get_recipe and get_recipes. if the id is set and the other params is null, it returns only one field etc.. is it ok?
alimango
I think thats potentially a little confusing but it's hard to say without specifics. AS a general rule, I prefer a scheme much like I've done that has clearly named functions (although these three could be named better) that use functional decomposition to reduce duplication.
cletus
I agree with cletus in separating the `get_recipe` from `get_recipes`. It will be easier for the one who will maintain your code to understand your code.
Randell
I agree that it's easier to maintain and I'm for that. Thanks for the insight guys :)
alimango
+1  A: 

In general, for clarity, a function should do a single task. However, "getting N rows" IS a single task - even when N==1; so I'd say this case qualifies, i.e, the function's NOT really "multi purpose"!-)

Alex Martelli
A: 

The answer to this is easy.

Just remember that Worse is better

ozona