Clause 22: declare member variables as private

Source: Internet
Author: User

First, let's take a look at why the member variables should not be public. Then let's take a look at all arguments against the Public member variables that apply to the protected member variables as well. Finally, we can conclude that all member variables should be private.

1. Syntax consistency. If the member variables are not public, all access member variables become functions, so there is no issue of parentheses.

2. Using member functions gives you more precise control over member variables. Therefore, you can design "no access (no function corresponding to this member is written)", "read-only access (const)", and "read/write access ".

3. encapsulation. If you use a function to access a member variable, when you want to replace the Member variable with a certain calculation in the future, the class customers do not know that the internal implementation of the class has changed.

 

Encapsulation of member variables and damage caused by changes in the content of member variablesCodeThe quantity is inversely proportional. The so-called change may be to remove it from the class.

Suppose we have a public member variable, and we have to cancel it. How much code will be destroyed?

All code that uses it will be destroyed, so the public member variables are completely unencapsulated. Suppose it is a protected variable? All subclasses that use it will be destroyed.

 

Remember:

  • Remember to declare the member variables as private. This allows the customer to access data consistency, slightly divided access control, allow constraints to be guaranteed, and provide class authors for full elasticity.
  • Protected is not more encapsulated than public.

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.