In-depth analysis of the encapsulation role in object-oriented

Source: Internet
Author: User

Before I (Dream on the Journey) published an article called "in-depth analysis object-oriented concept of objects," which mainly explains the relationship between classes and objects and the concept of objects, state, behavior, the role of a few knowledge points, so that we have some in-depth understanding of objects, and this article will talk about one of the three characteristics of object: , encapsulation is the basis of object-oriented, in-depth understanding of the characteristics of encapsulation, so that we can better understand the object-oriented thinking and implement object-oriented programming. The following are my many years of development experience to summarize the personal views, if you find the wrong or insufficient place, welcome to correct and exchange, thank you!

First, what is encapsulation?

As the name implies, seal: closed, Loaded: loaded, the specific implementation of the details into a container, and closed up, to prevent the container outside the container directly access to the implementation of the internal details, exposing only the specified access path; Examples of life: to eat in a restaurant, you just need to tell the waiter what you want to eat, The waiter will explain to the kitchen chef in the background, waiting for a period of time, the food is delivered directly to you before the waiter, as the customer you are not aware of the specific practice of food, the background kitchen cooks and cook the process is to be encapsulated details, and the waiter is a publicly exposed access path, You can only order food through the waiter and then get the food, but not directly to the backstage kitchen to ask the chef how to cook food;

The sample code is as follows:

    <summary>///restaurant///</summary> class Fanguan {private string dofoodname;        <summary>///food///</summary>/<param name= "Foodname" ></param>            public void Choosefood (string customer, String foodname) {dofoodname = Foodname;        Console.WriteLine ("Customer: {0}, order meal: {1}", customer, Foodname);        }///<summary>//For meals//</summary>//<returns></returns>            public string Getfood () {String cookeresult = Cookefood ("Chef Armor"); return string. Format ("{0}, please dine, thank you!"        ", Cookeresult); }///<summary> Cook cooking, private method, external not accessible//</summary>//<param name= "Cooker"            ;</param>//<returns></returns> private string Cookefood (String cooker) { Console.WriteLine ("Chef: {0} start cooking:{1}>>>>", cooker, dofoodname);            Console.WriteLine ("Fire");            Console.WriteLine ("Oil Discharge");            Console.WriteLine ("Put ingredients, stir fry");            Console.WriteLine ("Add seasoning");            Console.WriteLine ("Dish cooked up the pot, bring to the plate to pass to the waiter");            Console.WriteLine ("End <<<<"); return string.        Format ("dish: {0} is ready", dofoodname);            }}//actual usage: static void Main (string[] args) {Fanguan Fanguan = new Fanguan ();            Fanguan.choosefood ("Dream On the Journey", "braised eggplant");            String food = Fanguan.getfood ();            Console.WriteLine (food);            Console.WriteLine ("Dine");        Console.readkey (); }

The example is very simple and the results are no longer coming out.

Second, what is the role of encapsulation?

1. Isolation:
The encapsulated object (where the object is a programming unit that refers to a code, generally: an assembly, namespace, class, method, attribute, variable, etc.) whose external object is not directly accessible to the internal implementation details of the object, the changes to the internal implementation details do not affect the access principle of the external object (that is, after the object is modified, In the case of exposing the specified access path unchanged, external access to its object is not modified, this is the embodiment of isolation, but also to achieve high cohesion, low coupling one of the most fundamental ideas;
2. Reusability:
The encapsulated object can be accessed by multiple external objects without having to specify a different service object for each external object, such as: All object base classes are object classes, and the public members of the objects class can be used by all of their subclasses. The ADO-related data access class and its public members can be used by all other objects.
3. Readability:
The name of the encapsulated object (e.g., assembly name, class name, method name), if properly named, can understand the role of the object without looking at the implementation details, such as: A DataTable is used to load tabular data; ToString is converted to a string, Length is what it means.

Three, what is the scope of the package?

1. Encapsulated into constants/variables:
For example: Calculate the circumference length, the code before encapsulation is as follows:

            Before encapsulation:            decimal result = 2 * 3.141592653M * 10.8M;            Console.WriteLine ("Circumference length is: {0}", result);

The code after encapsulation is as follows:

            After encapsulation:            const decimal PI = 3.141592653M;            Decimal radius = 10.8M;            Decimal circumference = 2 * PI * RADIUS;            Console.WriteLine ("Circumference length is: {0}", circumference);

Which kind of readability do you think is higher? From my perspective, it is obvious that the encapsulated code is more easily understood by others, because the circumference of the long calculation formula is: C=2πr, from the circumference know is the result of a long circumference, and the right side of the equal sign is exactly the circumference of the calculation formula, so very intuitive, readability is reflected;
2. Encapsulation into methods/functions/properties:

Calculates the circle perimeter static decimal computecircumference (decimal radius)        {            const decimal PI = 3.141592653M;            Return 2 * PI * RADIUS;        } Usage: Console.WriteLine ("Circumference length is: {0}", Computecircumference (10.8M));

By encapsulation into a method, we see the Computecircumference method, we know is to calculate the circumference of the circle, at the same time I can use this method to calculate the circumference of all the different radii of the circle, readability, reusability is reflected;
3. Encapsulation into classes:

///<summary>////</summary> class Circle {        Origin x coordinate public int Originx {get; set;}        Origin y coordinate public int originy {get; set;}        Radius public decimal radius {get; set;} Public Circle (int originx, int. originy, decimal radius) {this.            Originx = Originx; This.            Originy = Originy; This.        radius = radius;        }///<summary>//For circumferential lengths//</summary>//<returns></returns>            Public decimal getcircumference () {Const decimal PI = 3.141592653M; Return 2 * PI * this.        Radius; }}//Usage: Circle circle = New Circle (10,10,10.8m); Console.WriteLine ("Circumference length is: {0}", circle.) Getcircumference ()); 

As can be seen from the example code above, I define (encapsulate) a circle class, the Circle class has the origin and radius, and there is a method to obtain the circumference length, the circle class can be used to represent a number of poor size of different positions of the circle, but also can get the circumference of the circle length, as to how the circumference is calculated, Pi precision We do not need to know and can not directly change, so the isolation, readability, reusability are reflected;
4. Encapsulating layers/Packages/assemblies:

Sometimes, due to the need of the system architecture, we may need to encapsulate the code describing various kinds of graphical information separately into an assembly, package, namespace, to facilitate the management of the code, so we can put the circle class in a separate assembly, At the same time, the assembly and namespace names are: Math.shape, meaning mathematics. Graphics, from the name you know this assembly or namespace is used to deal with math and graphics related.

The sample code is as follows:

namespace math.shape{public     class Circle     {         //omitted, IBID.      }}//usage: Math.Shape.Circle Circle = new Math.Shape.Circle (ten, 10.8M); Console.WriteLine ("Circumference length is: {0}", circle.) Getcircumference ());

Four, the packaging of the taboo

1. Avoid over-encapsulation

Such as:

            String a = "a";            String B = "B";            string c = "C";            String d = "D";            String joinstring = a + B + C + D;            Console.WriteLine (joinstring);

The improved Code:

            String joinstring = "{0}{1}{2}{3}";            joinstring = string. Format (joinstring, "a", "B", "C", "D");

This is a typical encapsulation over, too atomized, to define a variable for each string, the code volume increases, and the efficiency is not high, and the improved code is streamlined and efficient.

Of course, there are some encapsulation, such as: A method or a class code is very much, suppose there is a mathematical calculation class, you can calculate all the number types and all the mathematical calculation method, imagine how much its code, this time should consider the appropriate split encapsulation, At the very least, it can be broken into mathematical type classes and mathematical calculations.
2. Avoid inappropriate encapsulation

Such as:

        static bool IsNullOrEmpty (String str)        {            return string. IsNullOrEmpty (str);        }        static bool Isnotnullorempty (String str)        {            return!string. IsNullOrEmpty (str);        }

As can be seen from the above code, the IsNullOrEmpty of string has been able to meet the requirements, but some people may also be superfluous, adding such two classes, And even for the sake of not writing string. So, there's no need to write two methods, one way, because the two methods themselves are antagonistic, there may be a situation at the same time, the following improvements can be made:

        static bool IsNullOrEmpty (object obj)        {            if (obj = = null)            {                return true;            }            return string. IsNullOrEmpty (obj. ToString ());        }

This improved, the obvious isnullorempty can be used to determine whether all the type is null or empty, if you need to determine the need to be null or empty, just call the method and take the reverse, such as:! IsNullOrEmpty ("Zuowenjun")

Five, the end

This article was originally intended to be published last year, "deep analysis object-oriented concept of object" immediately after writing this, I generally write some of the most summarized articles are first written in Word and then copied over, this article is also, but because of the previous work has been written only an outline, So today I saw this blog post lying in my folder, but also Lenovo recently I as an interviewer and the status of new personnel (I published an article "from the interview caused by the thinking: b/S and C/S is what"), so decisive in today spent an afternoon of time, side want to write, and finally finished, Also hope that we can benefit from the two articles themselves are not very deep and very new technology, but as a programmer, if you want to have technical attainments, must first learn the basic skills, I repeat my point of view:

Technology is like martial arts, basic skills is very important, as long as the basic skills, and then to learn the architecture, design patterns, it will be easier, at the same time these seemingly tall things, such as: AOP,SOA,DI,IOC,DDD,CQRS, as long as the understanding of its principle, extrapolate can achieve "no recruit wins a recruit" The highest state.

In-depth analysis of the encapsulation role in object-oriented

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.