강한 결합은 서로 다른 클래스들이 서로 크게 의존하는 경우를 말한다.
강한 결합의 예시 코드는 아래와 같다.
export class ProductController {
buyProduct = (req, res) => {
const cashService = new CashService();
const hasMoney = cashService.checkValue();
const productService = new ProductService();
const isSoldout = productService.checkSoldout();
if (hasMoney && !isSoldout) {
// ...
}
};
refundProduct = (req, res) => {
const productService = new ProductService();
const isSoldout = productService.checkSoldout();
if (isSoldout) {
res.send("상품 환불 완료!!");
}
};
}
ProductController 클래스에 선언한 메서드에서 CashService, ProductService의 객체를 직접 생성해 메서드를 호출하는 형태의 코드이다.ProductController 클래스가 CashService, ProductService 클래스를 직접 사용해 생성한 객체에 의존하고 있는 강한 결합 상태이다.강한 결합은 아래와 같은 특징을 갖는다.
느슨한 결합은 강한 결합의 반대 개념으로, 객체들이 서로 결합이 되어 있긴 하지만 강한 결합 상태 보다는 느슨한 상태의 결합이라고 볼 수 있다. 어떤 클래스에서 다른 클래스를 직접적으로 사용하는 클래스 의존성을 줄인 결합 상태를 말한다.
강한 결합 상태의 코드를 느슨한 결합 상태로 만든 예시 코드는 다음과 같다.
// index.js
import express from "express";
import { ProductController } from "./mvc/controllers/product.controller.js";
import { CashService } from "./mvc/controllers/services/cash.service.js";
const app = express();
const cashService = new CashService();
const productController = new ProductController(cashService);
app.post("/products/buy", productController.buyProduct);
index.js에서 CashService 객체를 생성하고, ProductController 객체를 생성할 때 생성자의 인자로 CashService 객체를 전달한다.// product.controller.js
import { ProductService } from './services/product.service.js'
export class ProductController {
constructor(cashService) {
this.cashService = cashService;
}
buyProduct = (req, res) => {
// const cashService = new CashService();
const hasMoney = this.cashService.checkValue();
const productService = new ProductService()
const isSoldout = productService.checkSoldout();
if (hasMoney && !isSoldout) {
res.send("상품을 구매합니다.");
}
};
refundProduct = (req, res) => {
const productService = new ProductService()
const isSoldout = productService.checkSoldout();
if (isSoldout) {
res.send("상품을 환불합니다.");
}
};
}
constructor를 사용해 CashService 객체를 전달 받는다.ProductController와 ProductService는 강한 결합 상태인데, ProductService 객체를 직접 생성해서 사용하고 있기 때문이다.ProductController 클래스는 CashService 의 객체를 직접 생성하지 않는다. ProductController 외부에서 객체를 생성하여 constructor를 통해 안으로 전달하는 형태이다.
Constructor Injection(생성자 주입)을 사용하는 의존성 주입(Dependency Injection)으로 두 클래스를 느슨한 결합 상태로 만든 것이다.
강한 결합은 클래스들이 서로 크게 의존하여 강하게 결합된 상태를 말한다.느슨한 결합은 클래스들이 서로 결합이 되어 있긴 하지만, 강한 결합 상태 보다는 느슨한 상태의 결합이라고 볼 수 있다.강한 결합 상태의 코드는 유지보수가 어렵다.의존성 주입(Dependency Injection, DI)을 통해 강한 결합을 느슨한 결합으로 바꿀 수 있다.