Object-oriented and protected

Source: Internet
Author: User
Today, I saw an article written by my friend wayfarer about protected's "protection". After reading this article, I want to share some of my thoughts with you. If you don't give up on it, please read it.

What you think
 
-- Target audience


Speaking of the word protected, I will inevitably think of an object-oriented concept. So what is object-oriented? In fact, I personally think that the concept of Object-oriented has been evolving and changing. Today, the word object-oriented may make it more appropriate to be called abstract-oriented. When we first established the object-oriented concept, we probably didn't know exactly what the creator was. To understand what object-oriented (programming, or design) is, you may have to look at the past software.CodeWhat is it.

I. BC
Software development is basically process-oriented in the past 10 or more decades. Process-oriented core content includes two items: control flow and data flow. In this period, the greatest development estimation in the software industry is data structure andAlgorithmThe two "subjects" correspond to two "streams" respectively ". In process-oriented software code, the execution subject is a process or function. A process represents an action. The action object (which is not an object-oriented object) is some data. The data may be obtained through parameters or through global variables, there are also some constants or predefined values. If we think about it carefully, we will find that this is a "Dynamic Object" structure system, for example, the famous "line (x1, Y1)-(X2, Y2)" in basic )", translating it into natural language is "drawing a straight line (x1, Y1) to (X2, Y2 ". There are many similar examples, such as "printf (" % s \ r \ n "," Hello world! ");".

But where is the subject?

Ii. Genesis
The process-oriented Code does not highlight a subject. In many cases, this subject does not exist. In the example above, the subject is a screen. But what if we need to draw a straight line into the printer? (Or print a "Hello world ".) In the process-oriented code, we have to write a printline function by ourselves. (Fprintf is something in the file written in C language .) If we want to draw a straight line to the remote device, we need to write a remoteline. If ...... If you do not need to talk about it, you will also find it troublesome. People begin to think about this question: Can I write the subject clearly? Can we do less repetitive work? Then we came up with the object-oriented things. In the world where object-oriented is a "subject and object" structure, most things have a subject, such as the familiar "G. drawline (pen, pt1, pt2); ", because we have a" subject ", we can make different things do similar things in a similar way. If we just change g to H, we only solve the problem of "painting in this window" and "painting in that window". If we want him to draw in other types of space, we also need to allow the subject types to be different. However, we need to solve more problems by having the same concept. For example, the G of the printer and the G of the screen can be painted. Therefore, we have concepts such as inheritance and encapsulation. Is this all about object-oriented?

Iii. Reform and Opening Up
With the advent of the object-oriented concept, spring breeze bathed in the earth. As God says, there is light, so there is light. God said that there would be a poisonous snake, so there would be a poisonous snake. God said that there would be an apple, so there would be an apple, as a result, Adam and Eve ate the apple created by God and were "punished" by God ". I really don't understand, since God does not want Adam and Eve to eat this apple, why do they need to create such a thing? In fact, God certainly didn't want them to "eat" the apple. The apple was actually created to produce romantic love and the touching story of the next millennium. If you think of this apple as food, then what you see next is the painful punishment. If you see a touching story behind your scenes, the sweet romance and other beautiful words will fill your brain.

The same is true for Object-Oriented systems. Its core significance is not what you encapsulate things, but what is inherited, the most important thing is that he allows us to construct a software in an abstract way. For example, when we write code:

Stream. Write (buff, 4, Buff. Length-4 );
Or
Hashbuff = hasher. computehash (buff );

Do we need to care about what stream is and what algorithm is used by hasher? If we use the same stream object and hasher object for operations on the corresponding items, should the tasks be completed correctly? It should be done correctly, because this is what we expect. If we want to design a stream, should we consider how to design this class from this perspective? Should we be more abstract if we define this stream variable? Consider such a function:
Void dosomething (filestream stream, md5cryptoserviceprovider hasher, byte [] buff ){...}

If written in the following form, it will be more flexible and more in line with the true meaning of object-oriented (Abstract-oriented:
Void dosomething (Stream stream, hashalgorithm hasher, byte [] buff ){...}

In other words, all encapsulation, inheritance, and interfaces actually exist to provide abstract capabilities. If we use protected as a secret to protect the existence of "some methods", it would be a big mistake. Protection of these secrets should strictly be the responsibility of cryptography, rather than the responsibility of object-oriented.

Iv. Review history
The core of object-oriented is abstract, but we can see that the actual development process is not so. In the past, we had too many incorrect concepts. For example, the object-oriented technology makes it too easy for us to think that the core of this technology is object-oriented. Therefore, we often write an object-orientedProgramExcessive object flooding, inheritance flooding, and encapsulation of unknown content. Many developers, including me, once thought that the so-called object-oriented approach is to abstract some elements into objects, encapsulate them, and then derive everything from a base class. For example, there is a base class called an object, which derives from the active and dead objects, and derived from bacteria, viruses, plants, and animals. Animals contain monkeys, chickens, dogs, pigs, and people, there is Zhang sanli, Si Wang, er Ma Zi (and a baby ).
Yes, of course, object-oriented has to include this, but this is not all, not the root. The root cause is that when we write something, we do not need to care about what the specific object is, but only need to know at least what it should be. For example, in the previous example, dosomething only needs to know that stream is a stream, and hasher is a hash algorithm provider. As for the specific stream and hash algorithms provided, it should not be our concern, but the users who use this code are concerned. In this way, when designing the functions we are concerned about, we do not need to consider too many, too specific, and constantly changing issues.
Think about it, have we really understood the core of object-oriented?

V. What is encapsulation protected?
Object-oriented encapsulation does not protect your secrets, but prevents you from being used incorrectly to clearly define the boundaries of the problem. In terms of the term "protection", it is further said that it is not to authorize a user who uses the object (hereinafter referred to as a user) to use a member, instead, it authorizes the designers who extend the class (hereinafter referred to as designers) to extend the problem area. Now let's look back at the example written by wayfarer:

Class Base
{
Protected   Void Print ()
{
Console. Write ("This is protected method in base class!");
}
}

Class Derived: Base
{
Public   New   Void Print ()
{
Base. Print ();
}
} Class Otherclass
{

[Stathread]
Static   Void Main ( String [] ARGs)
{
Derived d= NewDerived ();
D. Print ();
Console. Readline ();
}
}

This example is indeed very confusing and I have been troubled by such problems. Before solving this problem, we must first clarify the following two problems:
What is protected? What is new?

Protected is a good answer. It indicates that this member is allowed to be used in a derived class, but it is not allowed to be directly used by user code that uses this class object. In fact, it is limited authorization to the design personnel and denied authorization to the user.
New is not hard to answer. For example, it is designed to create an overwrite illusion without override. If you think so, it will fall into the vortex of illusion. In fact, the role of new is not a trick, so that you can create a variety of illusion, or attempt to bypass some use and design authorization. The role of new is only to solve a naming conflict problem. That is to say, the members specified by new are actually irrelevant to the members with the same name as the base class, i'm sorry, but I have to declare that this print is not another print. If you try to use new to create the trick illusion, you will eventually miss your front teeth. Before I give an example of "hitting your front teeth", please allow me to give a scenario where the new keyword is correctly used.

I wonder if you have actually studied interfaces in. NET Framework? If you have studied it, the following questions should not be very difficult to answer.

Public   Interface Ifoo
{
BoolBubble ();
}

Public   Class Boo
{
Public VoidBubble ()
{
}
}

Public   Class Foo: Boo, ifoo
{< br> Public bool bubble ()
{< BR >}
}

The above code generates a warning on the bubble function of Foo, but it can still be compiled. Why can it be compiled? This issue is left to the readers themselves. There are two ways to solve this warning: one is to explicitly implement the interface ifoo; but if I do not want to implement this interface explicitly, then, you can only add a new modifier in front of the bubble function of Foo to tell the compiler that they are in conflict, but I still want to use this method to complete them. The same names of these two buckets give us the illusion of the relationship between them. In fact, the meaning of New bool bubble () is close to that of bool new_bubble, it has nothing to do with void bubble in boo. If you think it has something to do with it, I will give you an example below to show you how to touch your nose.

Public   Class Boo
{
Public   Void Bubble ()
{
Console. writeline ("Boo Sheet");
}
}

Public   Class Foo: Boo
{
Public   New   Void Bubble ()
{
Console. writeline ("Foo Sheet");
}
}

Class Program
{
Static   Void Main ( String [] ARGs)
{
Foo OBJ= NewFoo ();
Test (OBJ );
Console. Readline ();
}

Static   Void Test (boo obj)
{
OBJ. Bubble ();
}
}

Would you say boo sheet or Foo sheet? Please think about why.

The example given by wayfarer seems to be confusing, or may make everyone feel that there is a bug that exposes the protected function, but in fact it is not. I still can't remember what I said before. Protected is an authorization issue, not a confidentiality issue. This statement should partially solve your confusion. The above boo sheet example shows that you have not actually exposed the protected function, because you still cannot directly find the method to use the print function from a base variable pointing to the derived instance. If you still remember the abstract-oriented concept, you should also realize that the derived class you wrote is only a supplement to the base class, the user should generally use the base variable to use your object, instead of the derived variable, unless he thinks that he needs to use the functions provided by derived but not provided by base. If I do not use the New Keyword, but name the print function of derived as printbase, will it cause a bug of "exposing" the base class members?

Apparently not. At this time, if you still cannot access print with the base variable, you can still access printbase with the derived variable (and finally call print ). Do you still remember that the derivation aims to extend the boundaries of the problem domain? Here, a protected function of base is exposed to extend the boundary of the problem domain. The design base believes that the print function is the internal transaction of the object, while the derived designer believes that the print function should be a transaction between the external and the internal, whether print is still called is no longer important. (P.s.: allowed to use the derived class, but not allowed to be exposed, this is impossible, even if the New Keyword does not exist. What truly can be called "exposure" is reflection Bonding/reflection calling. Unfortunately, we still cannot call it a bug because it is the expected function of the design of "reflection", rather than the harmful side effects caused by carelessness .)

Speaking of this, I think the problems of protected and new should have been completed. Are you confused?


Vi. Back to the Future
Let's look back at abstract-oriented and interface-oriented. I have already mentioned abstract orientation. I don't know if you have more thoughts. Abstract to what is the header? Of course, there is no such thing, not void Taiji. The essence of abstraction is to describe what actions a subject can complete and what functions these actions constitute. From this perspective, we will find that the interface can well complete such tasks. For example, ilist represents an abstraction like "A list", which can provide a set of corresponding actions, such as "object this [int Index]; "The Nth item in the list can be retrieved or set. Only members defined by the ilist interface can indicate that this object can be called a list ". The term "service" may be more profound in expressing the above meanings:
Class arraylist: ilist {...}
This definition indicates that arraylist provides services related to the "list. If we use more interfaces when defining variables and parameters, rather than specific classes, our code will have a greater degree of freedom. At this time, we are concerned about whether an object can provide the services I need, rather than what it is.

At the beginning of object-oriented technology, we entered a misunderstanding in this aspect, that is, to use multi-inheritance to solve the above requirement. For example, we can see in C ++ that stream is derived from istream and ostream. This can also solve the problem, and may also express the meaning of "service. However, I think this will cause a lot of unnecessary troubles, such as name conflicts. Modern theories even tell us that it is not a good thing to inherit from him. If we can use references to replace inheritance, we should not inherit, such as decorate in designpattern.

What is the theory of the real future? I don't know. But at least I can see that interface-oriented design is more advanced than "object-oriented". At present, there are far fewer people who can really think like this than those who know how to encapsulate inheritance. From this perspective, it is also a future technology, at least a technology that needs to be popularized in the future. (Isn't com such an idea ?)

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.