Use eclipse v3.3 to keep the code clean

Source: Internet
Author: User
Tags ibm developerworks
Use eclipse v3.3 to keep the code clean

Use the flexibility provided by the latest version of eclipse to make your code readable for other developers.

Level: elementary

Katrin limpoeck (limpoeck@de.ibm.com), software engineer, IBM
Philip tiedt (philipp_tiedt@de.ibm.com), software engineer, IBM

July 30, 2007

The clean and easy-to-read Code allows developers who are not familiar with the program to quickly and completely understand the program, making software maintenance more effective than other methods. Learn about the new cleanup function in eclipse v3.3. Eclipse v3.3 provides more options for developers than earlier versions.

Writing a clean code helps other developers read, understand, and maintain your written code. However, not everyone agrees with definitions such as "beautiful", "precise", or "clean. Different developers have different styles and aesthetic tastes. So far, eclipse has set the format of the imported code in a simple way through a few modifiers. These operations are extended in eclipse v3.3 to provide a broader cleanup function level. Eclipse v3.3 allows you to clear code, add missing code, and apply a certain encoding style. The Wizard will help you configure cleanup settings and store them for later use.

We will discuss the basic concepts of cleanup and provide an overview of tools that help keep code clean.

Use configuration file management to clear configurations

A specific cleanup configuration is calledConfiguration File. The configuration file can be saved, so that you can provide the settings to others or apply the settings from earlier projects and others to the current code. According to the organization's coding conventions, the configuration file can be applied to all eclipse projects so that the same code style can be obtained from all development teams.

Eclipse preferences provide management functions for configuration files. Configuration files can be created, edited, and deleted. You can specify the configuration file that is globally used in the workspace. When you first open the workspace preferences and browseJava> code style> clean upYou will see the Active configuration file eclipse [built-in]. This built-in configuration file has been pre-configured and delivered along with eclipse. There are two built-in configuration files: Eclipse and save particle ant. These two configuration files define two minimal cleanup configurations, which can basically Delete unnecessary code. You can view the settings of these built-in configuration files by setting them as active configuration files. All details are shown in the details area.

Figure 1. built-in details

Existing configuration files can be used as various templates and can be expanded and customized. Therefore, select an existing configuration file from the drop-down menu as the active configuration file and clickEdit. The built-in configuration file cannot be changed. You can use the built-in configuration file as the basis for your own configuration file or simply apply the built-in configuration file to the Code as is.

To create your own configuration file, clickNew. Name the configuration file and select an existing configuration file from the drop-down menu for initialization. DeselectOpen the edit dialog nowAnd clickOK.

Figure 2. Create a configuration file

To share the configuration file, use the export function. To open the configuration file, clickEditAnd then clickExport. Name the configuration file, and then clickOKThen you can share the configuration file.

Figure 3. Export the configuration file

To apply the external configuration in the XML file to the project, you must first import it. ClickImport, Select a file, and then clickOK.



Back to Top

Cleanup type

The cleanup settings are divided into five main categories. Each category is displayed on the corresponding tab, which consists of the Setting part and the preview part. Preview is used to immediately display the impact of settings on the code. Use these settings and observe the changes in the Code in the preview to see how each change affects your code. When you clickEdit, Or selectOpen the edit dialog nowTo edit all these settings.

The following describes available settings and their advantages and disadvantages. Because many settings may have different styles, no recommendations are provided. Note: If you do not select a specific option, your code will remain as you type.

Code style

The first tab is used to process the encoding style and define how the block, expression, and variable declaration should be displayed.

Control statements
Select use blocks in if, while, for, And doStatements can define the position where braces are used. Braces help improve code readability. When braces are used, it is easier to see which content belongs to the same unit. Add ifOr elseWhen another statement of the condition, it can also help avoid errors. On the other hand, too many braces will make the code bloated and may make the code difficult to handle.

SelectConvert for loops to enhancedThe for loop symbol is used, which is introduced by Java V5.0 to reduce code. Note that this conversion is not backward compatible.

Expressions
Select Use parentheses around ConditionsYou can define the position where parentheses are used. For parentheses, refer to the above discussion about braces.
Variable declarations
Select Use modifier 'final' where possibleCustomizable usage finalKeyword location. finalModifiers can be used not only to declare variables that cannot be changed, but also to forcibly set the excellent choice of private fields forever. finalModifiers are critical to performance, robustness, and correctness.

Figure 4. Encoding Style

Member accesses

The second Tab allows you to define how members of the access type should be accessed.

Non static accesses
Need to use thisSelect this option when using a qualified word to access a field or method. thisThe qualifier helps you quickly check which fields or methods are members of the current class being compiled. It helps you distinguish between fields with the same name and local variables.
Static accesses
Use the check box to define the restriction settings. You can restrict access to static members by declaring classes to better identify and define the types of members. On the other hand, long class names may make simple member access bloated and make member access look unreadable or span multiple lines of code.

Figure 5. member access

Unnecessary code

The third Tab allows you to specify settings for deleting unused code and redundant code.

Unused code
Use the first check box to delete unused imports. If you do not use Organize importsOr Strg + Shift + OKey combination, so that automatic deletion of unused imports will help you keep the project as small as possible without any unused libraries.

Use the second check box to delete unused private members. Private Members can only be accessed in the SAVE class. If you do not use private members, you do not need them. Private Members only increase compiler overhead. After refactoring the code, if you have a large number of unused legacy code, the deletion will be very efficient. On the other hand, it is very dangerous to do so. Assume that you are designing a prototype for a new method that is not yet used but may be used in the future. This cleanup option deletes these methods if they are in the activation status and may miss important work.

Unnecessary code
Use the first check box to delete unnecessary code. The existence of redundant code will lead to additional runtime overhead, depending on the compiler you are using.

Use the second check box to remove unnecessary$NON-NLS$Mark. These tags are only used by eclipse to identify strings that should not be specific.

Figure 6. redundant code

Missing code

The fourth Tab allows you to add missing code.

Annotations
Defines the comments to be added to the Code. Java V5.0 @OverrideOr @DeprecatedAnnotations will help the compiler generate errors. Note that these annotations do not have backward compatibility.
Potential Programming Problems
This setting is defined if you need to add a sequence version ID. For implementation SerializableAPI class. We recommend that you use the Private Static final variable to define a sequential version uid. This variable can be automatically generated. It is used to check compatibility during deserialization.

Figure 7. Missing code

Code organizing

Although the fifth tab is at the end, its importance cannot be ignored. It is used to help you organize code.

Formatter
Defines whether format programs should be used in code cleanup. Query formatting program preferences: Preferences> JAVA> code style> formatter.
Imports
Define whether organize imports should be used. View organization import preferences: Preferences> JAVA> code style> organize imports.
Members
Determine whether to classify members in alphabetical order. Sometimes, it is better to classify members in alphabetical order to better browse the code. However, some may oppose this. Assume that you organize your code so that the methods called by each other are placed together to facilitate code browsing. Sorting may reorganize these methods, and they may not be in the desired order. The overview view provides an excellent feature for sorting members in the view, but cannot sort members in the code. The specific configuration and sorting method for members can be found in Preferences> JAVA> appearance> Members sort order.

Figure 8. Code Organization



Back to Top

How to apply a configuration file

After creating a configuration file, you can apply it to the Code in multiple ways. The simplest way is to open the context menu in the Java editor and selectSource> clean up.

Figure 9. Open the Cleanup Wizard

This operation will open the cleaning wizard, as shown below:

Figure 10. Cleaning wizard

The Wizard will guide you through the process of cleaning the selected source code. The upper-left description shows the number of projects to be cleaned up and the number of compilation units. Generally, we apply the configured configuration file to the compilation unit. However, you can customize the application code before it is cleared. This may be helpful if you need to view the results of a setting that affects the code.

As long as any Java project, software package, or Java file contains at least one compilation unit, the Cleanup Wizard can be started in it. For example, you can select all Java projects in the workspace and start the wizard. Cleaning affects all compilation units that can be reconstructed using the selected configuration file in the workspace.

By default, there is a global cleanup configuration file for the entire workspace. However, you can also enable project-specific cleanup in the project properties. Each project can have its own configuration file. To enable this cleanup operation, you only need to open the project properties and browseJava code style> clean up, As shown below:

Figure 11. Application configuration file

To preview the cleaning result, clickNext. The wizard calculates the number of code changes. Depending on the number of compilation units selected, this process may take some time. The next page shows the changes to be applied.

Figure 12. Preview results

This tree lists all the compilation units affected by cleanup. You can go to the tree to select different changes to the compilation unit. Select change to display the initial source code and reconstructed source code in the comparison view. After you view the changes, you may not want to apply all the changes. In this case, you can simply deselect unnecessary changes. ClickFinishThe entire cleanup operation will be performed.



Back to Top

Notes

SuchConvert for loops to enhancedOrAdd missing annotationsSome such cleaning and refactoring operations are bound to Java code compliance 5.0 or 6.0, and can be applied only when the source code is compiled according to the required Java version. The Cleanup Wizard allows you to select the refactoring options, regardless of which Java version is used. So if you want to know that there is no conversionforCycle or failure to correctly comment out the reasons for disapproval of the method, please goPreferences> JAVA> CompilerView the compiler compliance level of the workspace or project.

After you run the Cleanup Wizard multiple times and the configuration file has been correctly set, you may not want to click it multiple times in the wizard each time you perform the cleanup operation. In this case, you only needPreferences> JAVA> code style> clean upTo disable the wizard.

Figure 13. Hide/show Cleanup Wizard

Executing code cleanup on various resources usually results in many changes. The wizard allows you to preview the changes before the application. However, previewing is inconvenient if hundreds of files are affected, especially when you need to find a change during previewing. You can use the filter option to narrow down the changes list displayed on the preview page. Generally, almost all files are affected by source code format operations, but few files that do not approve of comments are added. In this case, the filter filters other changes to help you find those files. The filter is located in the upper-right corner of the preview page.

Figure 14. Application Filter

The cleanup operation can be performed manually and during the saving operation of java files. To enable this function, goWindow> preferences> JAVA> editor> SAVE actionsAnd select the additional operation. Follow the preceding steps to clean up the java files. Note that performing those operations sometimes increases overhead and reduces the speed of the workbench. At the same time, if you do not want to clean up, you may find it confusing why the code is not the same after saving the code you just wrote.

Figure 15. Clean up when saving



Back to Top

Conclusion

Share this article ......

Submit this article to Digg
Release to Del. icio. us
Submit to Slashdot!

Cleanup is a very practical tool that makes your code look more comfortable and easy for others to understand quickly. It may even make the code more robust. However, the encoding styles can be different. For example, in the past, programmers who used to avoid using too many quotation marks do not need to use code blocks wherever possible, because the Cleanup Wizard provides this operation.

Cleaning cannot solve conceptual or functional problems-at least the current version of eclipse cannot be used. However, explicit Code display saves a lot of effort. The wizard provides a wide range of operations and covers multiple key points of encoding styles and conventions. Each organization must determine its own style and conventions. Therefore, it is very helpful to extend the wizard, which is not implemented in eclipse v3.3. Cleaning is not only meaningful in the Java World, but also useful in other languages such as C/C ++, PHP, Python, and Perl. How will the Community adopt this feature? What is its development direction? I think these will be very interesting.

References

Learning

  • For more information, see the original article on the developerworks global site.

  • Refer to the "Eclipse recommended books list ".
  • New eclipse users should check the Eclipse project resources for beginners.
  • Refer to the Eclipse project resource extension eclipse tips on IBM developerworks.
  • To listen to interesting interviews and discussions with software developers, visit the developerworks podcast.
  • For more information about the eclipse platform, see "getting started with eclipse platform ".
  • Stay tuned to technical events and network broadcasts on developerworks.
  • View the free developerworks on demand demo and learn about IBM and open-source technologies and product features.
  • Check out recent seminars, trade exhibitions, network broadcasts, and other activities for IBM open source code developers to be held globally.
  • Visit the open source code area on developerworks for a wide range of how-to information, tools, and project updates to help you develop with open source technology and use it with IBM products.

Obtain products and technologies

  • Download the latest eclipse technology from IBM alphaWorks.

  • Download eclipse platform and other projects from eclipse Foundation.
  • Download the IBM product evaluation version and start using application development tools and middleware Products for DB2, Lotus, rational, Tivoli and websphere.
  • Use IBM trial software to improve your next development project, which can be obtained by downloading or from a DVD.

Discussion

  • The eclipse platform newsgroup should be the first stop to discuss eclipse issues (selecting this link will start the default Usenet news reader application and open eclipse. platform ).

  • There are many references in the eclipse news group for those interested in using and extending eclipse.
  • Join developerworks blogs and join the developerworks community.

Author Profile

Katrin limpoeck is a software engineer at the IBM development lab in boeblingen, Germany. She has a master's degree in computer science from Passau. Before joining IBM Germany in 2006, she joined multiple software engineering projects. Areas of interest include business process management, service-oriented architecture, Java Development, and eclipse.

Philip tiedt is a software engineer at the IBM development lab in boeblingen, Germany. He earned a bachelor's degree in computer science from Open University. Before joining IBM in Germany in 2004, he completed his graduation project at IBM t. J. Watson Research Center in Hawthorne, New York. He is interested in eclipse, user interface design, Java technology, and service-oriented architecture.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.