런타임 로직에서 MyServiceImpl 객체를 전혀 사용하지 않더라도 의존성을 해결하지 않으면 컴파일 에러가 발생한다.
테스트에서도 문제, MyServiceImpl이 무거운 객체라면 단위 테스트에서 getService 메서드를 호출하기 전에 적절한 테스트 전용 객체를 service 필드에 할당해야 한다.
일반 런타임 로직에다 객체 생성 로직을 섞어 놓은 탓에 모든 실행 경로도 테스트를 해야한다. (service null 체크)
메서드가 두가지 이상의 일을 하게 된다.
MyServiceImpl이 모든 상황에 적합한 객체인지 모른다.
초기화 지연이 한번이라면 모르겠지만 많은 애플리케이션이 이런 설정 기법을 수시로 사용하고 이는 곳곳에 흩어져 있기 때문에 모듈성이 저조되고 중복이 심각해진다.
즉 체계적이고 탄탄한 시스템을 만들고자 한다면 모듈성을 깨면 안된다.
모듈성을 위해 설정과 실행 논리를 분리하자.
주요 의존성을 해소하기 위한 전반적이며 일반적인 방식이 필요하다.
1. Main 분리
생성과 관련한 코드는 모두 main이나 main이 호출하는 모듈로 옮기고 나머지 시스템은 모든 객체가 생성되었고 모든 의존성이 연결되었다고 가정한다.
이렇게 분리를 하게되면 Application은 사용할 객체가 생성되는 과정을 몰라도 되며 생성과 사용이 분리가 된다.
코드참고
public class Main {
public long sellFruit() {
Fruit fruit = FruitBuilder.getFruit("apple");
return new FruitService().sellFruit(fruit);
}
}
public interface Fruit {}
public class FruitBuilder {
public static Fruit getFruit(String fruitName) {
if (fruitName.equals("apple"))
return new Apple();
else if (fruitName.equals("grape"))
return new Grape();
else if (fruitName.equals("orange"))
return new Orange();
else
throw new IllegalArgumentException("없는 과일");
}
}
public class FruitService {
public long sellFruit(Fruit fruit) {
if (fruit.equals("apple"))
return 1000;
else if (fruit.equals("grape"))
return 2000;
else if (fruit.equals("orange"))
return 1500;
else
throw new IllegalArgumentException("없는 과일");
}
}
2. 팩토리
때로는 객체가 생성되는 시점을 애플리케이션이 결정할 필요도 생길 때가 발생하는데 이런 경우는 팩토리 형식을 사용할 수 있다.
팩토리를 적용하면 Application(OrderProcessing)은 FactoryImpl을 받아 필요할 때 LineItem을 생성한다.
애플리케이션은 LineItem이 언제 생성되는지 알 수 없으며 생성과 사용이 분리가 된다.
코드참고
public class Main {
public long sellFruit() {
return new FruitService(new FruitFactoryImpl()).sellFruit("apple");
}
}
public interface Fruit {}
public interface FruitFactory {
Fruit getFruit(String fruitName);
}
public class FruitFactoryImpl implements FruitFactory {
public Fruit getFruit(String fruitName) {
if (fruitName.equals("apple"))
return new Apple();
else if (fruitName.equals("grape"))
return new Grape();
else if (fruitName.equals("orange"))
return new Orange();
else
throw new IllegalArgumentException("없는 과일");
}
}
public class FruitService {
private FruitFactory fruitFactory;
public FruitService(FruitFactoryImpl fruitFactory) {
this.fruitFactory = fruitFactory;
}
public long sellFruit(String fruitName) {
Fruit fruit = fruitFactory.getFruit(fruitName);
if (fruit.equals("apple"))
return 1000;
else if (fruit.equals("grape"))
return 2000;
else if (fruit.equals("orange"))
return 1500;
else
throw new IllegalArgumentException("없는 과일");
}
}
3. 의존성 주입
사용과 제작을 분리하는 강력한 매커니즘 중 하나로 IOC 기법을 의존성 관리에 적용한 매커니즘이다.
한 객체가 맡은 보조 책임을 새로운 객체에게 전적으로 넘긴다.
새로운 객체는 넘겨받은 책임만 맡으므로 단일 책임 원칙을 지키게 된다.
의존성 관리 맥락에서는 객체는 의존성 자체를 인스턴스로 만드는 책임은 지지 않는다. 대신에 이런 책임을 다른 ‘전담’ 매커니즘에 넘겨야만 한다. (제어의 역전)
초기 설정은 시스템 전체에서 필요하므로 대개 ‘책임질’ 매커니즘으로 ‘main’ 루틴이나 특수 컨테이너를 사용한다.