방프리

23.06.08 Chapter2. API 설계 (Item 17) 본문

C#/More Effective C#

23.06.08 Chapter2. API 설계 (Item 17)

방프리 2023. 6. 8. 01:11

Item 17 : 내부 객체를 참조로 반환해서는 안된다.

 

내부 객체를 외부에 노출시킬 때 다음과 같은 실수를 많이 할 것 같다.

public class MyBusinessObject
{
    public MyBusinessObject()
    {
    	DAta = new BindingList<ImportantData>();
    }
    
    public BindingList<ImportantData> Data { get; }
}

BindingList<ImportantData> stuff = bizObj.Data;

stuff.Clear();

프로퍼티를 통해 getter만 활성하였으나 참조 형태로 반환하여 원본 데이터가 훼손될 여지를 주게 되는 것이다.

어떻게 하면 외부의 동작으로부터 내부의 데이터를 보호할 수 있을까?

외부에 노출시킬 때 원본이 아닌 복사 객체를 보여주는 것이다.

public class MyBusinessObject
{
    private BindingList<ImportantData> listOfData = new
    	BindingList<ImportantData>();
        
    public IBindingList BindingData => listOfData;
    public ReadOnlyCollection<ImportantData> CollectionOfData => 
    	new ReadOnlyCollection<ImportantData>(listOfData);
}

복사 객체를 다시 ReadOnlyCollection으로 반환한다면 외부의 동작으로부터 안전하게 내부 참조 데이터를 보존할 수 있다.

Comments