3 ms·
There is nothing wrong with a one line function. Nothing whatsoever. There are huge benefits to extracting a single line of code into a function. I'll just link
by InclinedPlane 13y ago
There is nothing wrong with a one line function. Nothing whatsoever. There are huge benefits to extracting a single line of code into a function. I'll just link to a stackoverflow answer I made on the subject several years back: http://stackoverflow.com/questions/785145/one-line-functions-in-c/785217#785217 http://stackoverflow.com/questions/785145/one-line-functions...
Summary: Performance almost certainly isn't an issue (compilers are smart). Abstraction leads to better design, using a well-named function can improve readability, making it easier to understand, easier to prove correct, and easier to modify. When you keep code inline it increases the inertia of the given design and implementation, extracting even a single line into a function (when warranted) can make it far easier to drastically change implementation. And if you want that single line of code to become several lines, or to switch to calling out to a web service, implement caching, add error checking or what-have-you that's made much easier when it's encapsulated inside a function than when it's sitting inside a block.
Componentization is always good, even when the components are sometimes very small. Like all design choices extracting code into its own function requires judgment based on experience but when done right it can have many benefits, even when it's a single line, even when it's a fraction of a single line.
Blindly following a rule such as avoiding making functions too small is just as big an error as avoiding making functions too large.
- henrik_w 13y agoSteve McConnell makes some good points about this in Code Complete too, one of which is "small methods tend to become bigger". Even if it started out as a one-line method, it is not unusual to later find the need to add something else to it. This is from memory (I don't have the book here), so I can't give a more specific reference to it.