Do you use the default (package) visibility in Jav

2020-07-13 12:51发布

Default visibility in java means only other classes in the same java package can access it. I certainly see the use of it, and have used it in several occasions.

On the other hand, 90% of the default visibility I encounter is simply from a developer that forgot to add any visibility keyword.

So, on the one hand, there's legitimate uses, on the other, it often masks bad code. What do you do in your development teams?

3条回答
够拽才男人
2楼-- · 2020-07-13 13:33

If I specifically want package access I put /* package */ prior to the definition of the method/variable etc. to ensure people know I actually meant that, and wasn't being lazy. I rarely use it though.

查看更多
小情绪 Triste *
3楼-- · 2020-07-13 13:47

I generally try to get everyone to start with the most limited scope and only start to expand outward if we see that it's necessary in the design. Occasionally the decision to move from private to package-private is also driven by our need to write tests without having to go down the route of using a mocking framework (see Powermock).

To add to this, we follow the same mentality on mutability. Everything starts out as final and only as we see the need to modify state do we remove it.

查看更多
Ridiculous、
4楼-- · 2020-07-13 13:49

I encourage people to use private which I would have preferred to be the default.

Form time to time, I run a code analysis which reduces the access modifiers to only what is needed.

查看更多
登录 后发表回答