alimango
alimango

Reputation: 655

Should I implement multi-purpose functions?

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?

Upvotes: 0

Views: 184

Answers (3)

ozona
ozona

Reputation: 446

The answer to this is easy.

Just remember that Worse is better

Upvotes: -1

Alex Martelli
Alex Martelli

Reputation: 881605

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"!-)

Upvotes: 1

cletus
cletus

Reputation: 625057

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
}

Upvotes: 2

Related Questions