Can you explain the concept of refactoring?

 Posted by ArticlesMaint on 10/1/2009 | Category: Project Management Interview questions | Views: 4193

If you read the XP life cycle one of the things after we implement the task is code refactoring. Refactoring the process of changing the software in such a way that it does not change the behavior of the code but on the other hand improves the internal structure. No code can be perfect with architecture, coding conventions, high reusability at the first level itself. Normally it improves over the time. It helps developers to implement the necessary solution today and improve / make the code better tomorrow. Refactoring is the process of changing the system to improve the internal structure with out changing what the system does. Below are three major activities performed during refactoring.

Simplify complex code

XP is all about light-weight and simplicity. This holds true not only for a process but also for coding. When you see a code can be simplified, discuss the same with your pair developer and implement the same. For instance below is code which was further simplified in to one equation:

Figure: - Simplify Code

Move similar operations in to reusable code.
If we are having similar operations move them to one reusable code. For instance in the below class we have various sort function which sorts by phone, code, name and date. We can combine the same in to one function called as sort and make it simple.

Figure: - Reusable code

Remove duplications and redundancy

When a project has constrained time lines it’s very much possible that project can have lot of duplications. So when developers have executed the task they can review for these kinds of duplications. For example the below figure ‘Remove duplication’ shows how the phone number duplication is removed from the customer table. The customer table had repetitive fields like mobile number, land line and office number. In abstract terms these represent telephone numbers. So we split the customer table in to two tables one is the customer table and the other is customerphone and built a relationship between them.

Figure: - Remove Duplication 

Below is again one more scenario where we have an invoice class which has two methods (“GenerateInvNo” and “CreateInvNo”) and they do the same thing, generate unique invoice numbers. We can refactor / improve the code by combining these two methods in to one.

Figure: - Code Duplication

No Code is perfect it has to be made perfect.

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response