IT/리팩토링

[리팩토링] 클래스 멤버변수 이동

상쾌한기분 2019. 10. 25. 11:21
728x90
반응형

어떤 멤버변수 필드가 자신이 속한 클래스보다 다른 클래스에서 더 많이 사용 되어질 때
대상 클래스안에 새 필드를 선언하고 그 필드 참조 부분을 새 필드 참조 하도록 수정하자.

시스템이 발전하고 수정되어 앞으로 나아갈수록 새 클래스가 필요해지며 기능이 여기저기서 사용이 많아진다. 따라서 그러한 것들을 여기저기로 옮겨야 하는 상황과 필요가 있다.

지금은 합리적이고 올바르다고 판단해서 설계 및 개발을 했다 해도, 나중에는 그렇지 않을 수 있다.
문제는 그러한 상황에서 아무것도 하지 않는 것이다.

 

변경전 
AccountType 클래스에서 interestRate 필드를 더 많이 사용하는 경우

class Account
{
	private AccountType _accountType;
	private double _interestRate;

	double interestForAmount_days(double amount, int days)
	{
		return this._interestRate * amount * days / 365;
	}

	example method()
	{
		use _interestRate;
	}

}

class AccoutType
{
	example method()
	{
		use _interestRate;
	}

	example method2()
	{
		use _interestRate;
	}

	example method3()
	{
		use _interestRate;
	}
	
}

 

변경 후
필드 캡슐화 진행

class Account
{
	private AccountType _accountType;

	double interestForAmount_days(double amount, int days)
	{
		return _accountType.getInterestRate() * amount * days / 365;
	}

	example method()
	{
		use _accountType.getInterestRate();
	}

}


class AccoutType
{
	private double _interestRate;

	/* 필드 캡슐화 */
	void setInterestRate(double interestRate)	
	{
		this._interestRate = interestRate;
	}

	double getInterestRate()
	{
		return this._interestRate;
	}
	/* 필드 캡슐화 */

	example method()
	{
		use this.getInterestRate();
	}

	example method2()
	{
		use this.getInterestRate();
	}

	example method3()
	{
		use this.getInterestRate();
	}

}
728x90
반응형