Patterncore
Service layer
Also called Service Layer, application service layer, application layer, application services.
A service layer is the set of operations that an application offers to all its clients. Each operation controls its transaction and coordinates the domain objects.
- Family
- architectural
- Intent
- Define an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation.
Intent
A service layer "Defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation."1 The clients of the application, such as the web pages, the batch loaders and the other systems, call these operations and nothing below them. Randy Stafford wrote the pattern for the book.12
Problem
"Enterprise applications typically require different kinds of interfaces to the data they store and the logic they implement: data loaders, user interfaces, integration gateways, and others."1 These clients do different things, but they need the same operations: "Despite their different purposes, these interfaces often need common interactions with the application to access and manipulate its data and invoke its business logic."1
One operation can do much work. It can start a transaction, change several domain objects, write them, and then send an email or a message. If each client does these steps itself, the steps are copied: "Encoding the logic of the interactions separately in each interface causes a lot of duplication."1 Later, a change goes into some of the copies only, and the clients act differently for the same operation.
Solution
"A Service Layer defines an application's boundary and its set of available operations from the perspective of interfacing client layers."1 Each operation is one method of the layer. The method controls the transaction and coordinates the responses to the operation, such as the email after an order. The business rules stay in the Domain model or in a Transaction script below the layer.
The parts are:
- The service. A class or a module with one method for each operation of the application, such as
place_orderorcancel_booking. - The transaction control. Each operation starts a transaction, and commits it or rolls it back. A client never sees a half-done operation.
- The coordination. The operation calls the domain objects for the rules, the data source for the data, and other resources such as a mailer or a message queue.
- The clients. The web handlers, the loaders and the integration gateways. They change their input into a call of an operation, and change the result into their output.
clients web handler import loader integration gateway
\ | /
service layer place_order() cancel_order() ...
(transaction, coordination of the responses)
| |
domain layer Order, Customer, Product (the business rules)
|
data source database, mailer, message queue
In the following program, transfer is the operation. Two clients call it, and so they get the same checks and the same log.
class Account:
def __init__(self, balance):
self.balance = balance
accounts = {1: Account(100), 2: Account(0)}
log = []
# The service layer: one operation of the application that the clients call.
def transfer(source, target, amount):
a, b = accounts[source], accounts[target]
if a.balance < amount:
return "refused"
a.balance -= amount
b.balance += amount
log.append(f"transfer {amount} from {source} to {target}")
return "done"
print("web client:", transfer(1, 2, 30))
print("batch client:", transfer(1, 2, 90))
print("balances:", accounts[1].balance, accounts[2].balance, "log:", log)
web client: done
batch client: refused
balances: 70 30 log: ['transfer 30 from 1 to 2']
Example
Each example file is a small shop. The domain class Order knows its lines and its discount rule: a gold customer gets 10 percent off an order of 100.00 or more. OrderService.place_order is the operation. It starts a transaction, finds the customer and the products, asks the order to add the lines, and commits. It sends the email only after the commit, so a failed order gets no email. Two clients use the service: a web handler and a loader that imports orders from a file. The second import line names a product that does not exist, so the service rolls back the order, and the last lines show that the store has 2 orders and that 2 emails went out.
class DomainError(Exception):
pass
def cents(n):
return f"{n // 100}.{n % 100:02d}"
# Domain layer: the objects hold the business rules.
class Order:
def __init__(self, number, customer):
self.number = number
self.customer = customer
self.lines = []
def add(self, item, qty, price_cents):
if qty <= 0:
raise DomainError(f"bad quantity {qty}")
self.lines.append((item, qty, price_cents))
def total(self):
subtotal = sum(qty * price for _, qty, price in self.lines)
if self.customer["tier"] == "gold" and subtotal >= 10000:
return subtotal - subtotal // 10
return subtotal
# Data source and other resources, which the service layer coordinates.
class Store:
def __init__(self):
self.customers = {1: {"name": "Ann", "email": "ann@example.com", "tier": "gold"},
2: {"name": "Bob", "email": "bob@example.com", "tier": "regular"}}
self.prices = {"lamp": 2500, "desk": 7500, "pen": 500}
self.orders = {}
self._saved = None
def begin(self):
self._saved = dict(self.orders) # a copy of the map of orders
def commit(self):
self._saved = None
def rollback(self):
self.orders = self._saved
class Mailer:
def __init__(self):
self.sent = []
def send(self, to, text):
self.sent.append(f"{to}: {text}")
# Service layer: the operations of the application, with the transaction and the
# coordination of the responses in one place.
class OrderService:
def __init__(self, store, mailer):
self.store = store
self.mailer = mailer
def place_order(self, customer_id, items):
self.store.begin()
try:
customer = self.store.customers.get(customer_id)
if customer is None:
raise DomainError(f"no customer {customer_id}")
order = Order(len(self.store.orders) + 1, customer)
self.store.orders[order.number] = order
for item, qty in items:
if item not in self.store.prices:
raise DomainError(f"no product {item}")
order.add(item, qty, self.store.prices[item])
self.store.commit()
except DomainError:
self.store.rollback()
raise
# Only a committed order gets an email.
self.mailer.send(customer["email"], f"order {order.number}, total {cents(order.total())}")
return order.number, customer["name"], order.total()
store, mailer = Store(), Mailer()
service = OrderService(store, mailer)
# Client 1: a web handler.
number, name, total = service.place_order(1, [("lamp", 2), ("desk", 1)])
print(f"web: placed order {number} for {name}, total {cents(total)}")
# Client 2: a loader that imports orders from a file.
for line_no, (customer_id, items) in enumerate([(2, [("lamp", 1), ("pen", 3)]), (2, [("pen", 1), ("chair", 1)])], 1):
try:
number, name, total = service.place_order(customer_id, items)
print(f"import line {line_no}: placed order {number} for {name}, total {cents(total)}")
except DomainError as e:
print(f"import line {line_no}: refused: {e}")
print("orders stored:", len(store.orders))
for message in mailer.sent:
print("email", message)
web: placed order 1 for Ann, total 112.50
import line 1: placed order 2 for Bob, total 40.00
import line 2: refused: no product chair
orders stored: 2
email ann@example.com: order 1, total 112.50
email bob@example.com: order 2, total 40.00
- Verdict: idiom.
OrderServiceis a plain class, andplace_orderis one operation of the application. It opens the transaction, asks the domain objects to do the work, commits, and then sends the email. The two clients only call the service and report the result. - The store keeps a copy of its map of orders at
beginand puts it back atrollback. A real service would use a database transaction instead, for examplewith connection:insqlite3.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Main {
static class DomainError extends RuntimeException {
DomainError(String message) { super(message); }
}
static String cents(long n) {
return String.format("%d.%02d", n / 100, n % 100);
}
record Customer(String name, String email, String tier) {}
record Line(String item, int qty, long priceCents) {}
record Item(String name, int qty) {}
record Placed(int number, String customer, long total) {}
// Domain layer: the objects hold the business rules.
static class Order {
final int number;
final Customer customer;
final List<Line> lines = new ArrayList<>();
Order(int number, Customer customer) {
this.number = number;
this.customer = customer;
}
void add(String item, int qty, long priceCents) {
if (qty <= 0) throw new DomainError("bad quantity " + qty);
lines.add(new Line(item, qty, priceCents));
}
long total() {
long subtotal = lines.stream().mapToLong(l -> l.qty() * l.priceCents()).sum();
if (customer.tier().equals("gold") && subtotal >= 10000) return subtotal - subtotal / 10;
return subtotal;
}
}
// Data source and other resources, which the service layer coordinates.
static class Store {
final Map<Integer, Customer> customers = Map.of(
1, new Customer("Ann", "ann@example.com", "gold"),
2, new Customer("Bob", "bob@example.com", "regular"));
final Map<String, Long> prices = Map.of("lamp", 2500L, "desk", 7500L, "pen", 500L);
Map<Integer, Order> orders = new LinkedHashMap<>();
private Map<Integer, Order> saved;
void begin() { saved = new LinkedHashMap<>(orders); } // a copy of the map of orders
void commit() { saved = null; }
void rollback() { orders = saved; }
}
static class Mailer {
final List<String> sent = new ArrayList<>();
void send(String to, String text) { sent.add(to + ": " + text); }
}
// Service layer: the operations of the application, with the transaction and the
// coordination of the responses in one place.
static class OrderService {
private final Store store;
private final Mailer mailer;
OrderService(Store store, Mailer mailer) {
this.store = store;
this.mailer = mailer;
}
Placed placeOrder(int customerId, List<Item> items) {
store.begin();
Customer customer;
Order order;
try {
customer = store.customers.get(customerId);
if (customer == null) throw new DomainError("no customer " + customerId);
order = new Order(store.orders.size() + 1, customer);
store.orders.put(order.number, order);
for (Item item : items) {
Long price = store.prices.get(item.name());
if (price == null) throw new DomainError("no product " + item.name());
order.add(item.name(), item.qty(), price);
}
store.commit();
} catch (DomainError e) {
store.rollback();
throw e;
}
// Only a committed order gets an email.
mailer.send(customer.email(), "order " + order.number + ", total " + cents(order.total()));
return new Placed(order.number, customer.name(), order.total());
}
}
public static void main(String[] args) {
Store store = new Store();
Mailer mailer = new Mailer();
OrderService service = new OrderService(store, mailer);
// Client 1: a web handler.
Placed p = service.placeOrder(1, List.of(new Item("lamp", 2), new Item("desk", 1)));
System.out.println("web: placed order " + p.number() + " for " + p.customer() + ", total " + cents(p.total()));
// Client 2: a loader that imports orders from a file.
List<List<Item>> rows = List.of(
List.of(new Item("lamp", 1), new Item("pen", 3)),
List.of(new Item("pen", 1), new Item("chair", 1)));
for (int i = 0; i < rows.size(); i++) {
try {
Placed q = service.placeOrder(2, rows.get(i));
System.out.println("import line " + (i + 1) + ": placed order " + q.number() + " for " + q.customer()
+ ", total " + cents(q.total()));
} catch (DomainError e) {
System.out.println("import line " + (i + 1) + ": refused: " + e.getMessage());
}
}
System.out.println("orders stored: " + store.orders.size());
for (String message : mailer.sent) System.out.println("email " + message);
}
}
web: placed order 1 for Ann, total 112.50
import line 1: placed order 2 for Bob, total 40.00
import line 2: refused: no product chair
orders stored: 2
email ann@example.com: order 1, total 112.50
email bob@example.com: order 2, total 40.00
- Verdict: idiom.
OrderServiceis a class with one method for each operation. In a Spring application, the class would have the@Serviceannotation, and@Transactionalon the method would replace the calls tobegin,commitandrollback. DomainErroris unchecked, soplaceOrderdoes not declare it. The service catches it only to roll back, and then throws it again to the client.
class DomainError extends Error {}
const cents = (n) => `${Math.floor(n / 100)}.${String(n % 100).padStart(2, "0")}`;
// Domain layer: the objects hold the business rules.
class Order {
constructor(number, customer) { this.number = number; this.customer = customer; this.lines = []; }
add(item, qty, priceCents) {
if (qty <= 0) throw new DomainError(`bad quantity ${qty}`);
this.lines.push([item, qty, priceCents]);
}
total() {
const subtotal = this.lines.reduce((s, [, qty, price]) => s + qty * price, 0);
if (this.customer.tier === "gold" && subtotal >= 10000) return subtotal - Math.floor(subtotal / 10);
return subtotal;
}
}
// Data source and other resources, which the service layer coordinates.
class Store {
constructor() {
this.customers = new Map([
[1, { name: "Ann", email: "ann@example.com", tier: "gold" }],
[2, { name: "Bob", email: "bob@example.com", tier: "regular" }],
]);
this.prices = new Map([["lamp", 2500], ["desk", 7500], ["pen", 500]]);
this.orders = new Map();
this.saved = null;
}
begin() { this.saved = new Map(this.orders); } // a copy of the map of orders
commit() { this.saved = null; }
rollback() { this.orders = this.saved; }
}
class Mailer {
constructor() { this.sent = []; }
send(to, text) { this.sent.push(`${to}: ${text}`); }
}
// Service layer: the operations of the application, with the transaction and the
// coordination of the responses in one place.
class OrderService {
constructor(store, mailer) { this.store = store; this.mailer = mailer; }
placeOrder(customerId, items) {
this.store.begin();
let customer, order;
try {
customer = this.store.customers.get(customerId);
if (!customer) throw new DomainError(`no customer ${customerId}`);
order = new Order(this.store.orders.size + 1, customer);
this.store.orders.set(order.number, order);
for (const [item, qty] of items) {
if (!this.store.prices.has(item)) throw new DomainError(`no product ${item}`);
order.add(item, qty, this.store.prices.get(item));
}
this.store.commit();
} catch (e) {
this.store.rollback();
throw e;
}
// Only a committed order gets an email.
this.mailer.send(customer.email, `order ${order.number}, total ${cents(order.total())}`);
return [order.number, customer.name, order.total()];
}
}
const store = new Store(), mailer = new Mailer();
const service = new OrderService(store, mailer);
// Client 1: a web handler.
const [number, name, total] = service.placeOrder(1, [["lamp", 2], ["desk", 1]]);
console.log(`web: placed order ${number} for ${name}, total ${cents(total)}`);
// Client 2: a loader that imports orders from a file.
const rows = [[2, [["lamp", 1], ["pen", 3]]], [2, [["pen", 1], ["chair", 1]]]];
rows.forEach(([customerId, items], i) => {
try {
const [n, who, t] = service.placeOrder(customerId, items);
console.log(`import line ${i + 1}: placed order ${n} for ${who}, total ${cents(t)}`);
} catch (e) {
if (!(e instanceof DomainError)) throw e;
console.log(`import line ${i + 1}: refused: ${e.message}`);
}
});
console.log("orders stored:", store.orders.size);
for (const message of mailer.sent) console.log("email", message);
web: placed order 1 for Ann, total 112.50
import line 1: placed order 2 for Bob, total 40.00
import line 2: refused: no product chair
orders stored: 2
email ann@example.com: order 1, total 112.50
email bob@example.com: order 2, total 40.00
- Verdict: idiom.
OrderServiceis a class with one method for each operation. The method usestryandcatchto roll back on any error and then throws the error again, so the client still sees it. DomainErroris a subclass ofError. The import client usesinstanceofto report the errors that the user can correct and lets the other errors go up.
package main
import (
"errors"
"fmt"
"maps"
)
type domainError struct{ msg string }
func (e *domainError) Error() string { return e.msg }
func fail(format string, args ...any) error { return &domainError{fmt.Sprintf(format, args...)} }
func cents(n int) string { return fmt.Sprintf("%d.%02d", n/100, n%100) }
type customer struct{ name, email, tier string }
type line struct {
item string
qty, price int
}
type item struct {
name string
qty int
}
// Order is the domain layer: it holds the business rules.
type Order struct {
number int
customer customer
lines []line
}
func (o *Order) Add(name string, qty, price int) error {
if qty <= 0 {
return fail("bad quantity %d", qty)
}
o.lines = append(o.lines, line{name, qty, price})
return nil
}
func (o *Order) Total() int {
subtotal := 0
for _, l := range o.lines {
subtotal += l.qty * l.price
}
if o.customer.tier == "gold" && subtotal >= 10000 {
return subtotal - subtotal/10
}
return subtotal
}
// Store is the data source, which the service layer coordinates.
type Store struct {
customers map[int]customer
prices map[string]int
orders map[int]*Order
saved map[int]*Order
}
func (s *Store) Begin() { s.saved = maps.Clone(s.orders) } // a copy of the map of orders
func (s *Store) Commit() { s.saved = nil }
func (s *Store) Rollback() { s.orders = s.saved }
type Mailer struct{ sent []string }
func (m *Mailer) Send(to, text string) { m.sent = append(m.sent, to+": "+text) }
// OrderService is the service layer: the operations of the application, with the
// transaction and the coordination of the responses in one place.
type OrderService struct {
store *Store
mailer *Mailer
}
func (s *OrderService) PlaceOrder(customerID int, items []item) (*Order, error) {
s.store.Begin()
order, err := s.build(customerID, items)
if err != nil {
s.store.Rollback()
return nil, err
}
s.store.Commit()
// Only a committed order gets an email.
s.mailer.Send(order.customer.email, fmt.Sprintf("order %d, total %s", order.number, cents(order.Total())))
return order, nil
}
func (s *OrderService) build(customerID int, items []item) (*Order, error) {
c, ok := s.store.customers[customerID]
if !ok {
return nil, fail("no customer %d", customerID)
}
order := &Order{number: len(s.store.orders) + 1, customer: c}
s.store.orders[order.number] = order
for _, it := range items {
price, ok := s.store.prices[it.name]
if !ok {
return nil, fail("no product %s", it.name)
}
if err := order.Add(it.name, it.qty, price); err != nil {
return nil, err
}
}
return order, nil
}
func main() {
store := &Store{
customers: map[int]customer{1: {"Ann", "ann@example.com", "gold"}, 2: {"Bob", "bob@example.com", "regular"}},
prices: map[string]int{"lamp": 2500, "desk": 7500, "pen": 500},
orders: map[int]*Order{},
}
mailer := &Mailer{}
service := &OrderService{store, mailer}
// Client 1: a web handler.
o, _ := service.PlaceOrder(1, []item{{"lamp", 2}, {"desk", 1}})
fmt.Printf("web: placed order %d for %s, total %s\n", o.number, o.customer.name, cents(o.Total()))
// Client 2: a loader that imports orders from a file.
rows := [][]item{{{"lamp", 1}, {"pen", 3}}, {{"pen", 1}, {"chair", 1}}}
for i, items := range rows {
o, err := service.PlaceOrder(2, items)
var de *domainError
switch {
case errors.As(err, &de):
fmt.Printf("import line %d: refused: %s\n", i+1, de)
case err == nil:
fmt.Printf("import line %d: placed order %d for %s, total %s\n", i+1, o.number, o.customer.name, cents(o.Total()))
}
}
fmt.Println("orders stored:", len(store.orders))
for _, m := range mailer.sent {
fmt.Println("email", m)
}
}
web: placed order 1 for Ann, total 112.50
import line 1: placed order 2 for Bob, total 40.00
import line 2: refused: no product chair
orders stored: 2
email ann@example.com: order 1, total 112.50
email bob@example.com: order 2, total 40.00
- Verdict: idiom.
OrderServiceis a struct with one method for each operation.PlaceOrdercallsbuildfor the work and decides from its error whether to commit or roll back. In a Go service,buildwould take a*sql.Tx. domainErrormarks the errors that the user can correct, and the import client finds them witherrors.As.maps.Clonemakes the copy of the map of orders.
use std::collections::BTreeMap;
use std::fmt;
#[derive(Debug)]
struct DomainError(String);
impl fmt::Display for DomainError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
fn cents(n: i64) -> String {
format!("{}.{:02}", n / 100, n % 100)
}
#[derive(Clone)]
struct Customer {
name: &'static str,
email: &'static str,
tier: &'static str,
}
// Domain layer: the objects hold the business rules.
#[derive(Clone)]
struct Order {
number: usize,
customer: Customer,
lines: Vec<(&'static str, i64, i64)>,
}
impl Order {
fn add(&mut self, item: &'static str, qty: i64, price_cents: i64) -> Result<(), DomainError> {
if qty <= 0 {
return Err(DomainError(format!("bad quantity {}", qty)));
}
self.lines.push((item, qty, price_cents));
Ok(())
}
fn total(&self) -> i64 {
let subtotal: i64 = self.lines.iter().map(|&(_, qty, price)| qty * price).sum();
if self.customer.tier == "gold" && subtotal >= 10000 {
subtotal - subtotal / 10
} else {
subtotal
}
}
}
// Data source and other resources, which the service layer coordinates.
struct Store {
customers: BTreeMap<u32, Customer>,
prices: BTreeMap<&'static str, i64>,
orders: BTreeMap<usize, Order>,
saved: Option<BTreeMap<usize, Order>>,
}
impl Store {
fn begin(&mut self) {
self.saved = Some(self.orders.clone()); // a copy of the map of orders
}
fn commit(&mut self) {
self.saved = None;
}
fn rollback(&mut self) {
if let Some(saved) = self.saved.take() {
self.orders = saved;
}
}
}
struct Mailer {
sent: Vec<String>,
}
// Service layer: the operations of the application, with the transaction and the
// coordination of the responses in one place.
struct OrderService {
store: Store,
mailer: Mailer,
}
impl OrderService {
fn place_order(&mut self, customer_id: u32, items: &[(&'static str, i64)]) -> Result<Order, DomainError> {
self.store.begin();
match self.build(customer_id, items) {
Ok(order) => {
self.store.commit();
// Only a committed order gets an email.
let text = format!("order {}, total {}", order.number, cents(order.total()));
self.mailer.sent.push(format!("{}: {}", order.customer.email, text));
Ok(order)
}
Err(e) => {
self.store.rollback();
Err(e)
}
}
}
fn build(&mut self, customer_id: u32, items: &[(&'static str, i64)]) -> Result<Order, DomainError> {
let customer = match self.store.customers.get(&customer_id) {
Some(c) => c.clone(),
None => return Err(DomainError(format!("no customer {}", customer_id))),
};
let mut order = Order { number: self.store.orders.len() + 1, customer, lines: Vec::new() };
for &(item, qty) in items {
let price = *self
.store
.prices
.get(item)
.ok_or_else(|| DomainError(format!("no product {}", item)))?;
order.add(item, qty, price)?;
}
self.store.orders.insert(order.number, order.clone());
Ok(order)
}
}
fn main() {
let store = Store {
customers: BTreeMap::from([
(1, Customer { name: "Ann", email: "ann@example.com", tier: "gold" }),
(2, Customer { name: "Bob", email: "bob@example.com", tier: "regular" }),
]),
prices: BTreeMap::from([("lamp", 2500), ("desk", 7500), ("pen", 500)]),
orders: BTreeMap::new(),
saved: None,
};
let mut service = OrderService { store, mailer: Mailer { sent: Vec::new() } };
// Client 1: a web handler.
let o = service.place_order(1, &[("lamp", 2), ("desk", 1)]).unwrap();
println!("web: placed order {} for {}, total {}", o.number, o.customer.name, cents(o.total()));
// Client 2: a loader that imports orders from a file.
let rows: [&[(&'static str, i64)]; 2] = [&[("lamp", 1), ("pen", 3)], &[("pen", 1), ("chair", 1)]];
for (i, items) in rows.iter().enumerate() {
match service.place_order(2, items) {
Ok(o) => println!(
"import line {}: placed order {} for {}, total {}",
i + 1,
o.number,
o.customer.name,
cents(o.total())
),
Err(e) => println!("import line {}: refused: {}", i + 1, e),
}
}
println!("orders stored: {}", service.store.orders.len());
for m in &service.mailer.sent {
println!("email {}", m);
}
}
web: placed order 1 for Ann, total 112.50
import line 1: placed order 2 for Bob, total 40.00
import line 2: refused: no product chair
orders stored: 2
email ann@example.com: order 1, total 112.50
email bob@example.com: order 2, total 40.00
- Verdict: idiom.
OrderServiceowns the store and the mailer, andplace_ordertakes&mut self, because it writes. Thematchon the result ofbuildis the one place that decides to commit or roll back. builduses the?operator, so the first error ends the operation. The order goes into the store only at the end ofbuild, after all the items are correct.
Consequences
Benefits.
- One place for each operation. All the clients use the same code for an operation, so a change to the transaction or to the responses goes into one place.
- A clear boundary. The layer is the list of things that the application can do. This list is the place to check the permissions and the input, and a good start for a Remote facade.
- Clear transactions. Each operation is one transaction, so the limits of the transactions are easy to see. In Spring, the
@Transactionalannotation "specifies that an interface, class, or method must have transactional semantics",3 and it is often put on the service classes. - Clients that are easy to change. A new client, such as a command line tool, needs only to call the operations.
Liabilities.
Without the layer, the clients drift apart. In the following program, each client places the order itself. The web client sends the email, but the import client was written later, and its author did not know about the email.
This code runs but gives a wrong answer on purpose.
orders, emails = [], []
# Wrong: no service layer. Each client places the order and sends the email itself.
def web_place_order(customer, total):
orders.append((customer, total))
emails.append(customer)
def import_place_order(customer, total):
orders.append((customer, total))
# The import client was written later, and its author did not know about the email.
web_place_order("ann@example.com", 112)
import_place_order("bob@example.com", 40)
print("orders:", len(orders), "emails:", len(emails))
print("no email for:", [c for c, _ in orders if c not in emails])
orders: 2 emails: 1
no email for: ['bob@example.com']
Move the steps into one operation of the service layer, and let the two clients call it.
A layer that is too thick. The layer can take the business rules from the domain objects. Fowler writes that "the more behavior you find in the services, the more likely you are to be robbing yourself of the benefits of a domain model."4 Keep the rules in the domain objects, and keep the service for the transaction and the coordination.
One more layer. The layer adds classes and calls. An application with one client and simple operations may not need it.
When not to use it
When the application has one client. If only one user interface uses the logic, and its operations do not need transactions across many resources, the extra layer gives little. The calls can go from the client to the domain objects.
When the operations are only reads and writes of one table. A layer that only passes each call to a Table Data Gateway or a repository adds code and gives nothing.
Variants and related patterns
Domain facade. The service is a thin set of methods that pass each call to the domain objects. The rules stay in the Domain model.2
Operation script. The service holds the logic of each operation, as a set of Transaction script procedures, and calls the domain objects only for the simple rules.2
The application layer. Eric Evans names the same layer the application layer. In the words of Evans, quoted by Fowler, "This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down."4
Related patterns. A service layer is a Facade pattern for the whole application. A Remote facade puts a coarse-grained remote interface on the layer, and a Data transfer object carries the data of each call. An operation often uses a Unit of Work to write all its changes in one transaction. The layer is a way to keep Separation of concerns between the clients and the domain logic.
Known uses
- Spring applications. The
@Serviceannotation marks a service class, and the Javadoc says that the annotation "is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate."5 The service classes often have@Transactional, as in the example classDefaultFooServiceof the Spring reference.3 - Applications that follow Domain-Driven Design, where the application layer coordinates the domain objects for each task.4
References
- Randy Stafford, Catalog of Patterns of Enterprise Application Architecture, Service Layer, pattern summary
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 9, Domain Logic Patterns, Service Layer
- Spring Framework reference, Using @Transactional, introduction and @Transactional Settings
- Martin Fowler, Anemic Domain Model, 25 November 2003, the part on the Service Layer and the application layer
- Spring Framework API, Annotation Interface Service, description
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag Z57N8A Edit this page History Report an error Markdown