在现有代码中为常量创建静态导入的简单方法? [英] A simple way to create static imports for constants in existing code?

查看:121
本文介绍了在现有代码中为常量创建静态导入的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Foo中有一个常量的BAR,我将在C类中使用,我必须写

  Object o = Foo.BAR +...; 

我可以在Eclipse中使用Ctrl-Shift-M(用BAR上的光标)创建一个静态导入为:

  import static Foo.BAR; 

对象o = BAR +....;

我目前正在更新遗留代码,其中数千种我想转换为静态导入。 Ctrl-Shift-O / Organize导入不会这样做。有没有一个我错过的技巧?






编辑:其实我最喜欢的是告诉Eclipse我想让Ctrl-Shift-M在这个特定的类中的所有实例上做它的魔术,而不是我的光标所在的单个实例。 (这是传统代码,所以这实际上改善了可读性:))






编辑:我发现IntelliJ建议这样做

解决方案

一个注意事项:过度使用静态导入实际上可以使您的代码不易读取(imho),特别是如果常量名称没有明确指出它所属的类或枚举。您还可以从不同的类/枚举中获取不同的名称,声音类似,甚至具有相同的名称。



所以你强迫读者做的是希望他的IDE会告诉他课程(通过,说,一个工具提示),或者他们必须导航到它来找出它是什么。打印输出和代码段变得不那么重要。



由于这些原因,我很少使用静态导入。


If I have a constant BAR in Foo, which I will use in a class C I'll have to write

Object o = Foo.BAR + "...";

which I can use Ctrl-Shift-M in Eclipse (with the cursor on BAR) to create a static import for like:

import static Foo.BAR;

Object o = BAR + "....";

I am current updating legacy code with literaly thousands of these I'd like to convert to static imports. Ctrl-Shift-O / Organize imports does not do it. Is there a trick I've missed?


EDIT: Actually, what I would prefer is a way to tell Eclipse that I want to have Ctrl-Shift-M do its magic on ALL instances in this particular class instead of just the single instance I have the cursor placed at. (It is legacy code so this actually IMPROVES readability :) )


EDIT: I've found that IntelliJ suggest doing this.

解决方案

One cautionary note: excessive use of static imports can actually make your code less readable (imho), particularly if the constant name doesn't clearly indicate the class or enum from which it belongs. You can also get constant names from different classes/enums that sound similar or even have the same name.

So what you're forcing the reader to do is hope his IDE will tell him the class (via, say, a tool tip) or they have to navigate to it to find out what it is. Printouts and code snippets become that much less reeadable.

Honestly I use static imports extremely rarely for these reasons.

这篇关于在现有代码中为常量创建静态导入的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆