Effective Item-minimizes accessibility

Source: Internet
Author: User

Whether the module is well designed, an important factor is whether the external module hides the internal data and the implementation details.
A well-designed module hides implementation details and isolates the API from its implementation.
The modules communicate with each other through the API, which is not visible to the internal working conditions.
That is, encapsulation (encapsulation)--one of the basic principles of software design.


Why encapsulation?
The coupling between the modules can be effectively contacted by encapsulation, so that the modules can be independently developed, tested, optimized, used, understood and modified.
That

    • can increase development efficiency, modules can be developed in parallel.
    • Encapsulation reduces the burden of maintenance and can be optimized more efficiently without compromising the correctness of other modules.
    • It improves the reusability of the software, and the modules can be used in other environments as well.

(PS: Recall that I used to write a website in PHP without these concepts do not affect development work.) I felt nothing at the time, because I wrote it by myself, and then I did not expand it, so I didn't have any experience. )


Encapsulation can be guaranteed through access control.
The accessibility of an entity is determined by both the location of the entity declaration and the access modifier.
It is recommended that each class or member be not accessed by the outside world as much as possible .


There are only two levels of access for top-level classes and Interfaces: Package-level private and public .
Smaller accessibility represents smaller compatibility, which can be easily modified in later releases.
If it is public, you need to always consider the behavior of the customer. (PS: If a top-level class is only used inside a class, it can be declared as a private static inner class.) )
For example, such a class would not change the presentation in a later version, and could not include any constraints:

class Point {    public double x;    public double y;}


Thus, as is customary in many people, public access methods are used instead of public field to ensure the flexibility of the data within the class: class Point {private double X; private double y;

    public Point(double x, double y) {        this.x = x;        this.y = y;    }    public double getX() {        return x;    }    public double getY() {        return y;    }    public void setX(double x) {        this.x = x;    }    public void setY(double y) {        this.y = y;    }}

(PS: Of course, some common classes do not follow this rule such as Java.awt.Point, Java.awt.Dimension.
But the original authors also made it clear that these classes are not worth emulating. )

If a field can be public only, and it is allowed to be declared final, the damage can be less.
We can still access the field through the public access method.
Instead of using a public setter, you can join the constraint by using a constructor:

public final class Time {    private static final int HOURS_PER_DAY = 24;    private static final int MINUTES_PER_HOUR = 60;    public final int hour;    public final int minute;    public Time(int hour, int minute) {        if (hour < 0 || hour >= HOURS_PER_DAY)            throw new IllegalArgumentException("Hour: " + hour);        if (minute < 0 || minute >= MINUTES_PER_HOUR)            throw new IllegalArgumentException("Min: " + minute);        this.hour = hour;        this.minute = minute;    }    // Remainder omitted}


There are 4 levels of access for members (Field,method, nested classes, nested interfaces):

    • Private
    • Package-private (default)
    • Protected
    • Public

When a class's public API is designed, we make all the members private.
It then discovers that another class within the same package needs access to the member, and then modifies the access level. If this happens often, you should check whether the design is reasonable.
Although the package and private level members are part of the class implementation, the exported APIs are not affected.
However, this class implements the serializable when it is another matter.
If you use the protected adornment, you need to be aware that this member is part of the exported API.


Also, try not to set the instance field to public. If a field is not final or a final field that points to a mutable object, the public access level destroys the immutability of that field, which is not an internal data representation and is not thread-safe.
Of course, this is the same for arrays of length!=0.


If you need to declare an array as public, you can try the following:

private static final Thing[] PRIVATE_VALUES = {...};public static final List<Thing> VALUES =     Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));


Or you can use clone to copy an array at a time:

private static final Thing[] PRIVATE_VALUES = {...};public static final Thing[] values(){    return PRIVATE_VALUES.clone();}

Effective Item-minimizes accessibility

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.