Artykuł · Architektura warstwowa · Architektura heksagonalna
Architektura warstwowa: prezentacja, logika, dane – i gdzie to się psuje
Najstarszy i najpopularniejszy sposób układania aplikacji biznesowych: warstwy ścisłe i luźne, warstwy a fizyczne poziomy, kod w C#, TypeScript, Javie, Go i Pythonie, testy ArchUnit i NetArchTest oraz droga do heksagonu.
Moduł cateringu w pierogarni Haliny – wyceny wesel i komunii – powstał tak, jak uczy większość kursów: kontroler przyjmuje żądanie, serwis liczy cenę, repozytorium czyta menu z bazy. To architektura warstwowa (ang. layered architecture), domyślny układ niemal każdego szablonu projektu. Jest prosta i czytelna, ale ma jedną cechę, która po latach wraca jak bumerang: logika biznesowa zależy od bazy danych.
- 1968
- warstwy w systemie THE – Edsger Dijkstra opisuje system zbudowany z poziomów
- 3
- klasyczne warstwy – prezentacja, domena, źródło danych (Fowler, 2002)
- 80/20
- reguła sinkhole – ok. 20% żądań może tylko przechodzić przez warstwy (Mark Richards)
Kontekst i siły
Catering ma kilka reguł (minimum tydzień wyprzedzenia, rabat od stu gości), ale większość pracy to zwykłe formularze: menu, terminy, dane klienta. Zespół jest mieszany – juniorzy i dwóch seniorów – i potrzebuje struktury, którą każdy zrozumie od pierwszego dnia.
- Rozdzielenie odpowiedzialności – HTML i JSON nie powinny mieszać się z SQL-em i regułami cen.
- Przewidywalność – każdy wie, gdzie szukać walidacji, gdzie reguł, a gdzie zapytań.
- Wymienialność warstw – nowy interfejs (aplikacja mobilna) nie powinien wymagać zmian w logice.
- Koszt – struktura nie może być droższa niż problem, który rozwiązuje.
Struktura
Wzorzec warstw opisali m.in. Buschmann i współautorzy w Pattern-Oriented Software Architecture (1996), a Martin Fowler w Patterns of Enterprise Application Architecture (2002) spopularyzował trzy warstwy: prezentacji, domeny i źródła danych.
| Warstwa | Odpowiedzialność | Nie powinna |
|---|---|---|
| Prezentacja | Przyjęcie żądania, walidacja formatu, mapowanie na DTO, kody HTTP | liczyć cen ani pisać SQL-a |
| Logika biznesowa | Reguły, przypadki użycia, transakcje | znać HttpContext, req, res |
| Dostęp do danych | Zapytania, mapowanie obiektowo-relacyjne, cache | podejmować decyzji biznesowych |
Warstwy a poziomy. Warstwa (layer) to podział logiczny w kodzie, poziom (tier) – fizyczny: osobny proces lub maszyna. Trzy warstwy mogą działać w jednym procesie, a aplikacja trójpoziomowa z lat 90. to przeglądarka, serwer aplikacji i serwer bazy.
Warstwy ścisłe i luźne. W układzie ścisłym (closed) żądanie przechodzi przez każdą warstwę po kolei. W luźnym (open) wybrane warstwy można pominąć – na przykład prosty odczyt idzie z kontrolera prosto do repozytorium. Luźność przyspiesza pisanie, ale rozmywa granice, więc warto ją ograniczać do konkretnych, nazwanych przypadków.
Jak to wygląda w kodzie
Układ warstw w pięciu stosach
Pierogarnia.Catering.sln
├── Catering.Web/ ← PRESENTATION: controllers, view models, validation of input
├── Catering.Business/ ← BUSINESS: CateringService, pricing rules, DTOs
├── Catering.Data/ ← DATA ACCESS: EF Core DbContext, repositories, entities
└── references: Web → Business → Data (each layer knows only the one below)pl.pierogarnia.catering
├── web/ ← @RestController, request/response records
├── service/ ← @Service, @Transactional, business rules
├── repository/ ← Spring Data JPA interfaces
└── entity/ ← @Entity classes (often shared by service and repository)src/
├── controllers/ ← Express routers or NestJS @Controller
├── services/ ← business rules, no req/res objects here
├── repositories/ ← Prisma / TypeORM / Knex queries
└── app.tscatering/
├── cmd/catering/main.go
└── internal/
├── handler/ ← net/http handlers: decode JSON, call service, encode JSON
├── service/ ← business rules
└── repository/ ← database/sql or sqlc queriescatering/
├── api/ ← FastAPI routers (presentation)
├── services/ ← business rules
├── repositories/ ← SQLAlchemy queries
└── models.py ← ORM modelsTen sam przypadek użycia – wycena wesela – przechodzi przez trzy warstwy. Zwróć uwagę, gdzie mieszka reguła rabatu i od czego zależy serwis:
Wycena wesela przez trzy warstwy
// PRESENTATION – Catering.Web
[ApiController, Route("api/catering")]
public sealed class CateringController(CateringService service) : ControllerBase
{
[HttpPost("quotes")]
public async Task<ActionResult<QuoteDto>> Quote(QuoteRequest req, CancellationToken ct) =>
Ok(await service.Quote(req.Guests, req.EventDate, ct));
}
// BUSINESS – Catering.Business
public sealed class CateringService(ICateringRepository repo, TimeProvider clock)
{
public async Task<QuoteDto> Quote(int guests, DateOnly date, CancellationToken ct)
{
if (date < DateOnly.FromDateTime(clock.GetLocalNow().DateTime.AddDays(7)))
throw new BusinessRuleException("Weddings need a week's notice.");
var menu = await repo.GetWeddingMenu(ct);
var perGuest = menu.Sum(i => i.PiecesPerGuest * i.UnitPrice);
var discount = guests >= 100 ? 0.10m : 0m; // the business rule lives here
return new QuoteDto(guests, Math.Round(guests * perGuest * (1 - discount), 2));
}
}
// DATA ACCESS – Catering.Data (the interface is here too: Business references Data)
public interface ICateringRepository { Task<IReadOnlyList<MenuItem>> GetWeddingMenu(CancellationToken ct); }
public sealed class CateringRepository(CateringDb db) : ICateringRepository
{
public async Task<IReadOnlyList<MenuItem>> GetWeddingMenu(CancellationToken ct) =>
await db.MenuItems.Where(m => m.Wedding).ToListAsync(ct);
}// PRESENTATION – controllers/catering.controller.ts
router.post("/api/catering/quotes", async (req, res, next) => {
try {
const { guests, eventDate } = req.body as { guests: number; eventDate: string };
res.json(await cateringService.quote(guests, new Date(eventDate)));
} catch (err) {
next(err); // error middleware turns BusinessRuleError into 422
}
});
// BUSINESS – services/catering.service.ts
export const cateringService = {
async quote(guests: number, eventDate: Date): Promise<Quote> {
const weekAhead = Date.now() + 7 * 24 * 3600 * 1000;
if (eventDate.getTime() < weekAhead) throw new BusinessRuleError("Weddings need a week's notice.");
const menu = await cateringRepository.weddingMenu();
const perGuest = menu.reduce((sum, i) => sum + i.piecesPerGuest * i.unitPrice, 0);
const discount = guests >= 100 ? 0.1 : 0; // the business rule lives here
return { guests, total: Math.round(guests * perGuest * (1 - discount) * 100) / 100 };
},
};
// DATA ACCESS – repositories/catering.repository.ts
export const cateringRepository = {
weddingMenu: () => prisma.menuItem.findMany({ where: { wedding: true } }),
};// PRESENTATION – web/CateringController.java
@RestController
@RequestMapping("/api/catering")
class CateringController {
private final CateringService service;
CateringController(CateringService service) { this.service = service; }
@PostMapping("/quotes")
QuoteDto quote(@RequestBody QuoteRequest req) { return service.quote(req.guests(), req.eventDate()); }
}
// BUSINESS – service/CateringService.java
@Service
class CateringService {
private final MenuItemRepository repo;
private final Clock clock;
CateringService(MenuItemRepository repo, Clock clock) { this.repo = repo; this.clock = clock; }
QuoteDto quote(int guests, LocalDate date) {
if (date.isBefore(LocalDate.now(clock).plusDays(7)))
throw new BusinessRuleException("Weddings need a week's notice.");
var perGuest = repo.findByWeddingTrue().stream()
.map(i -> i.getUnitPrice().multiply(BigDecimal.valueOf(i.getPiecesPerGuest())))
.reduce(BigDecimal.ZERO, BigDecimal::add);
var discount = guests >= 100 ? new BigDecimal("0.90") : BigDecimal.ONE; // the business rule
return new QuoteDto(guests, perGuest.multiply(BigDecimal.valueOf(guests)).multiply(discount));
}
}
// DATA ACCESS – repository/MenuItemRepository.java
interface MenuItemRepository extends JpaRepository<MenuItem, Long> {
List<MenuItem> findByWeddingTrue();
}// PRESENTATION – internal/handler/catering.go
func (h CateringHandler) Quote(w http.ResponseWriter, r *http.Request) {
var req struct {
Guests int `json:"guests"`
EventDate time.Time `json:"eventDate"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
q, err := h.Service.Quote(r.Context(), req.Guests, req.EventDate)
if err != nil {
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
json.NewEncoder(w).Encode(q)
}
// BUSINESS – internal/service/catering.go
func (s CateringService) Quote(ctx context.Context, guests int, date time.Time) (Quote, error) {
if date.Before(s.Now().AddDate(0, 0, 7)) {
return Quote{}, errors.New("weddings need a week's notice")
}
menu, err := s.Repo.WeddingMenu(ctx) // *repository.CateringRepository: business imports data access
if err != nil {
return Quote{}, err
}
perGuest := 0.0
for _, i := range menu {
perGuest += float64(i.PiecesPerGuest) * i.UnitPrice
}
discount := 0.0
if guests >= 100 {
discount = 0.10 // the business rule lives here
}
return Quote{Guests: guests, Total: float64(guests) * perGuest * (1 - discount)}, nil
}# PRESENTATION – catering/api/quotes.py
@router.post("/api/catering/quotes")
def quote(req: QuoteRequest, service: CateringService = Depends(get_catering_service)) -> QuoteDto:
try:
return service.quote(req.guests, req.event_date)
except BusinessRuleError as e:
raise HTTPException(status_code=422, detail=str(e))
# BUSINESS – catering/services/catering.py
class CateringService:
def __init__(self, repo: CateringRepository, today=date.today):
self.repo, self.today = repo, today
def quote(self, guests: int, event_date: date) -> QuoteDto:
if event_date < self.today() + timedelta(days=7):
raise BusinessRuleError("Weddings need a week's notice.")
per_guest = sum(i.pieces_per_guest * i.unit_price for i in self.repo.wedding_menu())
discount = Decimal("0.10") if guests >= 100 else Decimal("0") # the business rule
return QuoteDto(guests=guests, total=round(guests * per_guest * (1 - discount), 2))
# DATA ACCESS – catering/repositories/catering.py
class CateringRepository:
def __init__(self, session: Session):
self.session = session
def wedding_menu(self) -> list[MenuItem]:
return list(self.session.scalars(select(MenuItem).where(MenuItem.wedding.is_(True))))Dalsza część artykułu dla zalogowanych
Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:
- Gdzie to się psuje
- Kompromisy
- Ścieżki ewolucji
- W praktyce
- Antywzorce
- Powiązane tematy
- Sprawdź się