Code Refactoring

Writing clean code is what you must do in order to call yourself a professional. There is no reasonable excuse for doing anything less than your best.

Hello Friends,

Code Readability and Coding structure is the most Important factor when you are working with the team.

Well structured code easy to read and understand for other developers.

Code Refactoring is one way to make code more readable and easy to understand for others.

Function with a lot of lines of code is less readable and is annoying for readers to read those lines.

It’s good practice to break down the code into individual functions in which each function does a specific task. We can reduce the number of lines by refactoring.

We can do refactoring in two ways

  • Manual Refactoring
  • Through Xcode shortcut
Manual Refactoring

It’s an old way of refactoring code. It is a time consuming method.

Lot of things you need to determine while manual refactoring as

  •  To determine how many parameters that function accepts.
  • To determine the parameters are mutable or immutable.
  •  Whether function returns any value or not.
For Example:

 

In this example you may see a func (init) having lots of lines, When you refactor above code manually. You can write a separate function for sorting arrays as this function can be treated as a separate task and you may reuse it for other places too.

  • Create separate function

  • Copy paste corresponding lines of code in the function


→ Notice warnings and errors we get while copy and paste.

  • Determine the required parameters needed to pass and Pass the parameters


→ We pass the parameters but still we may be getting errors because of the nature of parameters.

As Functions parameters are immutable in nature to make mutable we have to mention inout.

See, We have to follow many steps and sometimes spend lots of time on small tasks. Xcode has a quick way to do it for you, here we go

Through Xcode options

We can do the same tasks in fews clicks using Xcode options.

  • Select the portion of code you want to refactor

  • Right click on code

  • Select Refactor and then Extract to Methods

  • Mention Function name

Notice when we select extract to methods it automatically creates a function which accepts all the required parameters and nature of parameters with access modifiers and you are done.

Wrap up

See how easy it is to refactor code in a few clicks. It makes your code clean, reusable, readable.
This is the simplest way to refactor your code.

Thank you, For your interest in the content!

Please follow and like us:

Leave A Comment

Your email address will not be published. Required fields are marked *