Refactor your code in Android studio

code refactor

All of us as a developer never feel happy after going through the code we wrote few days or weeks ago. And end up replying something similar to this –

Why I wrote it this way. I would do it better if I could rewrite it today
And that’s when code refactoring comes into picture to make our code better readable, maintainable. The most common attempts of code refactoring are to rename, signature change, extracting from existing methods. So in this article I will explain all of you some of the refactor features of Android studio based on common code refactor attempts in quick and no time.


code refactorRenaming of a variable, method or class is most common attempt by most of the developers but after using of them it will be a headache to identify all the references and change it every places but that can be easily refactored in Android studio by right click select refactor menu and then select Rename menu or press Shift+F6 after selecting the respective variable, method or class name.


Change signature

Code refactorIn initial stage of coding of any module, so many developers do the mistakes of creating Classes or methods with inappropriate signature and then those classes and methods get inherited in other child classes which will again create a fear during the time of code refactor for such developers but Android studio gives another such handy feature to get rid off of such nightmares. You first need to select the method or class name and then right click select refactor menu and then select Change Signature menu or press ctrl+F6 and rest will be taken care by Android studio.

Extract method

code refactorCode refactor is really needed when your method size increased from more than 3-4 lines of code and which happens most of the time during initial phase of development and nothing wrong in it. But after then refactoring is again a challenge which you all can accept thanks to Android studio with few simple steps. You have select the block of code you want to refactor first and then press ctrl+alt+m and you will get a dialog asking for your new method signature and there you have to edit the method name in the edit box and add or remove any parameter if you want and press Ok.

After all such code refactor make sure you test all the possible test cases to assure that everything is working like earlier. So these are the most common code refactor option which all of us needed in our day-to-day life, but Android studio has many more such options make sure you try others too. I would like to hear about those.

If you want to learn fundamentals of code refactor check this out.


Note: This article is based on Windows environment, in other Operating system commands may change.

Happy coding!!!

Leave a Reply

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