We all know that a function should be small, but how small is small. We all know that a function must do only one thing and one thing only. But what is actually one thing?
I am not a pundit, but I learn from pundits and read their writings and watch their lectures. So my blogs are not really my research, its what I have learned.
What I have learnt about size of a function is it must be smaller than small. It’s an area when you have exhaust yourself to get the smaller chunk but couldn’t chop it. So a function can be one liner, where it may return or set a member variable. And this is exactly how you know if your function is doing only one thing or more than that. If you can create a smaller function out of the current function with a different name than the current, then you know your function was doing two things.
- Conditional block: conditional block, when used in function, it should only be used to invoke another function. It’s not only make the function smaller, it improves readability by miles.
- Stepwise: if function A invokes private function B and C, the should be in that order as well after the A method
- Name and arguments: a function name should follow almost everything from variable name convention apart from the name should be verb instead of nouns. As for arguments, the lower the better, none is best. The more the arguments the harder it becomes to test. Uncle Bob three args Max. I say if its three or more then it might need its own data structure and pass the object.
- Standalone: your function must do one thing, just one thing. That makes it standalone. It must not make changes to any other part of the application, which means your your function has side effects, which is worse.
- Unwanted guest: a function that has name like setSomething(), you will never expect to have a return value out of it. Nie if you are really returning something on this function then you are expecting an unwanted guest on the middle of the night. Stop doing that. A function that says getSomething() or isSomething() prescribes that we are always expecting a return.
- Error handling: first of all, error handling is not part of a function, it’s a function itself. You should have a function to check error/exception and if no error then your function should perform the act it was supposed to play. Also the error handling function should return actual error instead of error code. Your are forcing the user of the error handling function to write another function to describe the error otherwise.
Personally I can never write a function following all the principles at the first attempt. So what I do is just writhe the function and then REFACTOR, REFECTOR & REFACTOR.