使用 Eclipse V3.3 保持代码干净

http://www.ibm.com/developerworks/cn/opensource/os-eclipse-clean/(中文)
http://www.ibm.com/developerworks/opensource/library/os-eclipse-clean/?S_TACT=105AGX52&S_CMP=cn-a-os(英文)

Keep your code clean with Eclipse V3.3

Latest Eclipse offers flexibility in helping you keep your code readable by other developers

developerWorks
Document options
<script type="text/javascript" language="JavaScript"> </script>
Set printer orientation to landscape mode

Print this page

<script type="text/javascript" language="JavaScript"> </script>
Email this page

E-mail this page


Rate this page

Help us improve this content


Level: Introductory

Katrin Limpoeck (limpoeck@de.ibm.com), Software Engineer, IBM
Philipp Tiedt (philipp_tiedt@de.ibm.com), Software Engineer, IBM

03 Jul 2007

Clean, easy-to-read code allows developers who are unfamiliar with a program to understand it quickly and completely, which makes software maintenance more efficient than the alternative. Get an introduction to the new cleanup capabilities in Eclipse V3.3 that allow developers more options for cleanup than earlier versions.
<script type="text/javascript" language="JavaScript"> </script>

Writing clean code helps other developers read, understand, and maintain the code you write. However, not everyone agrees on the definitions of "pretty, "nice," or "clean." Different developers possess different styles and aesthetic sensibilities. Until now, Eclipse formatted imported code in a simple functional manner with few frills. In Eclipse V3.3, these operations are extended to provide a much broader level of cleanup capabilities. Eclipse V3.3 allows you to clean up code, add missing code, and apply a certain coding style. A wizard helps you configure your cleanup settings and store them for later use.

We will discuss the basic concepts of cleanup and give an overview of the tools that help you keep your code squeaky clean.

Manage your cleanup configuration with profiles

A specific cleanup configuration is called a profile. Profiles can be saved so you can give your settings to somebody else or apply settings from earlier projects and other people to your current code. According to your organization's coding conventions, they can be applied to every Eclipse project, so you get the same code style in all development teams.

Eclipse preferences offer management capabilities for profiles. Profiles can be created, edited, and deleted. You can specify the profile used in your workspace globally. When you first open the workspace preferences and navigate to Java > Code Style > Clean Up, you will see the active profile Eclipse [built-in]. This built-in profile is preconfigured and delivered with Eclipse. There are two built-in profiles: Eclipse and Save Participant. These define two minimal cleanup configurations that basically remove unnecessary code. You can see the settings of these built-in profiles by selecting them as the active profile. All details are shown in the details area.


Figure 1. Built-in details
Built-in details

Existing profiles can be used as a template of sorts, which can be extended or customized. Therefore, select an existing profile from the drop-down menu as the active profile and click Edit. Built-in profiles can't be changed. Use them as the basis for your own profile or just apply them on your code as-is.

To create your own profile, click on New. Name your profile and select an existing profile from the drop-down menu for initialization. Deselect Open the edit dialog now and click OK.


Figure 2. New profile
New profile

To share your profile, use the export functionality. To open the profile, click Edit, then Export. Name your profile file, click OK, and it is ready to share.


Figure 3. Exporting profiles
New profile

To apply an external profile from an XML file to your project, you must import it first. Click Import in the main cleanup preferences, select the file, and click OK.



Back to top


Cleanup types

Cleanup settings are divided into five main categories. Each appears in its own tab, which consists of the settings section and the preview section. Preview shows how the settings affect the code immediately. Play around with the settings and watch how the code in the preview changes to get an idea of how each change affects your code. The dialog to edit all these settings pops up after you click Edit in the main cleanup preferences or when you create a new profile and select Open the edit dialog now.

The following discusses what settings are possible, along with their pros and cons. Since many settings are matter of taste, we will not offer recommendations. Note that when you do not select a specific option, your code will remain as you typed it.

Code Style

The first tab deals with coding styles and defines how blocks, expressions, and variable declarations should appear.

Control statements
Select Use blocks in if, while, for, and do statements to define where braces are used. Braces help with code readability. It's easier to see what belongs together when braces are used. It also might help avoid errors when adding another statement that is meant to belong to an if or else condition. On the other hand, too many braces bloat code and may make your code unwieldy.

Select Convert for loops to enhanced to use the for loops notation, which was introduced with Java™ V5.0 to reduce the code. Note that this conversion is not backward-compatible.
Expressions
Select Use parentheses around conditions to define where parentheses are to be used. For parentheses, see the braces discussion above.
Variable declarations
Select Use modifier 'final' where possible to define where the keyword final is to be used. The final modifier does not only declare variables that never can be changed but it is also great to force that private fields are always set. The final modifier is important for performance, robustness, and correctness.

Figure 4. Coding styles
Coding styles

Member Accesses

The second tab lets you define how members of your types should be accessed.

Non static accesses
Select where you want to use the this qualifier for field or method access. The this qualifier helps you quickly see which fields or methods are members of the current class you are coding. It helps you to distinguish fields and local variables that use the same name.
Static accesses
Use the checkboxes to define the settings for qualifying. Static member access can be qualified through the declaring class to better identify which type defines that member. On the other hand, long class names might bloat simple member accesses and make them look unreadable or span several lines of code.

Figure 5. Member Access
Member Access

Unnecessary Code

The third tab allows you to specify settings for removal of unused and unnecessary code.

Unused code
Use the first checkbox to remove unused imports. If you do not use Organize imports or the key combination Strg+Shift+o, this automatic removal of unused imports helps you to keep your project as small as possible without any unused libraries.

Use the second checkbox to remove unused private members. Private members can only be accessed in the holding class. If they are not used, you do not need them. They just produce overhead for the compiler. Removal can be quite effective after restructuring code and having lots of legacy stuff unused. On the other hand, it can be quite dangerous. Imagine you are prototyping new methods that are not used yet, but may be in the future. This cleanup option would remove them if activated, and you might lose important work.
Unnecessary code
Use the first checkbox to remove unnecessary casts. The use of unnecessary casts can result in additional costs at runtime, depending on your compiler.

Use the second checkbox to get rid of unnecessary $NON-NLS$ tags. These tags are only used by Eclipse to identify strings that should not be externalized.

Figure 6. Unnecessary code
Unnecessary code

Missing Code

The fourth tab allows you to add missing code.

Annotations
Define what annotations to add to your code. Since Java V5.0 @Override or @Deprecated annotations help the compiler generate errors when deprecated methods are used or an override marked method fails to correctly override a method in one of the superclasses. Note that these annotations are not backward-compatible.
Potential programming problems
Define this if you want to add serial version IDs. For classes implementing the interface Serializable, we recommend that they have a private static final variable for the serial version UID. This can be generated automatically. It is used to check compatibility during deserialization.

Figure 7. Missing Code
Missing Code

Code Organizing

Last but not least, the fifth tab helps you organize your code.

Formatter
Define if the formatter should be used within code cleaning. Check out the formatter preferences: Preferences > Java > Code Style > Formatter.
Imports
Define if Organize Imports should be used. Check out the organize imports preferences: Preferences > Java > Code Style > Organize Imports.
Members
Define if you want to sort members alphabetically. Sometimes it's nice to have members sorted alphabetically to better navigate in your code. Again, there may be arguments against it. Imagine you structure your code so that methods that call each other are located close together for code navigation. The sort would reorganize them, and they may not be in the wanted order. The outline view offers a nice feature to sort members in the view, but not in the code. The specific settings and how members are sorted can be found in Preferences > Java > Appearance > Members Sort Order.

Figure 8. Code organizing
Code organizing



Back to top


How to apply profiles

Once a cleanup profile is created, there are different ways of applying it to your code. The easiest way is to open the context menu in the Java Editor and select Source > Clean Up.


Figure 9. Open the cleanup wizard
Open the cleanup wizard

This will bring up the cleanup wizard, shown below.


Figure 10. Cleanup wizard
Cleanup wizard

The wizard guides you through the cleanup of the selected sources. The description in the upper left shows how many projects and compilation units will be cleaned up. Usually, you would apply the configured profile to your compilation units. However, it is possible to customize the code clean just before applying it. This may be helpful if you want to check how a certain setting affects the result in your code.

The cleanup wizard can be launched on any Java project, package, or Java file if at least one compilation unit is contained. For example, you can select all your Java projects in the workspace and launch the wizard. Performing the cleanup would affect all compilation units in your workspace that can be refactored with the selected profile.

By default, there is one global cleanup profile for the whole workspace. However, it is possible to enable project-specific cleanup in your project properties. Each project can have its own cleanup profile. To enable this, simply open the project properties and navigate to Java Code Style > Clean Up, as shown below.


Figure 11. Applying profiles
Applying profiles

To preview the result of the cleanup, click Next in the cleanup wizard. The wizard now computes the changes to your code. Depending on the amount of compilation units selected, this might take a while. On the next page, you will be presented with the changes that will be applied.


Figure 12. Previewing results
Previewing results

The tree lists all compilation units that will be affected by the cleanup. You can step into the tree to select different changes of a compilation unit. Selecting a change shows the original source and the refactored source in a compare view. After reviewing the changes, you might not want all of them to be applied. In this case, you can simply uncheck the changes that should not be executed. Clicking Finish will perform the whole cleanup action.



Back to top


Good to know

Some of the cleanup refactoring actions like Convert for loops to enhanced or Add missing annotations are bound to Java code compliance 5.0 or 6.0 and can only be applied if the source file is compiled according to the required Java version. The cleanup wizard allows you to select those refactoring options no matter what Java version is used. So if you wonder why your for loops are not converted or your deprecated methods are not annotated correctly, check the compiler compliance level of the workspace or the project under Preferences > Java > Compiler.

Once you have run the cleanup wizard a few times and your profile is set up correctly, you might not want to click through the wizard every time you clean up. In this case, you can simply disable the wizard in the profiles settings page under Preferences > Java > Code Style > Clean Up.


Figure 13. Hide/show cleanup wizard
Hide/show clean-up wizard

Performing code cleanup on many resources often results in many changes. The wizard allows you to preview those before applying them. However, having hundreds of files affected makes reviewing uncomfortable, especially when you are looking for a certain change in the review. Use the filter option to narrow the list of changes shown in the preview page. Usually, almost every file is affected by a source code formatting action, but not many are affected by the action that adds a missing deprecation annotation. In this case, the filter helps you find those files by filtering out other changes. The filter is in the upper-right corner of the preview page.


Figure 14. Applying filters
Applying filters

Cleanup actions can not only be performed by hand but also during the save action of a Java file. To enable this feature, go to Window > Preferences > Java > Editor > Save Actions and select additional actions. Configure the cleanup actions as described above, and they will be performed on every save of a Java file. Please note that those actions can be expensive and slow down your workbench. Also, you might get confused that the code you just wrote looks different after the save if you don't have the cleanup in mind anymore.


Figure 15. Performing cleanup on save
Performing clean-up on save



Back to top


And now?

Share this...

digg Digg this story
del.icio.us Post to del.icio.us

Cleanup does not fix conceptual or functional problems — at least not with the current version of Eclipse. But it can save a lot of work by presenting code in a clear manner. The actions that come with the wizard are rich, and cover many points in coding styles and conventions. Organizations must decide on their own style and convention, and, therefore, it would be helpful to have the wizard being extensible, which is not the case in Eclipse V3.3. The cleanup concept not only make sense in the Java world but also could be useful for other languages like C/C++, PHP, Python, Perl, etc. It will be interesting to see how this feature is adopted by the community and the directions it will evolve.



Resources

Learn

Get products and technologies

Discuss
  • The Eclipse Platform newsgroups should be your first stop to discuss questions regarding Eclipse. (Selecting this will launch your default Usenet news reader application and open eclipse.platform.)

  • The Eclipse newsgroups has many resources for people interested in using and extending Eclipse.

  • Participate in developerWorks blogs and get involved in the developerWorks community.



About the authors

Katrin Limpoeck

Katrin Limpoeck is a software engineer in IBM's Development Lab in Boeblingen Germany. She holds a master's degree in computer science from the University of Passau. Before joining IBM Germany in 2006, she participated in several software engineering projects. Her areas of interest are business process management, Service-Oriented Architecture, Java development, and Eclipse.


Philipp Tiedt is a software engineer in IBM's Development Lab in Boeblingen Germany. He holds a bachelor's degree in computer science from the Open University. Before joining IBM Germany in 2004, he completed his bachelor's study at IBM's T.J. Watson Research Center in Hawthorne, N.Y. His areas of interest are Eclipse, user interface design, Java technology, and service-oriented architecture.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值