zoukankan      html  css  js  c++  java
  • 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();

    }

       

       

       

    作者:小郝
    出处:http://www.cnblogs.com/haokaibo/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    域名解析成功但ping不通解决方案
    PHP如何通过rabbitMQ死信队列实现业务的延时/定时操作
    短视频自导自演,分镜脚本如何设计
    如何在uni-app中使用fingerprint2实现游客设备标识
    以PHP门面模式实现简单的邮件发送
    搜索接口优化方案——幂集分词表
    CUMTCTF'2020 未完成 wp
    CUMTCTF'2020 已做wp
    Sqli-labs 1-10
    ETCD组件在grpc中的实践
  • 原文地址:https://www.cnblogs.com/haokaibo/p/minimize-the-accessibility-of-classes-and-members.html
Copyright © 2011-2022 走看看