방프리
23.06.08 Chapter2. API 설계 (Item 17) 본문
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으로 반환한다면 외부의 동작으로부터 안전하게 내부 참조 데이터를 보존할 수 있다.
'C# > More Effective C#' 카테고리의 다른 글
23.06.20 Chapter2. API 설계 (Item 19) (0) | 2023.07.15 |
---|---|
23.06.11 Chapter2. API 설계 (Item 18) (0) | 2023.06.11 |
23.05.20 Chapter2. API 설계 (Item 16) (0) | 2023.06.04 |
23.05.20 Chapter2. API 설계 (Item 15) (0) | 2023.05.20 |
23.01.30 Chapter2. API 설계 (Item 14) (0) | 2023.02.05 |
Comments