Monday, October 30, 2017

Refactoring Code

I believe refactoring is a very important trait for a programmer. Refactoring helps in reducing the repetition of code and also helps to make the code generic. Like everything else in life, code too accumulates dust if not maintained constantly. Constant refactoring helps in keeping the code clean. Learning to refactor early on in programming career helps in having a great career. In fact it is something we don't even need to learn as, as human beings we are experts at identifying patterns and  crux of refactoring is pattern matching.

Recently I was reminded of the age old programming puzzle by a friend and wanted to use that to capture my thoughts on refactoring.

The code is to generate something like this:



The initial code we would typically write would be specific to this particular output . (See the initial iteration in JSBin)




The first thing that strikes from this code is the repetition of the code block within the two for loops. The first refactor will be to extract this into a function. 

Anytime we see code being repeated, it immediately calls for refactoring. It is well known that lesser the code lesser will be the defects. 

The refactored code could look like this: (1st round of refactor)

This is still specific to the particular output. It could further be refactored to be generic, suitable for output of similar pattern, say a grid of 15x15. (2nd Round - Generalization)


Still it provides the same output as the first code, but, in a much generic way, with less repetition. 

The key rules of refactoring:

#1: If there is repetition of code, it is a no brainer for refactoring

#2: If the code could be applicable for similar problems, refactor it to be generic. Just be aware of the ROTI (Return on time invested)

#3: Don't make the code clever in the name of refactoring. The code should be clear to understand. Not clever. This code could be refactored to use a single loop, but, at the cost of clarity.   See line 24 in the code below. (This is fairly straight forward than the clever codes out in the wild. But, you get the drift.)


(Have a look at http://jsbin.com/bemitew/edit?html,js,output which has this 1 loop implementation)

Happy refactoring!




No comments:

Post a Comment