Is there such a thing as perfect code? Refactoring strategies & best practices

22 June 2020 at 10:30 by ParTech Media - Post a comment

“Pull request rejected!” – This are the exact things that no programmer wants to see, but unfortunately, they have to hear them daily. It’s not because the programmer hasn’t created good code, it’s just that every software company follows different code writing conventions such as some prefer adding comments often and other beliefs in the self-explanatory method.

Thus, we can say that there’s nothing like 100% perfect code because perception and norms of writing code vary a lot. However, if a programmer wants to beautify his code to match the client's expectations, then there’s a way through refactoring strategies and using some of the best practices.

What is refactoring?

Refactoring is the process of tweaking with a software system in a smart manner to improve its internal structure without altering external behaviour. In layman terms, refactoring is a process of reconstructing existing code without making any changes in the output. It is a well-defined technique used to modify existing code without affecting user-facing behaviour. what is refactoring

Source: Uruit

Refactoring has numerous benefits such as:

  • It is a simple process
  • Easy to understand
  • It makes simpler to pinpoint defects in code
  • Helps in eliminating deprecated or unused code
  • Reduce technical difficulties
  • Elevates performance

In spite of all the benefits, you have to remember that refactoring doesn’t automatically fix bugs or improve performance. If your code is already working, then refactoring will just help in enhancing and beautifying it using features like debugging, performance optimization, etc., Refactoring is like paraphrasing your already written text to remove any grammatical or spelling mistakes.

How does refactoring help?

Refactoring is a secret weapon in the hands of programmers that assist them in different situations.

refactoring situations

Source: Uruit

Weed out unwanted code and test cases

A programmer might have added lots of unused and deprecated code while developing – intentionally or unintentionally. Refactoring helps in identifying and removing this code . IDE's, like Visual Studio, will assist in recognizing unused functions, unnecessary references or properties by displaying how many times an element has been used in the code.

Focus on deleting rather than commenting

Whenever a programmer finds unnecessary code, a first instinct is to comment out the code instead of deleting it. But, refactoring here deletes the code to make it look smaller and easy to read. Plus, if your code is version controlled properly, then you have nothing to worry about as you have a previous version of the source.

Running basic improvements

In refactoring, the coder has to always analyse the basic things such as parsing logic, loops, I/O ops, exceptional handling, SQL transactions and so on. Some of the common areas of improvement are:

  • Switch – Multiple if-else block commands can be easily replaced with switch case.
  • I/O – If you have included I/O operations in your code to read or write files, then you have to ensure closing the streams.
  • Loops – When you are using loops to go through all items in the collection to search a particular item, then make sure to break and exit from the loops after you find the item.
  • SQL Transactions - It’s a common mistake to keep long SQL transactions.
  • Caching – If any static data is been queried repeatedly from the database, then the programmer should try to cache results during app loading.

Proper utilisation of tools

Modern IDE's offer inbuilt tools for assisting in coding operations such as extract, renaming, and formatting. Also extensions can add extra functionalities to IDE's. A good example is Resharper for Visual Studio.

Code revision

Before submitting your refactored code back to the source control ensure that your code is revised properly. Don’t let your years of experience or ego mislead you. All code need revision, no matter how experienced the coder that created it is.

Emphasis on testing

It is the stress point of the refactoring process. You have to run unit test cases while refactoring code so that by mistake you won’t modify the external functionality. It is a very important point.

Other best practices

Apart from code refactoring, you can consider a couple of other best practices to make your code perfect such as:

Ditch too long methods

Always keep one thing in your mind – a function or method should have one purpose only. If your function performs several things, then break it up into several methods with corresponding names. However, if you need to create a visual control, then define one method for a form and one for each control. Don't over-complicate code with too long methods with multiple functions.

Avoid extra long variable names & functions

After reading the name of a variable or function, it should be instantly obvious what the purpose of the method is. So no “run”. No “calculate”. No “a1”, “a2” and “a3”. To write a method name, a verb + noun combination will work best. When a method in a class, then place in conjunction with the class name. Similarly, to name event handlers, use “on” + event name. Moreover, you have to even name your function properly.

Enclose content in if statement

The If statement is a commonly used case. When you want the content body to react under certain conditions, then you have to put the code inside an if statement. Generally, if nothing much is happening in the else part of your if statement, then it is sensible to make revert conditions to verify the else part.

function saveChanges() {
  if (!this.hasChanges()) {
    return;
  }
  
  var user = this.getCurrentUser();
  if (!user.isAuthenticated() || !user.hasWriteAccess())
    this.showMessage(“Not authorised for saving changes”);
    return;
  }
  
  // Main code here..
}

Source: https://webagility.com/posts/shrink-your-code-or-die-refactoring

Don’t over use else/return

Use nested if’s and extract conditions into self-explanatory methods to make your code better to read and understand.

Don’t include too many if statement in conditions

Without including too many if statements in conditions, you will able to make code ready for non-technical persons also who might understand the purpose of the code.

No code is perfect

There’s nothing like perfect code because every company and programmer has its own version of perfect code. But, with refactoring strategies and best practices, coders can brush up their codes to meet the expectations of their clients. So, code can be improved or beautified, but can’t be perfected by anyone.

Latest