Effective Java 13 Minimize the accessibility of classes and members

本文深入探讨了通过限制类和成员的访问级别来优化软件设计,阐述了如何通过控制类和成员的可见性来提升系统开发效率、维护便捷性及性能调优能力。同时,提供了实例说明了如何正确地实现类和成员的访问控制,以减少并发问题并促进代码复用。

Information hiding is important for many reasons, most of which stem from the fact that it decouples the modules that comprise a system, allowing them to be developed, tested, optimized, used, understood, and modified in isolation.

Advantage

  1. Speeds up system development by parallel programming.
  2. Eases the burden of maintenance.
  3. Enables effective performance tuning.
  4. Increases software reuse.
  5. Decreases the risk in building large system.

Principle

1. make each class or member as inaccessible as possible.

Possible access levels for top level classes

Package-private

Public

For members (fields, methods, nested classes, and nested interfaces), there are four possible access levels, listed here in order of increasing accessibility:

• private—The member is accessible only from the top-level class where it is declared.

• package-private—The member is accessible from any class in the package where it is declared. Technically known as default access, this is the access level you get if no access modifier is specified.

• protected—The member is accessible from subclasses of the class where it is declared (subject to a few restrictions [JLS, 6.6.2]) and from any class in the package where it is declared.

• public—The member is accessible from anywhere.

 

2. Instance fields should never be public.

3. Classes with public mutable fields are not thread-safe.

4. It is wrong for a class to have a public static final array field, or an accessor that returns such a field.

a. make the public array private and add a public immutable list:

private static final Thing[] PRIVATE_VALUES = { ... };

public static final List<Thing> VALUES = Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));

b. make the array private and add a public method that returns a copy of a private array:

private static final Thing[] PRIVATE_VALUES = { ... };

public static final Thing[] values() {

return PRIVATE_VALUES.clone();

}

   

   

   

转载于:https://www.cnblogs.com/haokaibo/p/minimize-the-accessibility-of-classes-and-members.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值