E D R , A S I H C RSS

Collection Parameter

Collecting Parameter

몇몇 메소드의 결과와 협력하는 콜렉션을 어떻게 리턴할것인가?(?)

ComposedMethod의 단점중 하나는, 작은 메소드들 사이의 연관때문이다. 큰 메소드 하나에서 공유되었던 임시 변수들이, 이제는 작은 메소드들 사이에 공유된다. 가장 해결하기 쉬운 방법은 ComposedMethod를 없애고 다시 하나의 큰 메소드에 다 때려넣는 것이지만, 안좋다. 또 다른 해결책으로는 이 작은 메소드들 사이에서 공유되는 임시 변수를 멤버변수에 넣는 것이다. 이것은 객체의 생명기간 동안 유효한게 아니라, 저 메소드들이 실행될때에만 유효하다. 역시 안좋다.

우리의 해결책은, 메소드들마다 필요한 파라메터들을 넘겨주는 것이다. 이것도 좀 망설여지는 방법이긴 하나, 다른 것들보단 낫다.

어떤 콜렉션의 기혼남과 미혼녀를 추출해내는 코드를 보자.
~cpp 
vector<People> marriedMenAndUnmarriedWomen()
{
	vector<People> result;
	for(vector<People>::iterator it = result.begin() ; it != result.end() ; ++it)
	{
		if(it->isMarried() and it->isMan())
			result.add(*it);
	}
	for(vector<People>::iterator it = result.begin() ; it != result.end() ; ++it)
	{
		if(it->isUnmarried() and it->isWoman())
			result.add(*it);
	}
	return result;
}
ComposedMethod를 적용해보자.
~cpp 
vector<People> marriedMen()
{
	vector<People> result;
	for(vector<People>::iterator it = result.begin() ; it != result.end() ; ++it)
	{
		if(it->isMarried() and it->isMan())
			result.add(*it);
	}
	return result;
}
vector<People> unmarriedMen()
{
	vector<People> result;
	for(vector<People>::iterator it = result.begin() ; it != result.end() ; ++it)
	{
		if(it->isUnmarried() and it->isWoman())
			result.add(*it);
	}
	return result;
}
vector<People> marriedMenAndUnmarriedWomen()
{
	return marriedMen() + unmarriedMen();	// 될지 안될지는 모르겠지만 된다고 가정하자.
}

콜렉션을 리턴하지 말고 각각을 콜렉션에 더하자.
~cpp 
vector<People> marriedMenAndUnmarriedWomen()
{
	vector<People> result;
	addMarriedMenTo(result);
	addUnmarriedWomenTo(result);
	return result;
}

void addMarriedMen(vector<People>& aCollection)
{
	for(vector<People>::iterator it = result.begin() ; it != result.end() ; ++it)
	{
		if(it->isMarried() and it->isMan())
			aCollection.add(*it);
	}
}
void addUnmarriedMen(vector<People>& aCollection)
{
	for(vector<People>::iterator it = result.begin() ; it != result.end() ; ++it)
	{
		if(it->isUnmarried() and it->isWoman())
			aCollection.add(*it);
	}
}

즉, 두 메소드의 결과를 모으는 경우인데, 그리 흔한 경우는 아니였던걸로 기억. 약간은 다르긴 하지만 나의 경우 CollectionParameter 의 성격으로 필요한 경우가 read/write 등 I/O 가 내부적으로 필요할때 또는 Serialization 등의 일이 필요할때. 그 경우 I/O 부분은 Stream 클래스로 만들고(C++ 의 Stream 을 쓰던지 또는 직접 Stream 클래스 만들어 쓰던지) parameter 로 넘겨주고 그 파라메터의 메소드를 사용하는 형태였음. --1002


Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:22:57
Processing time 0.0098 sec