💻 프로그래밍

캡슐화(Encapsulation)

gameuiux 2024. 12. 25. 18:01
728x90
반응형

캡슐화(Encapsulation)

객체 지향 프로그래밍(OOP)의 핵심 개념 중 하나로,

데이터(변수)와 해당 데이터에 작용하는 메서드(함수)를 하나의 단위(클래스)로 묶고,

외부에서 직접 접근을 제한하는 것

 

 

캡슐화의 핵심 원칙

데이터 은닉(Data Hiding)
객체의 내부 상태(변수)를 외부에서 직접 접근하지 못하도록 제한
주로 private 접근 제한자를 사용한다.


정보 보호(Protection)
외부에서는 반드시 제공된 메서드(getter/setter)를 통해서만 내부 데이터를 읽거나 변경할 수 있다.

 

인터페이스 제공(Abstraction)
외부에서는 내부 구현 세부사항을 알 필요 없이, 필요한 기능만 사용할 수 있다.

 

 

캡슐화 예제

using UnityEngine;

public class Player : MonoBehaviour
{
    // **캡슐화된 변수**(데이터 보호)
    [SerializeField] private string playerName = "Player1";
    [SerializeField] private int health = 100;

    // **데이터 접근 메서드(getter/setter)**(제어된 접근)
    public string GetPlayerName()
    {
        return playerName;
    }

    public void SetPlayerName(string newName)
    {
        playerName = newName;
    }

    public int GetHealth()
    {
        return health;
    }

    public void TakeDamage(int damage)
    {
        health -= damage;

        if (health < 0)
            health = 0; // 음수가 되지 않게 보호(무결성 보장)
    }

    void Update()
    {
        Debug.Log($"Player: {playerName}, Health: {health}");
    }
}

 

 

왜 캡슐화가 중요한가?

보안(Security)
데이터를 무분별하게 조작할 위험을 줄인다.


유지보수성(Maintainability)
코드의 변경이 필요할 때 메서드 내부만 수정하면 되므로 유지보수가 쉽다.


유연성(Flexibility)
변수와 메서드를 분리하여 필요에 따라 추가 로직을 적용할 수 있다.

 

재사용성(Reusability)
클래스를 다른 프로젝트나 코드에서 재사용할 때 안정적으로 활용할 수 있다.

 

 

결론

캡슐화는 데이터를 보호하면서 필요한 부분만 노출시켜 안전한 코드 작성과 유지보수 편의성을 제공하는 개념이다.

728x90
반응형