Back To Home

OOPS

27-03-2024


Build Bulletproof Code: A Practical Guide to Encapsulation in C# for Unity

Hey there! "Do you get annoyed by neighbors peeking over your fence, trying to see what you're working on in your code garden? Encapsulation is like building a privacy fence around your classes! It ensures only authorized methods (the friendly gatekeeper) can access and modify the class's internal data, keeping your code neighbors out of your business."

Encapsulation is like a secret box that protects important things inside. In C# Unity, encapsulation is used to protect the important parts of the code that make the game work.

Lets simplify it by an example :-

  1. Let’s say you are playing a game and you press a button to make your character jump. The code that makes the character jump is protected inside an encapsulated class. This means that other parts of the code, like the enemies or the scenery, can’t accidentally change the way the character jumps.

  2. So, encapsulation is an important tool in game development because it keeps important parts of the code safe and helps game developers make changes to the game without accidentally breaking it.

The Importance of Encapsulation :-

Encapsulation offers several critical benefits in software development :

  1. Data Protection :
    Sensitive data is shielded from external code, preventing accidental or deliberate modifications. This ensures the consistency and reliability of your program's state.

  2. Controlled Access :
    You have the power to determine how data can be accessed and modified. This allows you to define setter logic that validates incoming values, upholding data integrity and enforcing business rules.

  3. Increased Maintainability :
    By compartmentalizing data and the operations that manipulate it, encapsulation enhances code readability and maintainability. Modifications become more straightforward as changes to internal data structures are less likely to impact other parts of the codebase.

Example :-

post 2

Imagine a peaceful village within a forest, protected by a sturdy fence. Inside, the villagers (your program's data) live organized and secure. This is encapsulation! It keeps your data (like the villagers) safe from the outside world (uncontrolled variables) by controlling access through designated methods (the village gate).

Benefits?

  1. Security :
    Only authorized methods can access data, keeping it safe.

  2. Organization :
    Encapsulation promotes clean and well-defined code structure.

  3. Control :
    You decide how others interact with your data.

  4. Encapsulation makes your Unity projects more secure and easier to manage!


Implementing Encapsulation in C# :-

C# provides access modifiers (public, private, protected) to control the visibility of data members and methods within a class, and across classes in an inheritance hierarchy:

  1. public :
    Accessible from anywhere in your code.

  2. private :
    Accessible only within the class where it's declared. This is the default access modifier for data members, promoting data hiding.

  3. protected :
    Accessible within the class and any classes that inherit from it.

  4. internal :
    Accessible only within the same assembly (project).

Encapsulation in Action - A C# Example :-

  
public class Player
{
    // Private data member for health (encapsulated)
    private int _health;

    // Public property with controlled access (getter and setter)
    public int Health
    {
        get { return _health; }
        set { _health = Mathf.Clamp(value, 0, 100); } // Ensures health stays within 0-100
    }

    public void TakeDamage(int damage)
    {
        Health -= damage; // Modify health through the property
    }
}               

In this example:

_health is declared as private, making it inaccessible directly from outside the Player class. This exemplifies data hiding, a key aspect of encapsulation.

The Health property provides a controlled way to access and modify the player's health.

The setter in the property utilizes Mathf.Clamp to maintain health within a valid range (0-100), demonstrating controlled access with validation logic.

Example 2 :-

Class :

  1. Class itself is an example of encapsulation. Class is like a container which contains similar data and functionalities. If we need to access a variable we need to go through this class first, without the class we can’t access any content of this class.

  2. A general class in C# can also use encapsulation by declaring its member variables and methods with access modifiers such as private, protected, or public.

  3.   
    public class Person
    {
        private int age;
    
        public Person(int initialAge)
        {
            age = initialAge;
        }
    
        public int GetAge()
        {
            return age;
        }
    }               
    
  4. In this example, the member variable “age” is declared as private, which means it can only be accessed within the Person class itself. The public method “GetAge” is used to return the value of age to other parts of the code that need to use it.

  5. By encapsulating the age variable, we can prevent other parts of the code from accidentally changing its value, which could lead to errors in the program. Instead, the age variable can only be accessed and modified through the public methods provided by the Person class, which ensures that its value is always valid and consistent.

Example 3 :-

School bag :

  1. Imagine you have a school bag with different pockets and compartments to store your books, pencils, and other school supplies. Each pocket or compartment is like a private member variable in a C# class, and you can only access its contents using a public method provided by the bag class.

  2. post 2
  3. Here’s an example of a Bag class that uses encapsulation to protect its contents:

  4.   
    public class Bag {
        private List books;
        private List pencils;
    
    public Bag()
    {
        books = new List();
        pencils = new List();
    }
    
    public void AddBook(string bookName)
    {
        books.Add(bookName);
    }
    
    public void AddPencil(string pencilColor)
    {
        pencils.Add(pencilColor);
    }
    
    public List GetBooks()
    {
        return books;
    }
    
    public List GetPencils()
    {
        return pencils;
    }
    }            
    
  5. In this example, the Bag class has two private member variables: books and pencils. These variables represent the contents of the bag and are not accessible from outside the Bag class.

  6. To add a book or pencil to the bag, we can use the public methods AddBook and AddPencil, which add the corresponding item to the books or pencils list.

  7. To retrieve the contents of the bag, we can use the public methods GetBooks and GetPencils, which return the corresponding list of items.

By encapsulating the contents of the bag, we can ensure that they are protected from accidental modification by other parts of the code. Only the public methods provided by the Bag class can be used to modify or retrieve the contents of the bag, which ensures that its contents are always valid and consistent.


I hope you found this blog post enjoyable!


More Blogs

See All