type
concept
created
Tue Apr 07 2026 02:00:00 GMT+0200 (Central European Summer Time)
updated
Tue Apr 07 2026 02:00:00 GMT+0200 (Central European Summer Time)
sources
raw/notes/systemPatterns, raw/notes/techContext, raw/notes/codeGuidelines
tags
service-layer architecture pure-functions testing django design-pattern

Service Layer Pattern

abstract
Business logic lives in `apps//services.py` as pure, stateless functions -- views call services, not the reverse -- enabling clean testing and separation of concerns.

Overview

The Service Layer Pattern is the primary code organization pattern for business logic in the wiki/entities/b2bpaper backend. It was first introduced in the containers app and is intended to be replicated across all apps that contain non-trivial business logic.

The Pattern

Core Principles

  1. Business logic in services.py, not in views or serializers
  2. Services are pure functions -- stateless, testable without HTTP context
  3. Views call services, never the reverse
  4. Services return plain data (dicts, lists, model instances) -- not HTTP responses
  5. Each app gets its own services.py when it has business logic

Code Organization

apps/<app>/
    models.py          # Data definitions
    serializers.py     # API serialization (explicit fields, never __all__)
    views.py           # HTTP layer, calls services
    services.py        # Business logic (pure functions)
    tests/
        test_services/  # Service unit tests
        test_api/       # API integration tests

Why Pure Functions?

Pure functions (stateless, no side effects beyond their explicit purpose) provide several advantages:

Reference Implementation: Containers App

The containers app (apps/containers/services.py) was the first to implement this pattern and serves as the reference for all other apps:

calculate_container_gap()

find_fill_suggestions()

calculate_freight_comparison()

build_fill_proposal()

Scoring System

The container fill scoring rates candidates 0-100:

Pattern Replication

The pattern should be replicated for:

Testing Strategy

The pattern enables a clean two-tier testing approach:

Sources

Related