반응형
데이터 뭉치(Data Clumps)는 코드에서 같은 데이터 집합이 여러 곳에서 사용되는 경우를 가리키는 냄새입니다.
이러한 데이터 뭉치는 흔히 다음과 같은 형태로 나타납니다.
Class Employee
{
public:
Employee(string inName, string inEmployeeAreaCode, string inEmployeeNumber)
:_name(inName),
_employeeAreaCode(inEmployeeAreaCode),
_employeeNumber(inEmployeeNumber)
{}
string GetEmployeePhoneNumber()
{
return _employeeAreaCode + "-" + _employeeNumber;
}
private:
string _employeeAreaCode;
string _employeeNumber;
string _name;
};
Class Office
{
public:
Office(string inLocation, string inOfficeAreaCode, string inOfficeNumber)
:_location(inLocation),
_officeAreaCode(inOfficeAreaCode),
_officeNumber(inOfficeNumber)
{}
string GetOfficePhoneNumber()
{
return _officeAreaCode+ "-" + _officeNumber;
}
private:
string _officeAreaCode;
string _officeNumber;
string _location;
};
Employee 클래스와 Office 클래스에서 각각 전화번호를 표현하는 방식이 동일하게 _employeeAreaCode와 _employeeNumber, _officeAreaCode와 _officeNumber로 나뉘어져 있는데 이들이 중복되어 데이터 뭉치를 형성하고 있습니다.
이러한 경우에는 코드의 가독성을 해치고 코드 유지보수를 어렵게 만들 수 있으므로, 이러한 데이터 뭉치를 제거하기 위해 코드를 개선해 볼 필요가 있습니다.
Employee 클래스와 Office 클래스에서 중복되는 데이터를 클래스로 추출하여 해결할 수 있습니다.
이를 위해 PhoneNumber 클래스를 새로 만들어서 공통으로 사용하면 됩니다.
class PhoneNumber {
public:
PhoneNumber(string areaCode, string number) : _areaCode(areaCode), _number(number) {}
string getPhoneNumber() const {
return _areaCode + "-" + _number;
}
private:
string _areaCode;
string _number;
};
class Employee {
public:
Employee(string name, PhoneNumber phoneNumber) : _name(name), _phoneNumber(phoneNumber) {}
string getPhoneNumber() const {
return _phoneNumber.getPhoneNumber();
}
private:
string _name;
PhoneNumber _phoneNumber;
};
class Office {
public:
Office(string location, PhoneNumber phoneNumber) : _location(location), _phoneNumber(phoneNumber) {}
string getPhoneNumber() const {
return _phoneNumber.getPhoneNumber();
}
private:
string _location;
PhoneNumber _phoneNumber;
};
위 코드에서는 PhoneNumber 클래스를 새로 추가하여 Employee 클래스와 Office 클래스에서 공통으로 사용합니다.
이를 통해 데이터 중복을 제거할 수 있습니다.
또한, PhoneNumber 클래스에는 전화번호를 구성하는 _areaCode와 _number가 함께 있으므로 기능적으로도 연관성 있는 데이터끼리 모아서 관리할 수 있습니다
적용 가능한 리팩터링 기법
'리팩터링 > 냄새 (리팩터링할 시점)' 카테고리의 다른 글
냄새 12. 반복되는 switch문(Repeated Switches) (0) | 2023.04.04 |
---|---|
냄새 11. 기본형 집착(Primitive Obsession) (0) | 2023.03.31 |
냄새 9. 기능 편애(Feature Envy) (0) | 2023.03.29 |
냄새 8. 산탄총 수술(Shotgun Surgery) (0) | 2023.03.21 |
냄새 7. 뒤엉킨 변경(Divergent Change) (0) | 2023.03.17 |