Design principles for Java classes

Source: Internet
Author: User
Tags modifier

1, cohesion

A class should describe a single entity, and all class operations should logically fit together to support a coherent goal. For example: Students and faculty belong to different entities, and two classes should be defined.

2. Consistency

To follow a certain design style and naming habits. Select the name of the information for the class, method, and data field. The popular style is to put the data declaration before the construction method and put the construction method before the method.

It is not a good habit to choose a name that is consistent and to choose a different name for a similar operation.

If you do not want the user to create an object for the class, you can declare a private construction method in the class.

3, encapsulation of

Hides its data field with the private modifier to avoid direct user access. If you want to make the data field readable, you can use the Get method, or you can use the Set method if you want the data field to be updatable.

4. Clarity

Class should have a very clear contract that is easy to interpret and understand.

Methods should be defined intuitively without confusion.

You should not declare a data field from another data domain.

5. Use the class name to refer to static variables and methods.

6. Do not initialize the static data field directly from the constructor by passing parameters. It is best to use static set methods to change the static data field.

7, class modifier private(can only be accessed in this class),default (can only be accessed in the same package), protected(could be accessed by classes and subclasses in the same package), public (classes in different packages can also be accessed). Subclasses can only extend accessibility in the parent class, not the accessibility of the parent class.

8. Final indicates that a class is the ultimate and cannot be a parent class. Similarly, an ultimate method cannot be overridden by its subclasses.

Design principles for Java classes

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.