Introduce Constant

The new code editor allows you to do away with magic numbers passed as parameters, in conditional statements, or lurking elsewhere in your code. It allows you to at least push these numbers into constant variables. That way if the number changes, you only need to change the constant and not hope you find all occurrences of the magic number in your code. (Of course, it would be even better if you externalized the value so you did not have to recompile your code to change a number.)

Let’s look at an example. Figure 9.10 shows code for a discount rule on an invoice. The rule states that if the order is greater than $100, then a 10% discount should be applied. However, both 100 and .10 are represented as magic numbers in the code. Selecting the value in the editor and then invoking the light bulb menu (Ctrl+.) presents you with options to introduce a constant instead of these numbers. Notice that the resulting changes are previewed right in the IDE. The example shown in Figure 9.10 will create a new variable (V) and assign it the constant value of 100.

Image

FIGURE 9.10 Convert a “magic number” in your code to a constant.

You apply the change by clicking on the menu item representing the version of the refactor you want to execute. This makes the change but also brings up the small refactor menu to allow you to apply the change to strings and comments (see Figure 9.11). Notice, too, in Figure 9.10 that you can click on Preview Changes directly from the light bulb foldout menu. Figure 9.11 shows the change being made. Notice as you name the constant the references are updated also.

Image

FIGURE 9.11 Executing an Introduce constant refactor inside the IDE.

The Introduce constant refactor gives you a few options (see Figure 9.10). The first option, Introduce Constant For, creates a standard constant scoped at the class level. The Introduce Local Constant For option creates a constant inside your method (or whatever type of code you are referencing in the editor). The options that include All Occurrences are going to search outside the selected magic number and find other uses of that number (and replace them with the constant variable).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset