횡단 관심사 처리
의존성 규칙을 위반하거나 핵심 로직을 오염시키지 않고 로깅, 인증, 인가를 구현하는 전략을 익힙니다.
횡단 관심사 처리은(는) CoddyKit의 무료 Clean Architecture & Design Patterns in Practice 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Clean Architecture & Design Patterns in Practice 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Clean Architecture & Design Patterns in Practice 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What are Cross-Cutting Concerns?
In software development, cross-cutting concerns are aspects of a system that affect many parts of the application but are not part of its core business logic. Think of them as system-wide services.
- Logging: Recording events for debugging or auditing.
- Authentication: Verifying a user's identity.
- Authorization: Determining what an authenticated user can do.
- Caching: Storing frequently accessed data for faster retrieval.
- Transaction Management: Ensuring data consistency across multiple operations.
The Clean Architecture Dilemma
Clean Architecture emphasizes keeping your core business logic (Entities and Use Cases) independent of external frameworks and delivery mechanisms. This is enforced by the Dependency Rule: dependencies must only flow inwards.
The challenge arises because cross-cutting concerns often rely on specific external frameworks (e.g., a logging library, a security framework). How can we implement these concerns without violating the Dependency Rule and coupling our core logic to external details?
Logging Without Pollution
Let's take logging as an example. If a CreateUserUseCase directly calls a logging framework like Log4j or SLF4J, it creates a dependency on that specific framework.
CreateUserUseCase → Log4j
This violates the Dependency Rule because the inner layer (Use Case) would depend on an outer layer (Frameworks/Drivers). Our core logic should not care how logs are written, only that they need to be written.
Defining a Logging Port
To solve this, we introduce an interface in our inner (Use Case) layer. This interface, often called an Output Port, defines the contract for logging. The Use Case depends on this abstraction, not a concrete implementation.
package application.ports;
public interface ILogger {
void info(String message);
void error(String message, Throwable t);
}Implementing the Logger Adapter
The actual logging framework implementation lives in an outer layer (e.g., Infrastructure). This concrete class acts as an Adapter, implementing our ILogger port and delegating to the specific logging library.
Notice how ConsoleLogger depends on ILogger (an inner layer abstraction), respecting the Dependency Rule.
package infrastructure.logging;
import application.ports.ILogger; // Depends on inner layer
public class ConsoleLogger implements ILogger {
@Override
public void info(String message) {
System.out.println("[INFO] " + message);
}
@Override
public void error(String message, Throwable t) {
System.err.println("[ERROR] " + message + " - " + t.getMessage());
}
}Logger in a Use Case
Now, our CreateUserUseCase can depend on the ILogger interface. The concrete ConsoleLogger is injected at runtime, typically by a Dependency Injection (DI) container, but we'll do it manually here for clarity.
package application.usecases;
import application.ports.ILogger;
import infrastructure.logging.ConsoleLogger;
public class CreateUserUseCase {
private final ILogger logger;
public CreateUserUseCase(ILogger logger) {
this.logger = logger;
}
public void execute(String username) {
logger.info("Attempting to create user: " + username);
// ... business logic to create user ...
logger.info("User created successfully: " + username);
}
}
public class Main {
public static void main(String[] args) {
// Manual Dependency Injection for demonstration
ILogger consoleLogger = new ConsoleLogger();
CreateUserUseCase useCase = new CreateUserUseCase(consoleLogger);
useCase.execute("Alice");
}
}Handling Authentication
Authentication (verifying who a user is) should occur at the application's entry points, not within the core Use Cases. The Use Case should only receive already authenticated user information.
- Middleware/Filters: In web applications, these intercept requests before they reach controllers.
- Input Port Decorators: You can wrap a Use Case with a decorator that handles authentication before delegating to the actual Use Case.
This ensures the Use Case remains focused on business logic, free from security framework details.
Authorization with Policies
Authorization (what an authenticated user can do) is often more complex. While basic authorization can also be handled at the entry point, more granular checks might involve the Use Case.
- Authorization Policies: Define separate objects or services that encapsulate authorization rules.
- Interceptors/Aspects: Apply these policies around Use Case execution, checking permissions before the core logic runs.
- The Use Case might depend on an
IAuthorizationServiceinterface (another Port) to query specific permissions.
DI for Cross-Cutting Concerns
The overarching principle for handling cross-cutting concerns in Clean Architecture is the Dependency Inversion Principle (DIP).
- High-level modules (Use Cases) should not depend on low-level modules (frameworks).
- Both should depend on abstractions (interfaces).
- Abstractions are defined in the inner layers, and their concrete implementations reside in the outer layers, injected at runtime.
This keeps your core logic clean, testable, and independent of external technologies.
Applying Clean Concerns
Consider a ProcessOrderUseCase that needs to log critical steps. Which approach aligns best with Clean Architecture's Dependency Rule?
Recap: Keeping Core Clean
We've explored strategies to handle cross-cutting concerns like logging, authentication, and authorization within Clean Architecture:
- Abstract Concerns: Define interfaces (Ports) in inner layers for concerns like logging.
- Implement Adapters: Provide concrete implementations of these interfaces in outer layers (Adapters).
- Boundary Handling: Use middleware, decorators, or interceptors at application boundaries for authentication and authorization.
- Dependency Inversion: This principle is crucial for ensuring your core business logic remains clean, independent, and free from external framework details.
자주 묻는 질문
“횡단 관심사 처리” 강의는 무료인가요?
네 — “횡단 관심사 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Clean Architecture & Design Patterns in Practice 강의 전체를 잠금 해제할 수 있습니다. Clean Architecture & Design Patterns in Practice 강의에는 총 4개의 강의가 포함되어 있습니다.
“횡단 관심사 처리”에서 뭘 배우나요?
의존성 규칙을 위반하거나 핵심 로직을 오염시키지 않고 로깅, 인증, 인가를 구현하는 전략을 익힙니다. 브라우저에서 직접 실행하는 실습 코드로 Clean Architecture & Design Patterns in Practice을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Clean Architecture & Design Patterns in Practice을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Clean Architecture & Design Patterns in Practice은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“횡단 관심사 처리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Clean Architecture & Design Patterns in Practice 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Clean Architecture & Design Patterns in Practice 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.