The quality code: How to write clean Function/Method

To write clean code is an art rather than science. From my experience at university, I did not get any course where I can learn to write clean code. Why do I bother clean code? Is it really important than solve a problem? No, it is not important than the solution of a problem but it will be pain in the future to maintain the code. For this reason, I have to write clean code to improve the quality and maintainability of the software. Here, I have presented a cheat sheet to create clean function or method:
  1. Function should do only one thing or logic [1].
  2. Function should be small not more than 30 lines [2]
  3. Function name should be descriptive rather than short name [3]
  4. The ideal number of function arguments [4]:
    1. Zero or no argument is the best policy
    2. One argument is the better policy
    3. Two arguments are the good policy
    4. Three arguments are the worse policy
    5. More than three arguments are not acceptable. The function should be converted to a separate class
  5. If a function contains try-catch block then the function should not have other code after catch/finally. 

          e.g:
public void doSomething(){
                 try{
                           //--------
                 } catch(Exception e){
                           //---------
                 }
}
Reference:
[1,2,3,4].  Martin., Robert C. "Functions" in Clean Code, Boston, MA, USA: Pearson Education Inc,
2009, pp 34 - 47

Note: Clean Code by Robert C.Martin is an excellent book to write clean code. I have just presented very
distilled version of the Functions chapter. So I can memorize the rules to write clean functions. You will find more from the book.

Comments

Popular posts from this blog

There is a process already using the admin port 4848 -- it probably is another instance of a GlassFish server; ERROR

How to Convert OutputStream to InputStream

How to compile and install GraphicsMagick (GM) in Linux