Jump to content
  • 0

Refactoring


Vishwadeep Khatri
 Share

Message added by Mayank Gupta,

Refactoring is an essential Agile process in which the internal structure of an existing program code is changed (without impacting its functionality) in order to keep it maintainable and simple. This helps in lowering the code complexity. 

 

An application-oriented question on the topic along with responses can be seen below. The best answer was provided by James Bob Lawless and Mohamed Asif

 

Applause for all the respondents - Gaurav Mathur, James Bob Lawless, Roshini Vijayan, Prabhu Gudelli, Prashant Philip Vargis, Arun Balakrishnan, Mohamed Asif, Kiran Kumar R, Praveen Thomas, Johanan Collins, C V Satish, Sandip Mittra, Chaitanya Shankar Nemani, Vijay Krishnan, Mohit Kumar, Parthasarathy Raghava.

Question

Q 423. Code Refactoring is an integral skill in an Agile Team. When should a team consider doing it? Are there any methods by which code refactoring can be avoided?

 

Note for website visitors - Two questions are asked every week on this platform. One on Tuesday and the other on Friday.

Link to comment
Share on other sites

17 answers to this question

Recommended Posts

  • 1

Code Refactoring is method of improving or updating the codes without changing the output and/or functionality of the solution.

 

A team must consider doing code refactoring is before making or adding any updates or new features to exisiting codes. Looking back and cleaning the exisiting code before adding in new will not only enhance te quality of the solution, but it will also make it easier for other developers to build on to the original codes.

 

Code Refactoring may not be avoidable in projects. However, these are the Main Techniques:

 

1. Red-Green Refactor - widely used in Agile Test-Driven Development. It breaks into 3 distinct steps

      1.1 Stop and Consider what's required (RED)

      1.2 Pass Basic Testing (GREEN)

      1.3 Impose Improvements (REFACTOR)

 

2. Refactoring by Abstraction - used for large scale refactoring to be done. It involves inheritance of class, order/hierarchy and extraction. The main purpose of abstraction is to minimize unnecessary duplication of codes (e.g. Pull-Up / Push-Down).

 

3. Composing Method - It involves streamlining of codes resulting to reduction of duplicates. Done through numerous processes, including "Extraction" and "Inline Methods".

 

4. Simplifying Method - It involves tweaking the interaction and relationship between classes. Adding, Removing and Introducing new parameters together with changing parameters with explicit methods and calls are all aspect of simplification.

 

5. Moving Between Objects - It involves making new classes and moving functionality between old & new classes.

 

6. Preparatory Refactoring - This is done when a software developer notices the need for refactoring, while adding new feature(s). By doing-so, the developer is minimizing future debugging or technical debt.

 

Conclusion:

Code Refactoring is keeping a clean, orderly and streamlined codes.  Do regular cleaning on your codes and you will hve better solution and productive work environment.

 

 

 

Link to comment
Share on other sites

  • 1

Refactoring makes the code Nimble and Workable as continuous iteration is done.

Note: It is not troubleshooting / debugging

 

It is done by changing internal modules/structures in the software application to keep it simple, legible, understandable, efficient and change friendly without affecting the output.

 

Code Examples: 

Before: Working Code

extension Collection

   {

    func episodes() -> [Episode]

        {

        return Episode.all.filter { $0.collections.contains(id) }

        }

   }

 

After: Refactored Code

extension Collection

   {

    func episodes(for user: UserData?) -> [Episode]

          {

           return Episode.scoped(for: user).filter { $0.collections.contains(id) }

          }

    }

 

When should team consider doing it?

It is Rule of Thumb:

1.       When developing the code for first time, JDI (Just Do it)

2.       When repeating similar module for second time, do it anyway

3.       When doing it for the third time, Refactor it  

 

Few general considerations for refactoring could be:

  • When code is cumbersome
  • When fixing a bug
  • Code smells
  • During code review
  • Ongoing maintenance project (spring cleaning)
  • Before adding a new feature to the original code
  • TDD (Test driven development)
  • After delivery on a tight deadline (Business pressure)
  • Mismanagement
  • Shortcuts taken during development
  • Speeding up without writing tests for new feature
  • Speeding due to wrong job size estimation (T-shirt Sizing)

Can we avoid Refactoring?

Refactoring is UNAVOIDABLE and it is Vital and Essential; however, if one is looking to avoid this can

  • Develop a clean perfect code (Most Optimal State)
  • Dump the Old code and start with New code, when developing features (Volatile environment)
Quote

Any fool can write code that a computer can understand. 
Good programmers write code that humans can Understand. 

                                                                                                             ~~Martin Fowler

 

Link to comment
Share on other sites

  • 0

Refactoring in Agile means improving the internal structure of an existing program’s source code without disturbing the external behaviour of the software. It is one of the critical and important practice for having success with an agile adoption.

 

The benefits of Refactoring can be seen as improving the code to ensure ease of maintenance, simple and easy to understand and importantly, keeping the pace of deliverable consistent despite there are changes in the code.

 

The development team should consider it while initiating the software project and anticipating changes during it’s lifecycle.

Link to comment
Share on other sites

  • 0

In an Agile Project Environment there is requirement for codes to be released every couple of weeks, hence there is a critical need to keep the codes or development process lean. The Agile delivery teams needs to move quickly to solve challenging problems that involve complex coding, where factoring helps maintain a greater level of code hygiene and enables team to deliver a high-quality product at faster pace

 

Code refactoring is a process practiced by a development team to clean up existing source code without changing the code’s functionality or behavior, which ensures getting the codes into a desirable state of reuse by the development team and hence very critical technical practice for the success of agile adoption. Overtime  across the agile release cycles the code complexity increases and it becomes difficult to maintain sustain the standard coding practicing and eventually harder to change. It’s extremely important to keep code clean and refactoring help the dev team to constantly respond to the code’s evolution. 

 

The potential benefits of adopting this practice of include removal and reduction of technical Debt and code smell, improving code readability, a better QA experience, and overall improved structure and functionality,

These together helps organizations save time and money. 

 

 The best time to consider refactoring is :

 

1) Before adding any new feature or updates or new requirement to existing code. Going back and cleaning up the current code before adding in new programming will improve the quality of the product and make it easier for future developers to build on the original code.

2) Another time to think about refactoring is soon after the product release to market.  Since the Dev Team will now have more availability to work on refactoring before moving to next sprints.

Standard practice is to write unit tests before moving ahead with code refactoring and execute them before and after refactoring to validate that the external behavior of the software system is not interrupted with this practice.

 

There are times when refactoring can be avoided Visa Via:

 

1)      when an application is getting completely revamped from the start, refactoring is not necessary, as it would be much more efficient to simply start from scratch without effort wastage.

2)      Another situation to skip refactoring is when trying to get a product to market within a set time frame when Refactoring can become quite time-consuming. Adding any additional coding or testing to an already tight timeline will lead to frustration and additional cost for the client and hence avoided

Link to comment
Share on other sites

  • 0

What is Code Refactoring ?

 

  • One need to build great foundation before embarking on building further floors on top of it.
  • Before we want to bring/ add / new articles to our residence, we need to make our house in order (remove,  unwanted stuff) --- this is nothing but doing housekeeping before one want to do further.

 

Like above examples, same is true for (software) Code refactoring. Code refactoring is a process of editing and cleaning up the old software codes which have inherent duplication, complexity, cumbersome internal structure without affecting the functionalities and behavior of the software. Code refactoring is integral part of any software / application project development.

 

Code refactoring is also integral to agile code / process development. That is very important part of Test Driven Development (TDD) flow which is nothing but iterative and continual improvement process. TDD approach is also called Red-Green- Refactor cycle.

 

When should a team consider doing it?

 

Refactoring is normally considered before adding new features. It is also done as part of “maintenance and housekeeping” as part of life cycle management of code. This is also done to simplify, help in ease of understanding and maintenance by end user.

 

Code refactoring is not something meant for fixing bugs, solving performance issues. Code refactoring is also not Code optimization where latter aim is speed/ delivery.

 

Are there any methods by which code refactoring can be avoided?

 

By doing anything right first time, one avoids rework, maintenance costs. Same is true for code refactoring. By developing code in subsets with simple, easy to understand, effective structure and by cyclic iteration of testing at each phase, code refactoring can be reduced/ avoided to great extent.

Link to comment
Share on other sites

  • 0

Code refactoring is the process of making changes in the structure and design of the code for making the coding simpler and easier to understand for the programmers. It helps in the maintenance of the code. In an agile project, code refactoring can be done before introducing new features or adding updates to the existing code. This will help in improving the quality of the code as well as help the developers to build on the original code. The best way to do code refactoring is to divide into smaller steps and perform timely testing before moving into the next update. Code refactoring can be avoided when the application has to be completely revamped or when the product need to be brought to market is a short time frame. 

 

Code refactoring can be avoided by doing the coding in a systematic way thereby ensuring good design and structure to the code initially itself so that no time need to be spent on code restructuring.

Link to comment
Share on other sites

  • 0

Code refactoring is a technique used in DevOps software development approach. DevOps stands for development and operations – a practice which merges development, quality assurance and operations (deployments & integration) into a continuous set of processes, thus making it an extension of agile and continuous delivery model.

 

Code refactoring involves cleaning up of existing source code without impacting its functionality. This helps in improving the efficiency and maintainability of the written codes. Potential benefits of code refactoring is to reduce technical cost, improve readability, better QA experience, and overall improved structure and functionality which helps in saving time and money.

 

Code refactoring activity is inevitable if we need to avoid ‘code rot’ which occurs due to duplicate codes, myriad patches, bad classifications, and other discrepancies. Different developers writing codes for the same software in their own styles can also contribute to ‘code rot’.

 

When should we consider s/w refactoring?

Ideal time to refactor codes is prior to adding any updates or new features to existing code. This cleansing activity of the current code before adding in new programming will help to improve the quality of the product as well as make the life of the future developers easy for building on top of the original code.

 

Another instance to do refactoring is immediately after we deliver a product to market. It might sound a bit weird as we have finally launched a product after working for months, maybe even years, and now we must go back to the beginning? Apparently, that would be the right time to take a stock of the code inventory, as chances are developers now have more availability to work on refactoring before moving on to the next job.

 

Are there any methods to avoid code refactoring?

To avoid refactoring there aren’t any specific methods however there some ways by which we can try minimizing code refactoring as well as the stress that activity creates. Some of them to list would be

- Write perfect code the first time that not only takes care of the current requirements but future ones too.       Start with a perfect code base.

- Deploy developers who write perfect codes

- Any changes in the requirements try not to change the codes or modify the existing one. Instead, write          new codes that can perform the same functionality as the old one. If necessary, scrap the old one.

- Write good unit tests so that even if there is a refactoring instance that occurs, it isn’t a painful or stressful     experience. Such tests will give the freedom to change your code knowing that many of the inevitable           errors and unintended consequences will be caught.

 

In short, since we are not having the luxury of living in a ‘frozen’ world of requirements and changes, refactoring plays an important role in avoiding messy codes and tough maintenance of the software. It is a natural part of the software and not a preference.

Link to comment
Share on other sites

  • 0

Code Refactoring :

 

Code refactoring is about improving the quality of the code by simplifying the code and improving its agility. Refactoring can be done at a code, database or an user interface level. The simplified code increases the ability to add more features, making it adaptable to change quickly as per the customer needs. A well factored code allows to solve problems faster. In simple terms refactoring is the process of cleaning the code by removing the unnecessary codes and replacing complicated, incomplete ones with simpler and reusable codes, making it less prone to errors and easy to maintain.

 

Why refactoring needs to be considered :-

 

  • It helps to improve the overall design of a software/application.
  • Making the software less heavy on codes, increasing the speed of execution.
  • Refactoring will improve the consistency in code ,design, structure, database and user interface of an application .
  • It makes the future changes on the application easy and simple.
  • Refactoring brings in convenience of maintenance.
  • The removal of redundant codes, reduce technical debt and improves the performance.
  • It Improves reusability of the software codes.
  • It improves the ability of bug identification and reduces the chances of bug occurrence.

 

When to do refactoring :-

 

Throughout  development stage :- In accordance with the rule of thumb “ Rule of three “ in computer programming , which states that when a similar code is used thrice ,the same requires refactoring on the third time and it should be extracted as a new procedure. The refactoring to be done here to avoid duplication, as it makes the code harder to maintain.

Choosing an appropriate design would help here to avoid duplication

 

During regular intervals of development :- A dedicated  timeslot could be defined in the development cycle to identify the ways to refactor. We will be able to address many bugs during the development itself as most of them are result of unstructured and inconsistent codes. 

 

During code review:-The code review is the last stage/chance to perform refactoring in a development lifecycle. Here the easy or quick fix in the code could be performed.

The advantages of refactoring performed at this stage is that it provides a view of the overall area of impact ,when the refactoring is applied.

 

When to avoid refactoring:-

 

The refactoring needs to be avoided in the below mentioned scenarios

  • When the program’s general behavior will be altered by refactoring :- The refactoring is about changes in the internal codes while maintaining the overall behavior of the program. The refactors which will alter the program behavior ,needs to be avoided.
  • When there is a chance of making a mistake :- As time and effort is involved in refactoring, avoiding the same is recommended on scenarios, where there is a possibility of making an error.
  • When the code is already clean : - if the code has no redundancy, bugs, no new features to be added and it meets all the required programming standards, refactoring initiatives could be avoided to save the effort.
Link to comment
Share on other sites

  • 0

Code refactoring is the process of restructuring the existing code – structure, content, design etc without having any changes to its functionality/behaviour. Code refactoring is done to make the code simpler – reduce complexity in terms of the logic used, cleaner, better readable, maintainable and efficient which would also help in improving the performance.

In agile where the focus is on smaller continuous iterations it is paramount to have code refactoring which will ensure the code quality is improved continuously through modifications

Certain things have to be kept in mind while refactoring code.

·       Refactored code needs to be testable and should be tested appropriately before changing

·       Refactoring should be done in an incremental manner

·       It needs to be done by breaking down the code in smaller chunks, refactoring should be small

 

Refactoring is essential and it has to happen. However if you want to avoid refactoring altogether, following steps could help but is very difficult.

·       Coding the perfect way: though this might be absurd but the perfect code might be the first thing that can help you from not having to refactor later

·       Sufficient testing : Sufficiently testing the code when you write it initially can avoid refactoring to an extend

·       Simple logic : Code logic can be written in simple or complex logic. It is always better to stick to simple terms while coding which will help in understanding it better for anyone referring and would help in avoiding any refactoring need arising due to code complexity

 

 

Link to comment
Share on other sites

  • 0

Code Refactoring involves changing the structure of the code, which may also be labeled as changing the factoring of the code. While code factoring changes the structure of the code, it does not change its functionality. The benefits of Code Refactoring are that it helps to improve the structure, design, and implementation of the code, making it more readable, less complex, easier to understand and maintain without changing its behavior. While code refactoring does not change the functionality, it can improve performance wherein the code uses less memory and works faster.

Code refactoring is done in a series of smaller steps called micro-refactoring. Such small steps done continuously, help in removing hidden bugs and software vulnerabilities. However, if code refactoring is not done well, it can introduce bugs into the system.

Benefits

Maintainability and supportability. Refactored code is easy to read and understand. Its logic is not only clear to the person who has written the code, but also to the one who is maintaining the code.

Scalability and Extensibility. It is easier to scale and extend the capabilities of Refactored code.

Saved resources such as time and money in the future.

Problems

Code refactoring is not easy. It requires understanding the metadata, data models, dependencies, and the very structure of the software system. With the high turnover of team members in the software development industry, the new team will have to recreate this understanding of the software system.

Code Refactoring should be avoided when the modifications are made, the structural architecture of the system could deteriorate. This can affect the maintainability and comprehensibility leading to a total change to the software system.

Reference

https://en.wikipedia.org/wiki/Code_refactoring

https://lvivity.com/what-is-code-refactoring

 

Link to comment
Share on other sites

  • 0

Code Refactoring is a technique/skill used by the agile software developers to improve the structure of the code without compromising the functionality and external behavior of the  code.

 

It is achieved by applying micro refactorings which are standardized actions. The introduction of code refactorings brings about very small changes in the code without adding any new bugs.

 

The agile team normally consider refactoring during:

* Code reviewing: Its done just before code goes live

* Scheduled Intervals: Club its introduction along with with routine scheduled actions

 

Benefits

* Easier to read both for the originator and other developers who  may work on it.

* High maintainability of source code 

* Expressive Internal Architecture

 

Avoiding Refactoring

Avoiding the code refactoring completely is an ideal situation. The only way to do that is by "code is written perfect the first time" which is akin to "first time right" or "Zero Defects" in the world of Quality

 

Link to comment
Share on other sites

  • 0

When the code used for development is restructured without impacting any of the external behaviour or any functionality is known as Code Refractoring.

 

The code refactoring can be achieved in multiple ways. The most common is to add or remove, introduce or replace parameter with explicit method and method call and so on. There are several techniques available which can be used for achieving code refractoring. Some of the most common are Red Green Factoring, Refracting by Abstract, Simplifying methods and so on.

 

When we want to implement any new feature in the application, code refractoring should be considered. Below are some of the common areas where we need to follow this approach.

·       Standardize the coding so that the defects can be fixed without impacting the other functionality

·       Uniformity in usage of the code so that any developer can understand in future

·       Patch any new features without impacting the entire functionality

·       Reuse of the code for any similar development

 

In the real life scenario it is important to have code refractoring as every software will keep on evolving. However, we can avoid this in those areas where below conditions prevails.

·       No new feature & functionality to be added

·       When the development has to be done in very faster pace as Code Refractoring is time consuming

 

In my opinion Code Refractoring is a very strong method a developer can use. There are many developer using this concept in a complete different level.

Link to comment
Share on other sites

  • 0

Code Refracting is all about the improving or simplifying the designs of existing codes or code components without changing/impacting any external  functional behavior.

 

Usually, team does the refactoring in the below instances :-

1)      Slicing a large technique to simpler & smaller focused techniques

2)      Rewriting the names of variables & parameters to make it clearer & more meaningful

3)      Moving the responsibilities towards more appropriate of class or division from the existing one

4)      Introducing new interfaces or changing exiting interfaces

 

Refactoring is also an important principal technique for controlling technical debt. These are 3 types

 

Type of Technical Debt

Causes

Methods to avoid Refactoring in Technical debts

Naive Technical Debt

Unclear Methods of execution,
Accidental,
Ignorance,
non-Vigilant

Providing best design pattern,
documentation and guidelines

Unavoidable Technical Debt

Upgrades,
Newer versions availability in the market,
Change requests or features addition in Scope during the mid of development

Future Proofing the Original Designs,
Codes should be repeatable & often useful to avoid the huge cost incurrence due to scope change

Strategic Technical Debt

Missing proper quality code practices,
Either refactoring too often than usual,
Or refactoring entirely is missing

Including PR & Design Reviews,
Monitoring Standards,
Sign Off's at each developmental stage

 

Additionally,  there are 3 more methods to avoid technical debit which also avoids code refactoring

-Managing the accrual of technical debt by using good technical practices  

-Making the technical debt visible by using a defect-tracking system

-Servicing (repaying) technical debt by remodeling the infrastructure and code development practices often as per the latest standards

 

Code Refactoring cannot be 100 % avoided. It will be part of Software development. However, those who follows the industry expertise, proves on its minimizing and always stands first at producing the acceptable software product.

Link to comment
Share on other sites

  • 0

Refactoring or more specifically Code Refractoring is a process by which a computer code is restructured without changing its behaviour. 

Restructuring makes the software more maintainable and extensible by improving the design, structure and implementation of the software without changing its functionality. 

Refractoring might also help developers to detect and fix dormant bugs and potential vulnarabilities. 

Applied to mechanical product design, refactoring would be a process of refining a design with a rapid prototyping and testing cycle used along with tools such as Deisgn FMEA that results in a more refined design before finalization.

Refactoring is usually performed before adding major updates or features. Interestingly, another perfect time to consider refactoring is when you've actually delivered the product. This could be the best time to do some housekeeping on your code to clean it up and make it more understandable. 

Code refactoring could be avoided if you're going to revamp the complete software since it would be better to start from scratch. 

In agile development refactoring is seamlessly integrated in the process itself so much so that build test and refactor cycle is a continuous process.  

 

 

red-green-refactor.png

Link to comment
Share on other sites

  • 0

Refactoring implies improving the internal structure of an existing program source code, while safeguarding its external behaviour. It simply refers to particular behavior preserving transformation.

 

It is not limited only to

  • writing the code again
  • fix the bugs
  • Improve aspects of software like its interface etc.

Refactoring actions are inclined towards the below to maintain the desired preserving conditions

  • Duplicates- removing duplicates enables to change the code in the future
  • Clarity - Renaming and redistributing responsibilities captures much more concepts thus improving reading and comprehension time

Below are the benefits of refactoring:

  • it improves objective attributes of code corelating with ease of maintenance
  • It helps code understanding
  • It encourages developers to think and understand design decisions,
  • It favors emergence of reusable design patterns and code modules

 

 

 

Link to comment
Share on other sites

  • 0

Code refactoring is a process that involves modifying and cleaning up previously written code without changing the function of the code. In other words, it is improving the internal structure of an existing source code, while preserving its external behavior. Code refactoring can be a great asset for project especially for projects driven in agile methodology. In an agile project, depending on the business requirements of the customer, the product/service keeps changing. Hence, the design structure should be robust to accommodate the changes.

 

Refactoring of the design/code can help to achieve the objectives.

·       Refactoring makes the code easier to modify

·       Refactoring makes the code easier to understand

·       Refactoring helps in sharing knowledge

 

Code refactoring can be considered for two reasons:

1.       Before adding any updates or new features to existing code – Helps in improving the overall quality of the product

2.       Post product delivery – To make sure the code is standardized and as a part of housekeeping.

 

Code refactoring should be primarily be used for clean-up effort. However, if code refactoring is not sufficient to support the business needs or when an application needs to be completely revamped, then rework effort should be taken up.

Link to comment
Share on other sites

  • 0

The best answer to this question has been provided by James Bob Lawless for highlighting the various methods by which refactoring can be avoided and Mohamed Asif for highlighting multiple guidelines for doing refactoring. 

 

And then, there are a couple of answers that are a must read - Chaitanya Shankar Nemani for giving the perspective of technical debt, Johanan Collins for highlighting a risk in refactoring.

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

  • Who's Online (See full list)

    • There are no registered users currently online
  • Forum Statistics

    • Total Topics
      3k
    • Total Posts
      15.1k
  • Member Statistics

    • Total Members
      53,955
    • Most Online
      888

    Newest Member
    Aakar Gupte
    Joined
×
×
  • Create New...