Public vs Protected vs Private

Όνομα: *
Το email μου: *
Email παραλήπτη: *
Μήνυμα: *
Τα πεδία με έντονους χαρακτήρες είναι υποχρεωτικά.
Δεν έχετε συμπληρώσει όλα τα απαιτούμενα στοιχεία Το email που δώσατε δεν είναι σωστό

Encapsulation is regarded as one of the pillars of Object Oriented Programming. In a few words it is a mechanism that restricts parts of a project from accessing some of its components. .Net framework contains three access modifiers. Public, protected and private. Once we take a short look at what these modifiers do, we will focus on why and how we should use them.
 

Access modifiers

Since encapsulation is a much discussed subjected I am not going to look thoroughly at what it is and how it works, rather than how to make effective use of it. However we're going to take a glance first.
 
What is the actual meaning of restricting access anyway? It's quite simple. Supposing a class contains a method, this method can obviously be used anywhere within the class but what about the outside world? if we choose to do so, we may deny an object of that class from calling that method. The examples following will make things much clearer.
 
 
 
 
 
Here's a brief summary of what each access modifier does.
 
  • Public is the simplest modifier. A component set as public can be accessed anywhere.
  • A private component, on the other hand, can only be accessed within its class.
  • A protected component stands in the middle. It can be accessed within its class and all derived classes. 

 

public vs private vs protected
 
 
In the following C# example there are four classes. Three of them contain a method to return a random number. However the first one uses a public method, the second one a private and the third one a protected method. The main class will try to call this method using each class.
 
public class Encapsulation : ClassWithProtectedMethod
{
  public Encapsulation()
  {
        //Public method is easily accessed
        ClassWithPublicMethod pubClass = new ClassWithPublicMethod();
        int random = pubClass.GetRandomNumberPublic();
 
        ClassWithPrivateMethod pubClassPriv = new ClassWithPrivateMethod();
        //Unable to access private method 
        //random = pubClassPriv.GetRandomNumberPrivate();
 
        //Protected method can be accessed since the Encapsulation class is derived from ClassWithProtectedMethod
        random = this.GetRandomNumberProtected();
  }
    
}
 
 
public class ClassWithPublicMethod
{
    //This is a public method. It can be accessed anywhere.
    public int GetRandomNumberPublic()
    {
        Random rnd = new Random();
        int random = rnd.Next();
        return random;
    }
}
 
public class ClassWithPrivateMethod
{
    //This is a private method. It can be accessed only within the class.
    int GetRandomNumberPrivate()
    {
        Random rnd = new Random();
        int random = rnd.Next();
        return random;
    }
}
 
public class ClassWithProtectedMethod
{
    protected int GetRandomNumberProtected()
    {
        //This is a protected method. It can be accessed only within the class and by derived classes.
        Random rnd = new Random();
        int random = rnd.Next();
        return random;
    }
}
 
There's one more access modifier left that should be mentioned in order to cover all of them. In addition to the previous modifiers, the internal keyword restricts access to files out of the assembly it is declared. In other words, the component is regarded as public within the assembly and private out of it. Internal may be used along with protected to create components that can be accessed only from derived classes within the assembly they are declared.
 
 

public vs protected vs private

We just found out what these modifiers do. Now, the real question is why should someone use them. I mean, this is our project and we definetely do not want it to be restricted. We would like it to be as easy to handle as possible. Setting components as private will only result in getting compilation errors when trying to access them and force us to change the modifier at that point. Why then not to do so all the way from the beggining and set all components to public?
 
Such questions are not hard to rise in novice developers. And, quite true, turning every modifier to public would not be a bad idea if we are talking about small projects. However, what if we were talking about a much bigger application containing a bunch of classes connected to each other one way or another? When creating such applications maintenance is something you should really keep in mind.
 
Supposing there is a class responsible for calculating some amounts. The class may contain lots of methods and other stuff used in its calculations. However when we are going to use that class we do not care for all of these. We only care about our methods GetAmountNo1, GetAmountNo2 etc. The rest of the class is like a black box to us and that's the way it should be. Apart from getting access to unesecary info, toying around with class members we may end up destroying its functionality. 
 
Since we are working on some large project it is expected that many developers work together. By restrincting access, our classes become much easier to use and less possible to end up in some strange piece of code.
 
You may have guessed that the best thing to do is restrict a member's access as much as possible. That's why by default .Net creates private members (a member having no access modifier is regarded as private). So, the best thing is to keep everything private. In case you do need to have access from another class, only then should you use protected or public members. Protected is much better than public since it allows only derived classes (which usually are much less in number than the whole of the classes) to access the members.
 
To sum up, the best thing to do is:
  1. Set every member to private.
  2. If you need to access it from a derived class set the member to protected.
  3. If you need to access it from a class that does not inherit its class, set the member to protected.
 

Summary

Access modifiers may allow a class member to be accessed by other classes or not. Setting a member as public it can be accessed by every class. A protected member can only be accessed by derived classes while a private member cannot be accessed outside of its class. Class members should be set to private unless needed to. In that case they should be set to protected or public.

Πίσω στο BlogΠροηγούμενοΕπόμενο

Σχόλια


  • 12-10-2013, 20:02 μμ
    kbadas
    Δημοσιεύσεις: 6
    I was actually thinking of covering the three main modifiers only, but you are right; internal should be present as well so that the article is complete. Thanks for the tip.
  • 10-10-2013, 18:33 μμ
    Stefanos
    Δημοσιεύσεις: 1
    And of course you can use "internal protected" to allow inheritance within an assembly and disable it outside that. Uncommon but nonetheless quite useful.
  • 10-10-2013, 18:31 μμ
    Stefanos
    Δημοσιεύσεις: 1
    "Internal" is another very useful access modifier: it acts as "public" inside the assembly where you use it, and "private" outside that assembly. This can be used to encapsulate internal implementation details that should be freely accessible from other code inside an assembly, but should not visible to outside consumers of the assembly.

Γράψε το σχόλιό σου
Όνομα: