Skip to content
Sarj Code Standards

prefer-injected-service

Inject a service instead of constructing it from dependencies already available to the consumer.

Why

Hardwired collaborator construction hides its lifetime and prevents callers from substituting the service directly.

Fix

Construct the collaborator at the application's composition boundary with the appropriate lifetime and inject it into the consumer. Do not introduce a global singleton or share request-specific state.

Examples

Before — flagged The consumer hardwires a collaborator using an existing dependency
app/service.py
class Worker:
def __init__(self, store):
self.store = store
def run(self):
return self.store.load()
class Consumer:
def __init__(self, store):
self.store = store
def run(self):
return Worker(self.store).run()
After — preferred The composition boundary supplies the collaborator
app/service.py
class Worker:
def __init__(self, store):
self.store = store
def run(self):
return self.store.load()
class Consumer:
def __init__(self, worker):
self.worker = worker
def run(self):
return self.worker.run()
def compose(store):
return Consumer(Worker(store))