My main() Method Is Better Than Yours글을 읽다보니 나오는 문장이라 소개한다.

New operator in application code is enemy of testing, but new in tests and factories is your friend.

최근 테스트 관련한 글들을 읽고 있는데 많은 곳에서 이야기하고 있는 내용이다. 그 중에서 가장 마음에 드는 문장이다. 지금까지 new operator를 사용하는 것에 신경쓰지 않았던 개발자라면 지금쯤 다시 한번 생각해볼 수 있는 계기가 되었으면 좋겠다.

How to Think About the “new” Operator with Respect to Unit Testing 글도 new operator를 생각하는데 도움이 되리라 생각한다. 테스트에 관심있는 개발자라면 이미 수도 없이 보아왔던 글들과 예제이다.

지금 프로젝트에서도 테스트 코드를 만들 때 Object의 생성을 어떻게 하느냐에 따라서 테스트 코드의 복잡도가 달라지는 것을 느낄 수 있었으며, 테스트 용이한 코드를 만들기 위해서 Object를 어떻게 생성하느냐는 중요한 이슈가 되었다.

혹시 이런 내용으로 글을 적었더니 클래스에서 new operator를 무조건 사용하지 말아야 된다고 생각하는 개발자는 없으리라 생각한다. Value-objects인 경우에는 new operator를 이용하여 직접 생성해도 무방하다. Value Object는 Object Graph 상에서 가장 말단에 위치하고 있기 때문에 직접 생성해도 테스트에는 큰 부담이 없다. 이와 관련한 내용은 Writing Testable Code의 9.Mixing Service Objects with Value Objects라는 글을 읽다 보면 잘 나와 있다.

A value-object should never take a service object in its constructor (since than it is not easy to construct). Value-objects are the leafs of your application graph and tend to be created freely with the "new" operator directly in line with your business logic (exception to point 1 since they are leafs). Service-objects are harder to construct and as a result are never constructed with a new operator in-line, (instead use factory / DI-framework) for the object graph construction.

이 이슈는 Dependency Injection(이하 DI)과도 관련이 있으니 아직까지 DI를 모르는 개발자라면 공부해볼만한 가치가 있을 것으로 생각한다.
Posted by 자바지기