patterncppMinor
Separate method for a single line code? Or embed in the caller function?
Viewed 0 times
thelinemethodcallerfunctionseparatesingleforcodeembed
Problem
I'm having an argument with my boss about whether or not it's better to have a separate function for a single line of code.
The code reads something like:
Is it better coding style to include the line
in a separate function name such as
The code reads something like:
while (count <= poscount)
{
key = etc.substr(pos2prev+1, pos-pos2prev-1);
std::string::iterator end_pos = std::remove(key.begin(), key.end(), ' ');
key.erase(end_pos, key.end());
val = etc.substr(pos+1, pos2-pos-1);
//process key and val
DEBUG("{\n\t%s:%s\n}\n", key.c_str(), val.c_str());
json_object_object_add(paramList, key.c_str(), json_object_new_string(val.c_str()));
count++;
pos2prev = pos2;
pos = etc.find("=", pos+1);
pos2 = (count == poscount) ? etc.find("\0",pos2+1) : etc.find("&", pos2+1);
}Is it better coding style to include the line
json_object_object_add(paramList, key.c_str(), json_object_new_string(val.c_str()));in a separate function name such as
processKeyVal(), or leave it as-is?Solution
I'm guessing that your boss's argument is that a well named function would make the code more readable, and I agree with that in general. I often do that myself even when the function contains a single line.
In this particular example I would not bother though. The comment above the json-call says the same thing as the function name would, and there are no obvious advantages to make a function for a single call.
So if your question is specifically for this example, then I agree with you - keep it as it is, but if you want a more general answer, then I agree with your boss.
For example - if this one-liner is something that you use in more than one place, i.e. if calling the "processKeyVal()" function in more than one place makes sense. Then I say you should make a function of it even if it would contain only one line of code.
Or to put it another way - it is not (always) the number of code lines that should determine if you make a separate function of a code snippet.
In this particular example I would not bother though. The comment above the json-call says the same thing as the function name would, and there are no obvious advantages to make a function for a single call.
So if your question is specifically for this example, then I agree with you - keep it as it is, but if you want a more general answer, then I agree with your boss.
For example - if this one-liner is something that you use in more than one place, i.e. if calling the "processKeyVal()" function in more than one place makes sense. Then I say you should make a function of it even if it would contain only one line of code.
Or to put it another way - it is not (always) the number of code lines that should determine if you make a separate function of a code snippet.
Context
StackExchange Code Review Q#33434, answer score: 2
Revisions (0)
No revisions yet.