Reputation: 655
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
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
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:
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