Episode 03 – Function Size

Clean Code

Episode 03

The third episode talks about how big the function should be. Function should do one thing, do it well and do it only. This episode will address what that one thing is and how to find all the classes by putting the function in the right size.

  • The first rule of functions
    • they should be small. 4-6 is ok… but 10 would be too big!
    • The reason is to minimize the number of indentation, try block and decision branches. Thus, within this function, there must be other small descriptive functions.
    • When you have a function with several functional areas and variable used throughout the different areas, what you have is a class. A class is a group of functions use a common set of variables.
    • The process is to create a class with the common set of variables as field of the class and start creating small but descriptive method inside the class that eliminate repetitions, and make the method read like speech.
  • Are you out of your mind?
    • To create a sea of functions and methods, the only way to not get lost in it is to make sure to have well descriptive names for functions, methods and classes.
  • Efficiency
    • Function call overhead should not be a concern on most cases (except embedded system with very limited resources) since the overhead is so small in almost all modern computer. The first priority should be readability for the purpose of maintaining the software.
  • Coding Time
    • It takes time to make things small by eliminate redundancy and organize thoughts. But not doing so is to burden other to organize and understand the code.
  • Where do classes go hide?
    • large function is a scope that divide into different functionality and using the same argument variables throughout the scope. Thus, this is actually a class with the share variable as field of the class and different functionality are method for the class.
  • One thing!
    • A Function should do one thing, do it well and do it only.
    • If a function is doing two different functionality, then it is doing more than one thing
    • If a function is manipulate different level of abstraction, then it is doing more than one thing
  • Extract till you drop
    • extract function until you cannot and all the functions will be about 4 lines long.
    • braces in if and while statement means you can extract more functions.
    • Feature envy is a situation which one object do some computation or decision only base on another object’s field. A better approach is to let the object with the field do the computation and expose a method for the result which other object can call.
  • Other References
    • Literate Programming by Donald E Knuth.
    • Working Effectively with Legacy Code by Michael C. Feathers.
    • Refactoring by Martin Fowler