ShouldKnow

A Brief Look at Encapsulation

Dictionary : “The succinct expression or depiction of the essential features of something”

Thesaurus: condense, summarise

Wikipedia says : “A language mechanism for restricting access to some of the object's components”

Encapsulation keeps the internal details of an object hidden, an example is below:

public class Fibber
{
    private int numberOfdoughnutsEaten = 6;

    public int TheTruth()
    {
        return LieValue(3);
    }

    public int OkTheRealTruth()
    {
        return LieValue(2);  //still not the real truth!
    }
    
    private int LieValue(int divideBy) 
    {
        return numberOfdoughnutsEaten / divideBy;
    }
}

Here we can see that we keep the internal value numberOfdoughnutsEaten private and only expose it through the methods Truth and Lie. We're also keeping the LieValue method private.

What does Encapsulation give us?

Keeping information private means that if we don’t want someone to be able to alter a value or call a method then they can’t.

This also simplifies the object when viewed from the outside. Seeing the underlying details would add more information for someone using it to try to understand and ideally we want them to have to understand only the essential parts of what the class does, not the underlying implementation. Simple is good!


Got a comment or correction (I’m not perfect) for this post? Please leave a comment below.




My Pluralsight Courses: (Get a free Pluaralsight trial)

API Security with the OWASP API Security Top 10

OWASP Top 10: What's New

API Security with the OWASP API Security Top 10

Secure Coding in ASP.NET Core

Secure Coding: Broken Access Control

Python Secure Coding Playbook

You've successfully subscribed to Gavin Johnson-Lynn!