Class encapsulation from the perspective of program development.

Source: Internet
Author: User

I remember that when I first switched from C to C ++, I realized that the biggest difference between C and C ++ is from process-oriented to object-oriented. The biggest difference is the encapsulation, inheritance, and Polymorphism of classes.
Inheritance and polymorphism are better understood. The former can inherit the public and protected data and methods of the parent class, and the latter is the reference of the base class pointing to the object of the derived class.
But encapsulation is abstract. I talked to airchain colleagues before. He said it was Code Security. Put member functions and member variables in private to make them invisible (at least in the absence Source code In this way, the variable values in the class can be accidentally modified externally.
At that time, we were all completely confused. At that time, I thought that if we switched to C, we would just need to put the method (equivalent to the public method and variable in the class) that we needed to know externally into the header file (head. h), put the variables and methods (equivalent to the private part) that you don't want to know into the code file (. CPP), so when someone else # include "head. H "is also unable to access the" privacy "code in it. The encapsulation of such classes is impossible.
Later, airchain posted an article titled "this is silly-just one day ago, I found myself having a serious misunderstanding of class encapsulation ."Article (Click here to browse), it tells you that as long as two variables are instantiated in the same class, they can access each other's private variables! That is to say, the benefits of class encapsulation cannot be explained from the perspective of code security.
After the summer vacation Program After development, I found several benefits of class encapsulation. This may explain why C ++ regards encapsulation as one of the three major features of C language improvement.

One of them is to reduce the amount of code rewriting. Let's look at the following example:
We need to write a software for starting the program. We can create a simple name for each program. For example, we name wow for World of Warcraft. In this way, we use a hotkey to call out our program and enter a nickname, you can quickly start one or the corresponding group of programs.
Now let's analyze it. This program requires two data columns. One appname is used to store nicknames and is unique. The second is apppath, which is used to store the program path. This is required. In this way, the simplest program is ready. Let's take a look at the case of no class encapsulation (C # syntax)

// Insert new program
Public   Bool Insertnewapp ( String Newappname, String Apppath)
{
Using (Oledbconnection ODC =   New Oledbconnection (connectstr ))
{
Oledbcommand odcmd = ODC. createcommand ();
Odcmd. commandtext =   String . Format ( " Insert into ultrarun (appname, apppath) values ('{0}', '{1 }') " , Newappname, apppath );
ODC. open ();
If (Odcmd. executenonquery () >   0 )
Return   True ;
Return   False ;
}
}

// When you need to modify the path or name of this program
Public   Bool Updateapp ( String Originappname, String Newappname, String Newapppath)
{
Using (Oledbconnection ODC =   New Oledbconnection (connectstr ))
{
Oledbcommand odcommand = ODC. createcommand ();
Odcommand. commandtext =   String . Format ( " Update ultrarun set appname = '{0}', apppath = '{1}' Where appname = '{2 }' " , Newappname, newapppath, originappname );
ODC. open ();
If (Odcommand. executenonquery () >   0 )
{
ODC. Close ();
Return True;
}
Else
{
ODC. Close ();
Return False;
}
}
}

// When you need to delete this name
Public   Bool Deleteapp ( String Appname)
{
Using (Oledbconnection ODC =   New Oledbconnection (connectstr ))
{
Oledbcommand odcmd = ODC. createcommand ();
Odcmd. commandtext =   String . Format ( " Delete from ultrarun where appname = '{0 }' " , Appname );
ODC. open ();
If (Odcmd. executenonquery () >   0 )
Return   True ;
Return   False ;
}
}

At first glance, there seems to be nothing wrong with it. We used to write C functions, and even most C ++/C # functions are like this. Yes, it seems that there is no difference in the short term. But now the user reports, but these two are not enough. When I set too many nicknames, such as wow and war3, too many names are similar and I don't know. Therefore, add a descrption (description ). Now you have forgotten it. When you add a database, there must be a reload. The user may have no instructions or instructions. Therefore, you need to add an overload parameter to all methods and modify the number of methods. In addition, the number of parameters for each caller must be modified.
So imagine what if we had encapsulated these methods into a class?

Public   Class Appinfo
{

Public   String Appname;

Public   String Apppath;

Public   String Appdescription;
Private Appinfo ()
{
//Null constructor is not allowed
}
Public Appinfo ( String Appname, String Apppath, String Appdescription)
{< br> This . appname = appname;
This . apppath = apppath;
This . appdescription = appdescription;
}

Public Appinfo ( String Appname, String Apppath ): This (Appname, apppath, Null )
{
}

We made a class and provided constructor with two parameters. In this way, the three creation methods are designed at first, and the parameter is a class during modification and deletion. No matter what you want to add in the future, you need to modify the parameters. We only need to change the variables and constructor methods of this class. The caller's Code does not need to be modified, because the parameter is still the class, and this class will automatically call the constructor of three parameters if there is a description during instantiation, you don't have to worry about this, in this way, we can save a lot of effort.

 

On the other hand, let's look at the efficiency of the two programs. No encapsulation, method must be overloaded, and three parameters must be passed. If we use classes for encapsulation, we only need to pass a parameter without overloading. If the former parameter has both the reference type and the value type, it will have both the value transfer and the reference transfer, and the value transfer will re-store the copy of this variable in the stack, such efficiency is really intolerable. The latter is passed by reference. After the transfer, it only saves a 32-bit address on the hosting stack. There is no deep replication problem and the efficiency is relatively high.

This article is only a summary of the history of beginners after learning C-> C ++-> C #. It includes many examples from practice, it is not excluded that there may be comprehension errors or other errors. This article is only for reference. If there is an error in this article or you have a better idea, please leave a message or click "Contact" E-mail me.

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.