결합도 응집도

React최적화

결합도(Coupling)와 응집도(Cohesion)

소프트웨어 설계에서 **결합도(Coupling)**와 **응집도(Cohesion)**는 시스템의 모듈 간 관계를 설명하는 두 가지 중요한 개념입니다. 높은 응집도는 유지하되 결합도를 낮추는 것이 좋은 설계의 핵심입니다. 아래는 React, TypeScript, JavaScript를 활용한 예시입니다.

1. 결합도(Coupling)

결합도는 모듈 간의 의존성을 나타냅니다. 결합도가 높으면 모듈들이 강하게 연결되어 있어 변경하기 어렵고, 결합도가 낮으면 모듈 간의 독립성이 높아져 변경과 재사용이 용이합니다.

  • 결합도가 높은 예시 (Bad Example)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import UserService from './services/UserService'; const UserProfile = () => { const user = UserService.getUser(); // UserService에 강하게 결합 return ( <div> <h1>{user.name}</h1> <p>{user.email}</p> </div> ); }; export default UserProfile;

위 예시에서 UserProfile 컴포넌트는 UserService에 직접적으로 의존하고 있기 때문에 결합도가 높습니다. 만약 UserService의 구현이 변경되면 UserProfile도 변경해야 합니다.

  • 결합도를 낮춘 예시 (Good Example)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // UserProfile이 UserService를 props로 받도록 개선 interface User { name: string; email: string; } interface UserProfileProps { user: User; } const UserProfile = ({ user }: UserProfileProps) => ( <div> <h1>{user.name}</h1> <p>{user.email}</p> </div> ); export default UserProfile; // UserService에서 데이터를 가져오는 로직을 분리 import UserProfile from './UserProfile'; import UserService from './services/UserService'; const App = () => { const user = UserService.getUser(); // 여기서만 UserService에 의존 return <UserProfile user={user} />; }; export default App;

이 방식으로 UserProfile은 UserService에 의존하지 않고, props로 user 데이터를 받기 때문에 결합도가 낮아졌습니다. 이제 UserProfile은 다양한 사용자 데이터를 받을 수 있어 재사용성이 높아집니다.


2. 응집도(Cohesion)

응집도는 모듈 내에서 기능들이 얼마나 밀접하게 관련되어 있는지를 나타냅니다. 응집도가 높으면 모듈 내의 기능들이 하나의 목적을 위해 함께 동작하며, 유지보수성이 높아집니다.

  • 응집도가 낮은 예시 (Bad Example)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // 한 컴포넌트에서 여러 책임을 다루는 경우 (응집도가 낮음) const UserProfile = ({ user, isLoggedIn }: { user: any; isLoggedIn: boolean }) => { const handleLogout = () => { // 로그아웃 처리 로직 console.log('Logged out'); }; return ( <div> <h1>{user.name}</h1> <p>{user.email}</p> {isLoggedIn && <button onClick={handleLogout}>Logout</button>} </div> ); }; export default UserProfile;

위 예시는 UserProfile 컴포넌트가 사용자 정보를 표시하는 책임 외에 로그아웃 로직까지 처리하고 있어, 응집도가 낮습니다.

  • 응집도가 높은 예시 (Good Example)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 const UserProfile = ({ user }: { user: any }) => ( <div> <h1>{user.name}</h1> <p>{user.email}</p> </div> ); const LogoutButton = ({ onLogout }: { onLogout: () => void }) => ( <button onClick={onLogout}>Logout</button> ); const App = () => { const user = { name: 'John', email: 'john@example.com' }; const handleLogout = () => { console.log('Logged out'); }; return ( <div> <UserProfile user={user} /> <LogoutButton onLogout={handleLogout} /> </div> ); }; export default App;

위 예시에서는 UserProfile과 LogoutButton의 책임을 분리하여 각 컴포넌트가 하나의 명확한 역할만 수행하게 하였습니다. 이를 통해 응집도가 높아졌으며, 유지보수와 테스트가 용이해졌습니다.

결론 결합도(Coupling): 모듈 간의 의존성을 줄여 변경에 유연하게 대처할 수 있게 하는 것이 중요합니다. 응집도(Cohesion): 모듈 내에서 관련된 기능들이 밀접하게 연관되어 있을수록 유지보수성과 가독성이 높아집니다.