Java为啥不建议用通配符_为什么在Java导入语句中使用通配符不好?

使用带有Java导入语句的通配符并不错。

在Clean Code中,Robert C. Martin实际上建议使用它们以避免长时间导入列表。

这是建议:

J1: Avoid Long Import Lists by Using

Wildcards

If you use two or more classes from a

package, then import the whole package

with

import package.*;

Long lists of imports are daunting to

the reader. We don’t want to clutter

up the tops of our modules with 80

lines of imports. Rather we want the

imports to be a concise statement

about which packages we collaborate

with.

Specific imports are hard

dependencies, whereas wildcard imports

are not. If you specifically import a

class, then that class must exist. But

if you import a package with a

wildcard, no particular classes need

to exist. The import statement simply

adds the package to the search path

when hunting for names. So no true

dependency is created by such imports,

and they therefore serve to keep our

modules less coupled.

There are times when the long list of

specific imports can be useful. For

example, if you are dealing with

legacy code and you want to find out

what classes you need to build mocks

and stubs for, you can walk down the

list of specific imports to find out

the true qualified names of all those

classes and then put the appropriate

stubs in place. However, this use for

specific imports is very rare.

Furthermore, most modern IDEs will

allow you to convert the wildcarded

imports to a list of specific imports

with a single command. So even in the

legacy case it’s better to import

wildcards.

Wildcard imports can sometimes cause

name conflicts and ambiguities. Two

classes with the same name, but in

different packages, will need to be

specifically imported, or at least

specifically qualified when used. This

can be a nuisance but is rare enough

that using wildcard imports is still

generally better than specific

imports.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值