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
2009-09-02 02:03:48
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
2009-09-02 02:15:29
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
2009-09-02 02:31:29
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
2009-09-02 02:42:33
I agree that it's easier to maintain and I'm for that. Thanks for the insight guys :)
alimango
2009-09-02 02:52:28
+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
2009-09-02 02:34:24