[Learn Android Studio Chinese Course] Chapter fourth: Refactoring Code
Fourth chapter refactoring Code refactoring codes
Developed in Android Studio, the solution will not always be an overnight one. As an efficient programmer, you need some flexibility and code refactoring in your development, debugging, and testing. As you move through this chapter, you will understand how Android studio generates code, and in this chapter you will see how Android studio reconstructs your code. The greatest risk of refactoring code is the possibility of introducing unexpected errors. By analyzing the results of some risk refactoring operations, Android Studio reduces these risks and then activates the Find tool window, where you can preview your changes before the release-there marks any errors or conflicts.
Many of the refactoring operations described in this chapter can also be performed without the refactoring tools of Android Studio. In any case, you must avoid forced refactoring (for example, by reorganizing your code with a full-text find/replace operation), because in these cases, Android Studio cannot protect you from the errors introduced. Conversely, if Android Studio discovers that you are attempting a refactoring operation, it will try to avoid any foolish mistakes you make. For example, drag a JAVA source file from one package to another in the Project tool window, which will force the production of refactor? The move action, which analyzes the results of your move operation, allows you to preview those changes and then appropriately change all the import statements in the class to fit the new all-inclusive name.
The vast majority of refactoring operations are limited to a single method or class, and will not introduce errors into your project. Dangerous refactoring operations are those that involve two or more resource files. If the refactoring operation introduces a compilation error, the check Manager will flag those affected resource files with a red tag in the editor. Based on this, you can either try to fix them, or use ctrl+z| The cmd+z simply cancels the refactoring operation. If the refactoring operation is done with no compile errors, but involves too many resource files, you still have to test and verify that you have introduced any real-time errors. The 11th chapter covers the test.
Tip: You must submit any important refactoring changes as a single git commit, so you can then easily reply to that commit. The 7th chapter covers git.
This chapter focuses on using the best tools to perform refactoring operations. Before we visit our independent refactoring operations, we would like to point out that Android Studio has an extremely handy refactoring tool called Refactor? Refactor this. Always select this in the context menu, as shown in Figure 4-1, which integrates most of the useful refactoring operations. Shortcut keys are Ctrl+alt+shift+t | Ctrl+t, on the PC you can easily remember the initials cast.
Figure 4-1: The refactoring refactor this menu, which includes most of the useful refactoring operations.
Before you start the example in this chapter, modify the Sandbox.java file in chapter 3rd, which does not extend and contain any methods or member variables, like the following small fragment:
public class Sandbox {
}
Rename renaming
In the Project tool window, select sandbox and navigate to refactor? Rename or press Shift+f6. Brings up a dialog box to allow you to rename your class, or you can rename the names that appear in the comments, the test instances, and the inherited classes. Rename the sandbox to Playpen and click on the Refactor button, shown in 4-2. You will see the operation renamed in your project. Now please use CTRL + Z | Cmd+z Cancel this operation.
Figure 4-2: Renaming Sandox to Playpen
Change Signature Modify Signature
Changing the signature operation allows you to change the following properties of the method: visibility, name, return type, arguments, and exceptions thrown. Create a method in Sandbox.java, such as the following code snippet:
public string Greetings (String message) {
Return "Hello" + message;
}
Move the cursor over the word greetings (the highlighted bold character) and press Ctrl+f6 | Cmd+f6, or navigate to refactor? Change Signature. The result dialog box allows you to modify the signature of the method, as shown in 4-3.
Figure 4-3: Modify Signature dialog box
In the parameter table, click the string type parameter message, and change its name from message to Greet,4-3. Icons Green + and red-allows you to increase or decrease the parameters of the method separately. Also, you can edit their type and name in the parameter table. Also, when you modify the current method, you may decide to select the radio button for the delegate overloaded method. Selecting this button will keep your original method unaffected, but will generate another method for your new definition signature. In Java if you might consider a series of overloaded methods with the same name, but the order of the parameters and/or the type of the parameter differs. However, the changes you make do not limit the overloads of the method. If you wish, you can preview them before submitting them by clicking the Preview button. Press the Refactor button to finish and leave.
Type MigrationType porting
As the title describes, type porting allows you to migrate from one Java type to another. Let's assume that you have created a person class. As your development progresses, you find that person is too generic, so you create a manager class that extends to person. If you want to migrate all the person instances to the manager, you can easily use the type porting.
Place the cursor over the string declaration of the Greetings Method (in the highlighted bold word in the code snippet below) and press Ctrl+shift+f6 | Cmd+shift+f6 or choose refactor? Type migration. The results dialog box is shown in 4-4.
public string Greetings (string greet) {
Return "Hello" + greet;
}
Figure 4-4: Type porting, from string to date
Change java.lang.String to Java.util.date,4-4 as shown. Select Open file from the drop-down menu in the Select Range box. As with most refactoring operations, you can preview your changes by clicking the Preview button. Here we press the Refactor button.
MoveMoving
You can move the source code files by one of the following three methods.
? Drag the source file from one package to another in the Project tool window;
? Select Source file to navigate from the main menu to refactor? Move;
? Select the source file in the Project tool window and press F6.
Right-click (Ctrl-click on Mac computer) Com.apress.gerber.helloworld package and select New? Package. Name the refactoring target package. From the Project tool window, drag and drop the Sandbox.java into the refactoring target package and press OK when the Figure 4-5 dialog box appears. Any drag-and-drop operation performed in the Project tool window will automatically result in a refactoring move operation, which will allow you to safely move a class from one package to another.
Figure 4-5: Refactoring Move dialog box due to drag-and-drop operations
In addition to moving classes, you can also move member variables. In your sandbox.class, define a new member variable as follows:
public static final String hello = "Hello Android Studio";
Move the cursor over this line of code and press F6. Causes a dialog box to allow you to move member variables from one class to another. As shown in 4-6. Please click the Cancel button to cancel this operation.
Figure 4-6: Dialog box for moving member variables
Copy replication
Copy, a bit like move, press the shortcut key F5 or select the Refactor in the main menu? Copy to access. In the Project tool window, select Sandbox.java in the previously refactored package and press the F5 key. Select the Com.apress.gerber.helloworld package in the drop-down menu of the target package and click on Ok,4-7 as shown. It is not a good idea to copy the Java source files as we are here, because the results are ambiguous and there are common errors.
Figure 4-7: Dialog box for copying classes
Safe DeleteSafe Removal
Let's delete the class that we just copied. With the Delete button in the Project tool window in Android Studio, you can always delete files and resources. In the refactoring package just click on the Sandbox.java file and press the DELETE key. The Results dialog box allows you to delete using the safe delete check option. The advanced point of security removal is that we can query for any damage that could be caused by relying on this asset before performing the deletion, as shown in 4-8. If you send anything in this project that relies on this asset, you will be given an option to browse them, or click Delete anyway to force the deletion.
Figure 4-8: Secure Delete dialog box
Extract precipitation
Precipitation is not an operation but a few. This section covers some important precipitation operations: precipitation variables, precipitation constants, precipitation fields, precipitation parameters, and precipitation methods. In Sandbox.class, let's first remove all the member variables and methods from the white paper:
public class Sandbox {
}
Extract Variable Precipitation Variable
In your Sandbox.java class, define a method as follows:
Private String saysomething () {
return "Something";
}
Place the cursor over the hard-coded something value (in bold) and select refactor? Extract? Variable, or press Ctrl+alt+v | Cmd+alt+v then press ENTER, do not select the check box that declares final. Android Studio precipitates A local variable and names it based on a hard-coded string. You will end up with the following code:
Private String saysomething () {
String something = "something";
return something;
}
Extract Constant Precipitation Constants
When you develop Android apps, you'll find that you use a lot of strings as keys-for example, in maps and bundles. Therefore, precipitation constants will save you a lot of time.
Define a method like the following code snippet. Place the cursor over the Name_key string and press Ctrl+alt+c | Cmd+alt+c. The result dialog box is shown in 4-9. Here, Android Studio offers some suggested names. As a rule, constants should be capitalized in Java. Select Name_key and press ENTER.
Note: In order to create and process this method without a compilation error, you must import Android.os. Bundle
private void AddName (String name, bundle bundle) {
Bundle.putstring ("Name_key", name);
}
At the end you will see a constant name of Name_key, as defined below:
public static final String Name_key = "Name_key";
Figure 4-9: Precipitation constant Name_key
Extract field precipitation domain
The precipitate field converts a local variable into your class domain (a.k.a. Member variable).
Note: In order to create and process this method without a compilation error, you must import Android.os. Bundle
Define a method in your sandbox:
Private Date getDate () {
return new Date ();
}
Place the cursor on date (bold) and press Ctrl+alt+f | Cmd+alt+f. You will see a dialog box 4-10 shown. In Android, the first letter of the custom field (a.k.a member variable) name is in M. You will notice a drop-down menu that allows you to initialize the domain, domain declaration, or constructor in the current method. Select the domain declaration and press ENTER.
Figure 4-10: The Precipitate Domain dialog box
The results are as follows:
Private final Date mdate = new Date ();
...
Private Date getDate () {
return mdate;
}
To remove the final keyword, the result of this field is declared as follows:
Private date Mdate = new Date ();
Extract Parameter Precipitation Parameters
The precipitation parameter allows you to precipitate a variable and put it in the method of the envelope. Define a method in your sandbox:
private void SetDate () {
Mdate = new Date ();
}
Place the cursor on date () (bold) and press Ctrl+alt+p | Cmd+alt+p then press ENTER. The result of this method is shown in the following code snippet:
private void SetDate (date date) {
Mdate = date;
}
Method for precipitation of Extract methods
The
Precipitation method lets you select one or more lines of contiguous code into a separate method. There are two reasons why you would want to do this. The first is that the method is too complex. An algorithm block that breaks it to about 10 to 20 lines is easier to read and less error-prone than 100 lines of code.
Furthermore, repeating code is never a good idea, so if you find duplicate code, it's best to precipitate them into a method and invoke them in a repeating place. By precipitating the duplicated code into a method and calling it, you can keep your method in one place, and if you want to modify it, you just need to modify it once. Rebuild the following two methods in your sandbox as shown in Listing 4-1. You are free to copy and paste.
Manifest 4-1
private String Methodhello () {
String greet = "Hello";
StringBuilder StringBuilder = new StringBuilder ();
for (int nc = 0; NC < nc++) {
Stringbuilder.append (greet + NC);
}
return stringbuilder.tostring ();
}
Private String Methodgoodbye () {
String greet = "Goodbye";
StringBuilder StringBuilder = new StringBuilder ();
for (int nc = 0; NC < nc++) {
Stringbuilder.append (greet + NC);
}
return stringbuilder.tostring ();
}
As we have already mentioned, any time you find repeating a block of code or copying and pasting a block of code, you have to consider the precipitation method. Select the bold highlighted block in Listing 4-1. Press Ctrl+alt+m Now | Cmd+alt+m precipitation method. A dialog box is rendered that lists the signature of the method. Rename this method as shown in Getgreet,4-11, then click OK.
Figure 4-11: Precipitation Method Dialog box
Android Studio scans your files and sees you have another compelling code block case. In the Process Replication dialog box, click Yes to accept the suggestion, 4-12.
Figure 4-12: Copy Processing dialog box
You will see the code in Listing 4-2. Now the result method is easy to keep somewhere.
Listing 4-2: The result code derived from the precipitation method operation
Private String Methodhello () {
String greet = "Hello";
return Getgreet (greet);
}
Private String Methodgoodbye () {
String greet = "Goodbye";
return Getgreet (greet);
}
private string Getgreet (string greet) {
StringBuilder StringBuilder = new StringBuilder ();
for (int nc = 0; NC < nc++) {
Stringbuilder.append (greet + NC);
}
return stringbuilder.tostring ();
}
Advanced RefactoringAdvanced Refactoring
The rest of the refactoring operations described throughout this chapter are high-level. If you are interested in simply and quickly improving Android Studio, already have enough knowledge to effectively use refactoring operations, maybe you can skip this section. But anyway, if you have a better understanding of Java and want to delve into more refactoring operations, keep looking.
Remove all member variables and methods from the Sandbox.java, starting with a blank sheet of paper.
public class Sandbox {
}
Right click on the Com.apress.gerber.helloworld package in the Project tool window (Mac computer with CTRL + click), select New? Java Class. Name this class for Minibox. Modify the Minibox class definition to inherit from the sandbox and have a member variable called Mshovel, as shown here:
public class Minibox extends Sandbox {
Private String Mshovel;
}
Push members down and pull members uppushing up member variables and pulling down member variables
Push-up member variables and pull-down member variables for inheritance. Notice that we have defined a MSHOVEL member variable in the Minibox class. Let's assume that mshovel may also be useful for other subclasses that inherit from the Sandbox class. To do this, open the Minibox class and select refactor? Pull members up. The results dialog box is shown in 4-13.
Figure 4-13: Push the Member Variable dialog box
Mshovel will be selected by default, and because the sandbox is the parent class of Minibox, the push-up member variable combination window is set to the Com.apress.gerber.helloworld.Sandbox class by default. Click Refactor, view sandbox and Minibox, you will find Mshovel member variables no longer appear in the Minibox, but belong to the sandbox. As a general rule, if you think a member variable is also useful for other extension classes, push these member variables higher in the inheritance hierarchy. Use a similar technique to pull down member variables.
Replace Inheritance with delegationTo disassociate and delegate member variables
Right click (Mac computer with CTRL + click) Com.apress.gerber.helloword Package select New? Java Class. Name this new class as patio and inherit from the sandbox:
public class Patio extends Sandbox {
}
After further analysis, we decided that patio was not a sandbox, but more like it had a sandbox. To change their relationship, navigate to refactor? Replace Inheritance with delegation. In the Results dialog box, click on the delegate to generate getter method, as shown in 4-14.
Figure 4-14: de-inheriting and delegating member Variables dialog box
Now your patio class will have a sandbox member variable, as shown in the following code snippet:
public class Patio {
Private final Sandbox msandbox = new Sandbox ();
Public Sandbox Getsandbox () {
return msandbox;
}
}
Encapsulate FieldsPackage Domain
The encapsulation domain is an object-oriented policy that hides class member variables and provides an interface that exposes the Getter/setter method as public by making the access level private. Even when you choose refactor? Encapsulate fields have a lot of options, but refactor? Encapsulate fields similar to code? Generate? Getter and Setter. Open your sandbox class and define a member variable called Mchildren, such as The thick, bright part of the code snippet below. From the main menu, select Refactor? Encapsulate fields.
public class Sandbox {
Private String Mshovel;
private int mchildren;
}
The Results dialog box allows you to choose exactly how to encapsulate these fields and their access levels. The true encapsulation domain will have a private visibility and public access (getter) and change (setter) method. Click on the Refactor button, 4-15, and notice that Android Studio generates all the getters and setters for us in our Sandbox.java class.
Figure 4-15: Encapsulate Domain dialog box
Wrap method return value type of the value wrapper
Wrapping the return value may be useful when you need to return an object instead of a base data type (and of course there are other scenarios where you might want to wrap a return value). Put the cursor on the GetChildren () method and navigate to the refactor? Wrap Method Return Value. Select the Use Existing class option, the Name box is entered Java.lang.Integer, and the wrapper field box is selected as shown in Value,4-16. Now click on the Refactor button and notice that your GetChildren () method returns an integer class instead of the base data type int.
Figure 4-16: Wrapper return Value dialog box
Replace Constructor with Factory Methodreplacing constructors with factory methods
Place the cursor in the sandbox definition box. Press Alt+insert | Cmd+n then chooses to generate a new constructor. Select all member variables as shown in 4-17, and then click OK.
Figure 4-17: Dialog box for selecting a field through the constructor
Place the cursor anywhere in the code snippet Builder as shown below and navigate to refactor? Replace Constructor with Factory Method. The resulting dialog box looks like Figure 4-18. Click Refactor to generate a factory method.
Public Sandbox (String Shovel, int children) {
Mshovel = shovel;
Mchildren = children;
}
Figure 4-18: Dialog box with Factory mode instead of constructor
Notice that the previous constructor has now become private and a new static method returns an instance of the Sandbox class, as shown in the following code snippet. This will be useful if you are creating a singleton class.
public static Sandbox Createsandbox (String shovel, int children) {
return new Sandbox (shovel, children);
}
Convert Anonymous to Inner converting anonymous inner class
Add the following line to the constructor of your sandbox class:
New Thread (New Runnable ()). Start ();
Place the cursor on runnable () and press Alt+enter to invoke the completion code operation. Then select the Implementation method. Select the Run () method and click OK. Your code will look like the following fragment:
New Thread (New Runnable () {
@Override
public void Run () {
Do something
}
}). Start ();
Place your cursor over runnable () and navigate to refactor? Convert Anonymous to Inner. Android Studio recommends myrunnable as the class name, as shown in 4-19. To select the Make class static option, click OK. Notice that you will get a private inner class called myrunnable in the sandbox, which implements the Runnable interface. This example does not do much, however, you may have a chance to use this when delegating the view's behavior.
Figure 4-19: Dialog box for converting anonymous inner classes
SummarySummary
This chapter discusses many of the refactoring operations currently in effect in Android Studio. Refactoring code is a necessary part of programming engineering, and the refactoring tool in Android Studio is one of the best refactoring tools. Android Studio reduces the risk of some operations execution by analyzing reasoning and allowing you to preview the results in the Find tool window before committing. The most important is the refactoring operation refactor? Refactor this dialog box is so valid, this can be ctrl+alt+shift+t by using the shortcut key | Ctrl+t to invoke.
[Learn Android Studio Chinese Course] Chapter fourth: Refactoring Code