Skip to Content

Architecture / practical course

Make every abstraction earn its place.

Learn to recognize recurring design problems, choose a fitting pattern, and apply it in the shape of an Odoo module you can explain and maintain.

Current price$ 95.00Price and available payment options are confirmed on the product page.
Design Patterns for Odoo Mastery visual overviewFIELD NOTES / Design Patterns for Odoo Mastery
01Understand the work

Begin with a real goal, the people involved, and the constraints around the system.

02Make the reasoning visible

Connect concepts to decisions, tradeoffs, and behaviors you can inspect.

03Leave with a next step

Use what you learn to choose, build, or plan the next useful action.

A thoughtful guide to the work, the decisions behind it, and how to tell whether the next step is right for you.

01

The real problem patterns solve

Odoo work rarely begins with a blank canvas. A project grows from business rules, existing records, installed modules, integrations, scheduled work, and people who need the system to behave consistently. As the number of responsibilities grows, a method that once felt straightforward can become difficult to change safely. Design patterns give names to recurring ways of organizing those responsibilities. The name is useful only when it helps you see the forces in the problem: what varies, what must remain stable, which object owns a decision, and where a boundary belongs. This course treats patterns as tools for reasoning rather than templates to paste into every module.

02

Start with the pressure, not the pattern name

A sound design begins with an observable pressure. Perhaps two payment providers need similar operations but different request formats. Perhaps a notification must be sent to several destinations without making the business model depend on every destination. Perhaps a workflow has a number of legitimate states and transition rules. Write down the behavior users need, the behavior that changes, and the behavior that must be protected. Only then compare possible structures. A pattern should reduce a specific kind of coupling or make an important variation explicit. If it adds more concepts than it removes, a smaller design is probably better.

03

Reading an Odoo module as a set of responsibilities

Models describe business records and the rules that make those records valid. Methods express operations and transitions. Views present a usable interface. Access controls define who may inspect or change data. Controllers adapt incoming web requests to application behavior. Jobs and integrations move work across time or system boundaries. These concerns interact, but they do not all need to be owned by the same object. When reviewing a module, trace one user goal through its route: which record is read, which rule is checked, which collaborator performs an external action, and how success or failure becomes visible? That concrete path is a better starting point than an abstract diagram alone.

04

Factory Method: isolate a choice that varies

A factory is useful when a caller should request a capability without knowing the concrete class that will provide it. In an integration module, for example, a stable service interface may be paired with provider-specific adapters selected from configuration. The caller can ask for the configured provider and work against the agreed interface. In Odoo, the simplest version may be a small mapping and constructor in a service layer; it does not automatically need a deep hierarchy. Keep validation close to the configuration boundary. Make unsupported choices fail with an actionable error rather than silently selecting a surprising default.

05

Adapter: translate at the system boundary

External systems use their own naming, payload shape, error conventions, and timing expectations. An adapter converts that outside contract into the vocabulary your module uses. The domain logic can then reason about a normalized result instead of scattering provider-specific keys throughout models and controllers. A good adapter makes the conversion visible and testable: it maps identifiers, normalizes dates and amounts, distinguishes a rejected request from a temporary connection failure, and preserves enough context to diagnose a problem. It should not conceal business policy. Whether an order is eligible for fulfillment remains a domain decision, even if an adapter retrieves the provider response.

06

Observer: announce a fact without centralizing every reaction

Events and notifications are useful when one meaningful change has several independent consequences. A completed payment might update an order, trigger fulfillment, and send a receipt. The design question is not whether every action should become an event. It is whether the producer can state a stable fact while consumers respond without the producer owning their implementation details. In Odoo, transaction boundaries, retry behavior, and queue semantics matter. Decide what happens when a subscriber fails, whether the work is synchronous, and how duplicate delivery is handled. Document the event meaning; do not use vague messages such as “something changed” when downstream code needs a precise business fact.

07

Strategy: swap an algorithm behind a stable operation

Sometimes the operation remains stable while the policy varies. A pricing rule, allocation method, or risk calculation can be represented as a set of strategies when callers should apply one of several explicit algorithms. The choice may depend on company, product, date, or configuration. Keep the selection criteria readable and make it possible to identify which strategy ran. A small number of clear branches can be superior to a class per branch. Use a strategy boundary when it makes variation local and gives the algorithms a meaningful shared contract.

08

Command: represent a request that has a lifecycle

A command packages an intended operation so it can be validated, queued, retried, audited, or presented for confirmation. It is helpful when the request is more than a direct method call: perhaps it has parameters, authorization requirements, a result, and a failure state. In an Odoo workflow, a wizard can represent user intent while a service performs the operation. Keep command handling honest about transaction boundaries and idempotency. A retry must not create duplicate records or repeat an irreversible external action without a safeguard.

09

State: make allowed transitions explicit

Status fields often begin as labels and later accumulate rules: a submitted request may be approved or rejected; an approved request may be fulfilled; a fulfilled request may not be edited in the same way as a draft. A state-oriented design asks which transitions are legal, who can request them, and what side effects occur. Put transition checks where all entry points share them. A button is not a security boundary. Validate access rights, record rules, and business conditions on the server. Keep the state graph small enough that a maintainer can reason about it.

10

Composition before inheritance

Odoo uses inheritance extensively, but every inherited model extends an existing contract and can affect other installed modules. Use inheritance when the new behavior is genuinely part of that model’s responsibility and the framework extension point is appropriate. Use composition or a focused service when a capability can stand on its own. Before overriding a method, read its callers and the expected extension behavior. Preserve cooperative calls where required, and avoid a broad override that accidentally blocks another addon from participating.

11

A worked design review

Imagine a service that sends an order update to either Provider North or Provider South. First define the stable business operation: send an update for a particular order and return a normalized outcome. Second, list the provider differences: endpoint, authentication, payload format, and error codes. Third, place translation in adapters. Fourth, make the selection policy explicit and validate its configuration. Fifth, decide whether the call belongs in the user transaction or in a queued job. Finally, surface failures with enough context for an operator to retry safely. This design may use a factory and adapters, but those names follow from the responsibilities rather than dictate them.

12

Reviewing a pattern in an existing codebase

Begin by describing the current behavior in one sentence and identifying the records and callers involved. Follow the path from interface to method to persistence or external effect. Mark the places where the same rule appears more than once, where one object knows details it should not need, and where a change to one concern forces unrelated edits. Do not refactor only because a familiar pattern is absent. Write a small change that proves the intended boundary, inspect its effect on inheritance and security, and verify the behavior at the owning interface.

13

A practical decision checklist

Before introducing a pattern, ask: What concrete variation or coupling does it address? Which object owns the business decision? Is this behavior synchronous, queued, or external? What must be true before the operation begins? What should a user or operator see after failure? Can this boundary be explained in a short paragraph? Does the abstraction make the next likely change easier? If these questions have no specific answers, keep the implementation direct and revisit the design when the pressure becomes real.

14

Who this course is for

The material is aimed at developers who already read Python classes and have begun working with Odoo modules. It is especially relevant when a codebase has multiple providers, repeated workflow logic, extensions from several addons, or responsibilities that are difficult to test independently. New programmers can still benefit, but should first become comfortable with functions, objects, imports, and the basic Odoo request and model lifecycle. The goal is not to collect pattern vocabulary; it is to make changes with a clear explanation of why the chosen structure fits.

15

What to do after studying

Choose one modest feature from a project you understand. Describe the user-visible behavior, list the rules that must hold, and trace its current implementation. Identify one likely source of change. Sketch the simplest design that keeps that change local. Implement the smallest boundary that clarifies the responsibility, then review access, errors, persistence, and extension behavior. Record what became easier and what new complexity appeared. That comparison is the evidence that the pattern helped.

16

A learning route through the pattern families

A useful way to study patterns is to move from the reason a family exists to the tradeoffs of a specific member. Creational patterns deal with the decision of which object to construct and how to assemble it. Structural patterns deal with how existing objects fit together. Behavioral patterns deal with how responsibility and communication move through a system. This is a map, not a ranking. An adapter may matter more to a small integration than every creational pattern combined, and a clear state transition may matter more than a sophisticated event network.

For each pattern, keep a short note with five parts: the pressure that prompted it, the participants, the collaboration between those participants, the benefit you expect, and the cost you accept. For a factory, the pressure might be provider selection. The participants could be a configuration reader, a factory, and two adapters. The benefit is that business code calls a stable interface. The cost is another indirection and a need to keep provider configuration valid. This note prevents a pattern name from becoming an unexplained badge on a diagram.

Odoo’s module model adds practical questions to the map. Will the design be extended by another installed addon? Does it need to preserve batch behavior for recordsets? Does the interface need to be available to a scheduled action as well as a form button? Does the choice depend on the current company or website? Is the operation inside a database transaction, or can it be queued and retried? The same pattern can be sound in one execution path and unsafe in another if those questions are ignored.

As a study exercise, take one family at a time and find a small existing feature that might benefit. Draw only the objects that participate in the behavior. Write the current and proposed call paths. Then identify one situation where the new design would be worse, such as an extra class for a behavior that never varies. Being able to describe when not to use a pattern is part of understanding it.

17

Creational choices in an extensible application

Object construction looks small until the choice carries configuration, dependencies, or validation. A caller that constructs a concrete provider directly becomes coupled to that provider’s class and assumptions. A small factory can move that choice to one place. The factory should not become a global service locator that knows every subsystem. Its responsibility is narrower: read an explicit choice, validate it, and return an object that supports the contract the caller needs.

An abstract factory is more useful when several related objects must be created as a compatible set. Imagine two shipping providers whose label and tracking clients must use matching authentication and identifier rules. Creating a label client from one provider and a tracking client from another would be a configuration defect. A factory for the provider family can preserve that pairing. If there is only one object to construct, an abstract factory may add unnecessary ceremony.

The Singleton pattern is often overused because “one instance” sounds like a convenient global. In a framework with a registry, worker processes, transactions, test isolation, and multiple companies, hidden global state creates questions about lifetime and scope. Prefer the framework’s established configuration and service mechanisms. If a resource must be shared, document whether it is shared per request, per worker, per company, or across the entire deployment. Those are different guarantees.

A Builder can help when an object requires a sequence of optional choices whose combinations must stay valid. It is useful if the construction steps are understandable and the builder prevents incomplete states. It is not useful for an ordinary record with two fields. A Prototype can help when a configured object is deliberately copied as a starting point, but copying persistent records has relational and ownership consequences. Before using a cloning idea in Odoo, specify which fields copy, which relations stay linked, and which identifiers must be regenerated. The question is always whether the creation boundary protects an invariant that matters.

18

Structural patterns at Odoo extension points

An Adapter makes two contracts compatible. In Odoo integrations, one side is often a business operation and the other is an external API with its own payload and vocabulary. Keep external field names at the boundary. Convert dates, amounts, identifiers, and errors into forms the rest of the module understands. The adapter should explain the translation, not hide a business decision such as whether an order is eligible for export.

Composite is useful when clients should treat an individual item and a group through the same operation. Think about a reporting tree or a set of nested approval steps. The shared contract must be meaningful for both a leaf and a group. If methods only make sense on one side, a composite can produce confusing empty behavior. State whether operations aggregate children, stop at the first failure, or preserve the order of results.

Decorator adds a responsibility around an object while preserving its underlying contract. Logging, caching, timing, or access-aware wrappers are common examples. In Odoo, the wrapper must preserve important call semantics, exception behavior, and context. A cache that ignores company, language, user permissions, or configuration can return the wrong result or expose information. A performance improvement is not valid if its cache key omits part of the answer’s meaning.

Bridge separates two dimensions that would otherwise grow into a class-per-combination matrix. For example, a notification’s content policy and its delivery channel may vary independently. Before creating the bridge, count the real variation points and ask whether they change independently in practice. A pair of ordinary methods may be clearer for a small matrix. Patterns are most useful when they keep future change proportional: adding one channel should not require rewriting every content type, and changing one policy should not disturb unrelated delivery code.

When reviewing a structural design, draw the direction of dependency as well as the runtime call. The caller may know an interface while an adapter knows an external SDK. A decorator may wrap a service while the model still owns authorization. Keeping those distinctions visible makes extension behavior, tests, and access review much easier.

19

Behavior patterns, transaction boundaries, and retry safety

Strategy is a good fit when an operation has multiple policies that share a useful contract. Selection still needs a home: company configuration, a request field, or an explicit argument. Avoid letting a strategy guess from ambient context that its caller cannot see. Make the selected policy inspectable in logs or results when users or operators need to explain an outcome.

Observer and event-style communication can reduce direct dependencies, but they change the failure model. A synchronous listener may fail the transaction that produced the event. A queued consumer may run later, after the originating record has changed. A webhook may be delivered more than once. Define whether the message records a fact that happened or a command that should happen. Include stable identifiers and enough version or timestamp context to detect stale work. Make consumers idempotent when retries can occur.

Command is appropriate when an operation needs a lifecycle: validate, approve, queue, execute, retry, or report. A command object or Odoo wizard can make parameters and intent explicit. It should not pretend a database transaction can atomically include an external API call. Decide what gets committed before a remote request, how a timeout is represented, and how a duplicate request is recognized. If a user presses a button twice, the second action should have a defined result.

State makes allowed transitions explicit. Model the states and transitions before adding buttons. A “complete” transition may require all lines to be processed, while “cancel” may be forbidden after an external fulfillment has begun. Enforce those rules in server-side methods used by every entry point. A view condition can guide the user but cannot protect an RPC call. Keep side effects associated with a named transition and make their retry path clear.

Template Method can give subclasses a stable sequence with a few designated steps, but method inheritance in Odoo is cooperative and shared across modules. Read the complete inheritance chain and preserve expected `super()` behavior. Prefer a smaller explicit collaborator when override ordering becomes difficult to explain. The behavioral pattern decision is sound when a maintainer can answer: who initiates the operation, who can change its policy, what is atomic, and what can be retried?

20

A pattern selection workshop for your own module

Choose one real workflow and describe it without using pattern names. A sentence such as “a manager approves the request, then the system exports it to a provider and records the provider’s identifier” reveals a person, a transition, an external boundary, and a result. List the rules that must always hold: only a manager can approve; an unapproved request cannot export; a timeout must not erase the approval; and retry must not create a duplicate provider object. These are the design constraints.

Next draw the current path from user action to persistent state and any remote effect. Mark each point where a decision is made. If the same provider-specific parsing appears in three places, an adapter may localize it. If a policy varies by company, a strategy may make that variation testable. If an operation needs a queue and retry history, a command-like job record may be appropriate. If the workflow is one simple branch with no likely variation, an ordinary method may be the best answer.

Create a small proposed design and annotate each new abstraction with the pressure it addresses. Then perform a counter-review: what new dependency does this add, how will another addon extend it, how does it behave with multiple records, and how will access rights apply? If the design cannot answer these questions, refine it before coding.

Implement a narrow slice instead of refactoring the whole module. Preserve current behavior, add the smallest boundary, and compare the new call path with the old one. Verify a normal case, an invalid transition, an access-denied case, and a retry or failure case where relevant. Review the diff as a maintainer who has never heard the design discussion. The pattern has earned its place only if the resulting code makes the rule easier to find and the next change safer to make.

21

Extension seams, inheritance, and the cost of a hidden override

Odoo’s extension system lets modules cooperate by extending the same model. That power creates a design pressure of its own: a method may be composed from several implementations, and the order in which they participate matters. Before adding an override, identify the intended extension seam. Read the parent method, inspect its decorators and callers, and check whether another installed addon already extends it. Preserve `super()` behavior when the contract expects cooperative inheritance. A seemingly small omission can prevent another module from applying a security check, a field update, or a downstream operation.

An override is justified when the behavior belongs to the model and the framework exposes a stable method for changing it. It is less suitable when it merely provides an alternate algorithm for a separate responsibility. In that case, a collaborator or explicit strategy may make the dependency easier to see. Do not introduce a new service only to avoid reading the inheritance chain; sometimes an override is exactly the extension point the framework intends.

Review the override as a contract: what inputs may arrive, which records can be in `self`, whether the method is called in a transaction, which side effects it owns, and what return value callers expect. Check how the override behaves when another module adds its own behavior before or after yours. A useful test can establish that the required chain remains intact. When the method has business significance, document the invariant rather than the implementation detail.

The warning sign is not inheritance itself. It is an extension whose behavior cannot be explained without guessing about load order, context, or hidden global state. The remedy may be a smaller override, a documented hook, or a new explicit boundary. Choose the smallest design that gives every participating module a comprehensible contract.

22

Designing seams that are straightforward to verify

A design boundary is useful when it lets you verify one behavior without constructing the whole application around it. An adapter can be checked with representative provider responses. A pure policy calculation can be checked with a few clear inputs. A state transition can be tested for allowed and rejected cases. A controller can be reviewed for request validation and response shape. These checks do not replace an end-to-end user workflow, but they make the reasons for a failure easier to isolate.

Start from an observable claim. “The export chooses the configured provider” is one claim. “The payload maps our customer reference to the provider’s account identifier” is another. “A timeout leaves the order retryable without creating a duplicate” is a third. If one test tries to prove all of them through a long setup, the design may be coupling distinct behavior or the test may simply be too broad. Separate the claims and identify the smallest boundary that owns each one.

Test the contract rather than private mechanics. A strategy test should prove the result or decision for representative policies, not the exact order of helper calls. An adapter test should prove translation and error normalization. An Odoo model test should include the record and access context that make the business rule meaningful. A UI harness should operate as the intended user and assert what that user can see and do.

Use failure examples deliberately. A missing provider configuration should not quietly choose a default. A remote error should not be reported as success. An access-denied user should not gain permission because a button was hidden. A duplicate event should not repeat an irreversible action. Writing these examples before the abstraction is finalized often reveals whether its contract is genuinely small and stable.

23

A concrete review: adding a second notification channel

Suppose an Odoo application currently sends an assignment notice by email. A new request asks for an internal activity as well. The first tempting design is to add a conditional to the assignment method. That may be appropriate if this is a one-time second effect. Before adding an event bus or a notifier hierarchy, ask whether channels vary by company, user, event type, or configuration, and whether delivery should be synchronous or queued.

If both channels are fixed and reliable in the same transaction, two explicit calls may be clearest. If each notification policy evolves independently or plugins must add channels, a narrow notifier contract can provide a seam. A strategy can select a formatting or delivery policy; an adapter can translate to an external provider; a queue can separate slow delivery from the user’s transaction. Those roles solve different pressures and should not be collapsed into a class named “NotificationManager” that owns everything.

Define the event meaning: was the assignment committed, or is the system merely attempting it? Decide whether failure to create the activity should roll back assignment. If email is delayed, what status will the operator see? Can the notification be sent twice? Does the content reveal information to a recipient who should not see the record? These are design requirements, not implementation details.

Implement one path and inspect how a future third channel would be added. If adding it requires edits in many unrelated places, a boundary may help. If an interface and several classes exist solely to wrap two one-line calls, the abstraction may cost more than it saves. Record the reasoning so that later developers can revisit the decision when the variation actually grows.

24

How to keep a design decision understandable six months later

A design decision is easiest to maintain when it leaves evidence close to the code. Use names that describe the business responsibility, tests that demonstrate the contract, and a short note when an important tradeoff is not obvious. Avoid writing documentation that repeats every implementation line. Explain why the boundary exists and what future change would justify revisiting it.

For a provider adapter, record which external contract it translates and how unknown responses are handled. For a strategy, record the selection rule and where configuration is managed. For a state machine, record legal transitions and side effects. For an asynchronous command, record retry safety and the operator’s recovery path. These are the details a future maintainer needs before changing behavior.

Keep the note factual. If a pattern was introduced to support a planned second provider, say whether that provider exists yet. If a cache is temporary, state its invalidation rule. If a test uses a simulated response, do not describe it as an end-to-end provider verification. Precision preserves trust in the architecture record.

When the design changes, update the tests and note together. An obsolete diagram can be more harmful than no diagram because it directs investigation to a path that no longer exists. A small, accurate record helps a future developer understand the reason for the design without requiring the original team to reconstruct the conversation.

25

Choosing a pattern vocabulary that helps a team collaborate

A shared vocabulary can make code review more efficient. When a developer says “this adapter normalizes the provider response,” a teammate can ask whether the boundary preserves error categories. When someone calls a class a “strategy,” a reviewer can ask how selection works and which contract every implementation follows. The name compresses a useful explanation only if the team agrees on what it means.

Do not use pattern names as a substitute for behavior descriptions. A ticket that says “add an Observer” does not explain which event occurs, who listens, or what failure means. A design note that says “use Factory” does not identify the configuration scope or invalid-choice behavior. Start with the requirement and then use pattern language to discuss the structure.

Teams sometimes apply the same word differently. One developer may call any helper a service; another may expect a service to own a transaction. Resolve the practical contract in the codebase: what inputs are accepted, what state can change, which errors are returned, and how callers are authorized. Names should guide navigation, while contracts govern correctness.

When teaching a pattern, compare it with a simpler implementation and explain the tradeoff. This helps new maintainers learn when the abstraction is useful and when it should not be copied. A shared vocabulary is valuable when it makes a conversation shorter without making the design less precise.

26

Pattern review prompts for a design meeting

Begin with the user or system event that starts the behavior. Ask what must be true before it begins and what outcome the caller needs. Identify which data is authoritative and which parts are external. These questions establish the problem before the team draws classes.

For each proposed abstraction, ask: What changes independently? Who owns that change? Which caller depends on the contract? Can the implementation be selected explicitly? What happens when the choice is missing or invalid? Which transaction commits local state? Which side effects can be repeated? How will the team diagnose a failure?

Ask about framework behavior too. Can the method receive multiple records? Which company and user context apply? Does another addon extend the same method? Do record rules filter the data? Is a view condition being mistaken for server authorization? Will an upgrade preserve the relevant XML IDs and inherited view targets?

Close by writing down the simplest valid option, the selected option, and the cost accepted. Name the evidence that will verify the decision. If the team cannot answer a critical question, make a small experiment or defer the dependent implementation. A meeting is successful when it reduces uncertainty and assigns a clear next action.

27

A complete design walkthrough: export a request safely

Start with the user outcome: an approved Odoo request should be sent to an external provider, and the team should know whether it was accepted. List the invariants before discussing patterns. Only approved requests can be exported. The provider reference must be retained. A retry must not create a duplicate. A timeout may leave the result uncertain. An unauthorized user must not trigger the action.

Trace the current entry point and record lifecycle. A form button may call a model method; a scheduled job may later retry failed records. Both should call the same business operation. Put the approval and authorization checks in a server-side transition or service used by both entry points. The view can hide the button for convenience, but the model remains authoritative.

Define an adapter contract: accept a normalized request and return a normalized outcome. Provider-specific identifiers, field names, and error codes stay inside the adapter. A small factory can choose the adapter from validated company configuration. If the provider offers idempotency support, derive and persist a stable key. If it does not, define how an uncertain timeout is reconciled before another submission.

Because the call can be slow, consider a durable operation record or queued job. Persist the intent and pending state, then call the provider asynchronously. Distinguish rejected, retryable failure, succeeded, and unknown outcomes. An operator should be able to see the last attempt and a safe error summary. Do not mark the request exported before provider acceptance is known.

Test authorization, invalid state, normal response, provider rejection, timeout, duplicate dispatch, and retry. Check that the company’s configuration is used and that sensitive payload values do not enter logs. The patterns here are Adapter, perhaps Factory, Command-like job state, and an explicit State transition. Each one addresses a named requirement; none is included merely to make the diagram look complete.

28

A complete design walkthrough: a configurable approval policy

Suppose several companies approve requests differently. One requires a manager; another requires a manager when the amount exceeds a threshold and a finance reviewer above a second threshold. The first question is policy ownership: is this variation stable company configuration, a product rule, or a one-off exception? The answer determines where the choice belongs.

Represent the facts needed for a decision explicitly: request amount and currency, company, requester, current state, and any required category. Normalize amounts before comparing thresholds. Decide what happens when a company has no configuration. A missing policy should fail visibly or use a documented default, not silently choose the first strategy registered.

A strategy contract might answer whether approval is allowed and return the required reviewer role or next state. Keep selection separate from evaluation so an operator can see which policy was applied. If the rules are only two simple branches, a clear model method may be enough. If companies install additional policies or the algorithms evolve independently, a strategy boundary may make change safer.

The approval transition remains a lifecycle operation. It must check the current state, caller permissions, and whether required reviewers have acted. The view can show the appropriate action, but the model method should reject a direct unauthorized call. Record who approved and when if that information matters later.

Verify each policy with amounts below, at, and above its thresholds; different currencies; missing configuration; a user with the wrong role; and a repeated approval attempt. Review multi-company behavior and make sure a cached decision includes the relevant company and configuration. This walkthrough shows how Strategy and State can cooperate without merging policy selection and lifecycle control into one conditional maze.

29

A complete design walkthrough: compare two competing refactors

A legacy method may calculate a result, write several records, and notify an external system. One proposed refactor introduces a service, adapter, factory, event bus, and queue. Another extracts only the external call into an adapter and leaves the local transition explicit. Compare the proposals against the observed problem rather than counting pattern names.

Start with evidence from recent changes and failures. Which part changes most often? What has caused defects? Is the method slow because of remote latency, difficult to test because of mixed responsibilities, or simply hard to read? If the provider has not changed and the request is always synchronous, a full queue architecture may add work without addressing the actual pressure.

Estimate the support cost. The first design adds configuration, durable job state, event monitoring, duplicate protection, and more extension points. The second may leave some coupling but be easier to understand and deploy. If the core concern is a testable provider boundary, the adapter may provide most of the value. If reliability under retry is the issue, a durable command record may be justified. The proposal should fit the failure the team has actually seen.

Consider the next likely change, not every imaginable change. Is another provider committed? Is background processing a product requirement? Must multiple consumers react independently? If the answer is no, keep the design smaller and document a review trigger. If the answer is yes, implement the boundary and verification evidence that support that concrete need.

Write the decision as a short comparison: current pressure, options, selected design, accepted costs, and what evidence would change the choice. A good refactor makes the important behavior easier to locate and safer to change. It does not guarantee that the system never needs a future refactor.

30

A worked Adapter exercise: normalize an external response

Start with two example responses from a provider. One may use `customer_code`, another `accountId`; one returns a date in ISO format, another includes an offset. Write down the stable information the Odoo business operation needs: external reference, status, effective date, and any safe diagnostic code. Do not begin by designing a class hierarchy. Begin with the translated result.

Implement the conversion at the boundary and decide how malformed input is represented. A missing account identifier may be a permanent validation error. An unknown status may require manual review. A timeout is not a malformed response because no response arrived. Keep these outcomes distinct so the caller can choose the right next action.

Test a normal response for each supported provider, missing required data, an unknown status, and a provider error. Verify that secret fields and raw personal information are not copied into logs. Then trace a business operation that consumes the normalized result and confirm it does not know the provider’s original key names.

The exercise is complete when a provider change can be localized to translation and configuration while eligibility, authorization, and state transitions remain owned by the Odoo application. If the adapter has begun calculating discounts or deciding who may approve, draw a new boundary and move that policy back to the domain.

31

A worked Strategy exercise: choose a pricing policy

Suppose a company can price an implementation service by fixed package or by a configured hourly rate. The stable operation is “calculate an estimate for this scoped request.” The varying policy is the method and its parameters. Define which inputs are mandatory for each policy and what result fields are returned: amount, currency, assumptions, and explanation.

Decide how the policy is selected. It may depend on a company setting or a user’s explicit choice, but the selection should be observable. An absent configuration should fail clearly rather than falling through to whichever class happened to load first. Keep the method free of unrelated persistence or notification work so its behavior can be verified on representative values.

Compare a strategy object with a simple conditional. If there are only two stable policies and selection is local, a clear conditional may be enough. If policies are added by other modules or evolve independently, a strategy contract may help. The decision should reflect expected change rather than abstract extensibility.

Test each policy at a normal value and a boundary. Confirm that currency rounding is consistent and that inputs for one policy are not silently accepted by another. Verify the display and stored estimate through the user interface. A named policy is valuable when the team can answer why it ran and reproduce the result later.

32

An event design exercise: approved does not mean delivered

A workflow event should describe a fact that has occurred. “Request approved” means the approval transition passed its server-side checks and was committed. “Send request to provider” is a command. Mixing the two can make consumers assume that an action already happened when only intent was recorded.

Define the event identifier, record reference, timestamp, and relevant version information. Decide whether a consumer should use the event’s snapshot or reload the current record. If the record can change after approval, a consumer that reloads later may see a different state. If the snapshot contains sensitive data, minimize it and apply the correct access policy.

Choose synchronous or asynchronous dispatch based on the delivery need. Synchronous subscribers can participate in a transaction but may delay the user. Asynchronous subscribers need durable message state, duplicate handling, and monitoring. A failed consumer should not make the approval appear to have failed if the approval already committed; instead, expose delivery status separately.

Test duplicate events, stale events, consumer failure, and recovery. Name the state users see while delivery is pending. This exercise teaches that an event is a contract across time, not simply a convenient way to call another method.

33

A pattern portfolio for Odoo module boundaries

Several common boundaries appear repeatedly in Odoo systems. A model method owns a record’s invariant or transition. A focused service can own a calculation shared across models. An adapter translates to a provider contract. A queue record can hold a long-running operation’s lifecycle. A wizard captures short-lived user intent. A factory can validate and construct a provider implementation. These are useful shapes, not requirements for every feature.

The framework already supplies important mechanisms: the ORM and transaction lifecycle, model registry and extension, access rights, record rules, scheduled actions, and view metadata. Recreating these mechanisms in a custom abstraction can make behavior harder to reason about. The design task is to fit domain responsibilities to framework contracts while keeping integrations and policies clear.

Use a portfolio review to map one feature. Draw the entry point, model operation, policy, persistence, provider adapter, and response. Mark where access is checked and when the transaction commits. Identify which parts may change independently and which have one stable owner. Remove boxes that only rename another box.

This map helps an Odoo developer explain why a pattern exists in context. The answer should connect directly to a user behavior, a source of variation, or a failure guarantee. If it cannot, the abstraction may not have earned its maintenance cost.

34

Choosing a boundary around business policy

A boundary should separate responsibilities that change for different reasons. Business policy may change when a company changes its rules. An adapter changes when a provider changes its protocol. A view changes when users need a different workflow. Keeping these concerns together in one method means a provider update can accidentally alter eligibility, or a new policy can require editing every integration call.

Start by naming the policy in business terms. “Is this request eligible for dispatch?” is clearer than “process request.” Identify its inputs: request state, company configuration, date, and customer status. Decide whether the result is a Boolean or a richer outcome with a reason. Then identify which callers need it and whether they should share the same rule.

If the policy is company-specific, pass or read the company explicitly and test two companies. If it is time-sensitive, decide which timezone and date boundary apply. If it depends on a provider response, separate the response translation from the policy. These choices keep the boundary faithful to the actual business meaning.

The best boundary is not always a separate class. A model method may be the right owner. A small pure function may be enough for a calculation. A collaborator may be useful if the policy is shared across models or changes independently. Choose the form that makes the rule easy to find, test, and explain.

35

Multiple companies and context-sensitive behavior

Multi-company behavior changes the assumptions behind many design patterns. A factory may need a different adapter configuration per company. A cache may need a company identifier in its key. A strategy may be selected from company settings. An event consumer may execute under a service user whose current company differs from the record’s company.

Make company ownership explicit where it affects the result. Do not depend on whichever company happens to be active in a browser tab when processing a queued job. Validate that related records belong to a compatible company. Decide how shared records behave and whether users can act across companies. A `sudo()` call does not remove the need for a company policy; it only changes access enforcement.

Test two companies with different settings and records. Confirm that an operation for one company does not read another company’s data or reuse its cached result. If a workflow is intentionally cross-company, record which role is allowed to do it and how the action is audited.

Patterns can localize the company-dependent choice, but they cannot infer the correct scope. A clear configuration boundary and explicit context make the policy reviewable. This is one reason to treat company and user as part of a method’s inputs even when they arrive through the Odoo environment.

36

Concurrency and duplicate work

Two workers can act on the same record at nearly the same time. A method that checks “not yet exported” and then calls a provider can race: both workers observe the old state and both submit. A design that is correct in a single-user diagram may fail under concurrent jobs or repeated webhooks.

Identify the critical section and the invariant. Does the record need a lock or a unique constraint? Is there a stable idempotency key? Can one worker claim the job with a state transition before performing the external operation? What happens if the worker stops after the claim but before completion? A lock alone does not solve recovery if a process dies.

Use database constraints for uniqueness where the invariant can be represented in the schema. Use the framework’s supported transaction and locking mechanisms for contested updates. Keep the external side effect outside assumptions of database atomicity. Record an operation identifier and reconcile uncertain outcomes when the provider can complete an action despite a lost response.

Test duplicate events and concurrent attempts in a controlled environment. Verify that the final record state and external side effect match the business expectation. Explicitly document whether the operation is at-most-once, at-least-once, or effectively-once through idempotency. Precision here is more useful than a vague claim that the job is “safe to retry.”

37

A compact architecture decision record

An architecture decision record can be a short page with six headings: question, context, options, decision, consequences, and review trigger. Keep the question narrow, such as “Should external exports be synchronous or queued?” Summarize only the context that changes the decision. Name at least one viable alternative so future readers can see what was considered.

The decision should be direct and testable. “Use a queued job because provider response time regularly exceeds the user request budget; persist a pending state and retry transient failures” is clearer than “make the system scalable.” Consequences include the status field, monitoring, idempotency, and operator recovery that the queue requires.

Record assumptions and who confirmed them. If a provider’s idempotency support is not verified, mark that open question. Add a review trigger such as “revisit if a second provider is introduced” or “revisit when job backlog exceeds the agreed threshold.” This prevents old decisions from being treated as permanent truth.

Keep the record near the code or project documentation that owns the feature. Update it when the implementation or underlying constraint changes. A concise decision record helps a reviewer distinguish an intentional tradeoff from accidental complexity.

38

Repositories, the ORM, and keeping persistence honest

The Repository pattern gives a domain-oriented interface to persistence. In some application architectures it helps separate business policy from a particular database. Odoo already provides a rich ORM with recordsets, domains, access rules, computed fields, and transactions. Wrapping every `search`, `create`, and `write` in a custom repository often duplicates that interface without adding a useful boundary.

Use a repository-like abstraction when it expresses a domain query or hides a genuinely variable persistence source. A method such as `open_requests_for_review` can make an important query intent clear if it is shared and has a stable policy. A generic `get_by_id` wrapper around the ORM may add little. Keep access context and company scope visible; a repository must not quietly bypass the ORM’s security behavior.

The Unit of Work pattern coordinates changes that commit together. Odoo’s transaction management already supplies a unit-of-work-like boundary for a request or job. Do not manually commit in ordinary model code to imitate a pattern. Manual commits can leave partially applied business operations and break rollback expectations. If work must span an external system or a long-running job, design a durable workflow instead of pretending one database transaction covers everything.

The question is whether the abstraction adds domain meaning or isolates a real variation. If it merely renames familiar ORM calls, prefer the ORM. If it captures a stable business query, transaction policy, or external persistence contract, define that boundary explicitly and verify its access and transaction semantics.

39

Circuit breakers and resilience at remote boundaries

A circuit breaker stops repeatedly calling a dependency that is already failing. It can protect a system from a slow or unavailable provider, but it also changes the user experience: requests may be rejected before they reach the provider. A breaker needs a clear threshold, reset behavior, scope, and operational visibility. A single global breaker can let one tenant’s failures affect another tenant if the dependency is configured per company.

Before implementing a breaker, measure the actual failure mode. A timeout and a provider rejection are different. A rate limit may need a `Retry-After` delay. A validation error will not improve with a retry. Use request timeouts and classify responses first. If calls happen in a queue, the queue may already provide backoff and retry state. Avoid layering several retry mechanisms that multiply attempts.

Resilience patterns work together with an adapter, which can normalize provider errors, and a Command or job record, which can preserve operation state. Decide what the user sees while the provider is unavailable and how an operator can inspect the backlog. If a request is still pending, do not show a final failure prematurely. If the system declines new work, explain what can be done next.

The design goal is bounded failure and informed recovery, not the illusion that external systems never fail. Keep breaker state visible, scope it to the dependency it represents, and test open, half-open, and recovered behavior in a controlled environment.

40

Dependency injection without a framework inside the framework

Dependency injection supplies collaborators to code instead of having that code construct or locate every dependency itself. It can make a policy or service easier to test and can keep external details outside the business operation. In Odoo, the environment and registry already provide framework-managed model access. Adding a large custom container can duplicate those mechanisms and make ordinary calls harder to follow.

Prefer explicit constructor or method arguments for small collaborators when the lifecycle supports it. A pure function can receive a policy or data value directly. A model method can call a focused service factory that uses a validated company configuration. Avoid ambient global containers that can return different objects depending on hidden runtime state.

Tests should replace only the dependency that crosses a boundary. A provider adapter can be stubbed while the business rule remains real. A clock can be passed or wrapped when deterministic time matters. Do not mock every ORM method in a test if the behavior depends on real record rules or computed fields; use an Odoo test environment for those guarantees.

Injection is most useful when it clarifies who owns a dependency and how its implementation can vary. If it adds a container, provider registry, and several interfaces for one fixed helper, the setup may be more complex than the feature. Make the dependency direction clear, then keep the mechanism as small as the application permits.

41

Pattern anti-cases in mature addons

A mature addon can accumulate abstractions that were once useful but no longer match the product. A factory may support providers that are no longer configured. A strategy may have one implementation and no known variation. An event bus may carry vague events that every consumer interprets differently. A mediator may now own policy from several models. Patterns do not become permanent merely because they have names.

Review an abstraction by finding its callers, implementations, tests, and configuration. Ask when it last changed and what extension it currently supports. If an interface has one implementation and no real substitutability, determine whether it still protects a likely change or only adds navigation. If removing it would require broad edits, identify the coupling it has accumulated before deleting it.

Refactoring should preserve behavior in small steps. Add characterization checks for important existing outcomes. Simplify one boundary, verify the user path, then continue. Do not delete an event consumer or inherited hook because no direct caller is visible; the framework may register it dynamically. Search XML IDs, decorators, hooks, and module dependencies as well as ordinary Python references.

The goal is not to make the code fashionable. It is to make ownership, change, and failure easier to understand. Sometimes the result is a new abstraction; sometimes it is a well-named method and fewer files. A good architecture can evolve as evidence about the product changes.

42

Command, Template Method, and an operation with a lifecycle

Command represents a request as data and behavior with a lifecycle. It can be validated, authorized, queued, audited, and retried. A wizard is one familiar Odoo way to collect intent, but the wizard should pass a clear request to the model or service that owns the operation. If the request must survive a worker restart, a transient form alone is not durable state.

Template Method provides a stable sequence with selected steps that subclasses can customize. This can be useful when several related workflows share ordering and invariants. In Odoo, cooperative inheritance and method resolution make the extension contract important. A subclass should not silently skip validation or persistence. Before using the pattern, check whether composition or an explicit sequence of collaborators would be easier to understand.

The two can work together: a command can carry an operation through validation and execution, while a template method defines the execution phases. That combination is justified only when the lifecycle and sequence are real. A simple button that changes one field does not need a command hierarchy.

Write down the request’s identity, parameters, caller, and result. Then specify which failures are retryable and which side effects have already occurred. If the system can identify duplicate commands, a retry becomes safer. If it cannot, provide an explicit reconciliation path. The useful abstraction is the one that makes those lifecycle decisions visible.

43

Mediator and interaction coordination

Mediator coordinates several participants so they do not all depend directly on each other. A multi-step process may have a form, validation policy, external adapter, and result notifier. If each participant calls every other participant, the dependency graph becomes difficult to change. A mediator can own the sequence and translate outcomes between them.

The mediator should coordinate, not absorb every business rule. A large “workflow manager” that validates data, calculates policy, writes all models, calls providers, and renders messages has simply moved the god object. Keep domain decisions with the records or focused policies that own them. Let the mediator decide which participant acts next and how the interaction progresses.

In an Odoo module, decide whether the mediator is stateless code, a persistent workflow record, or a transient user interaction. If the process spans time or external callbacks, persistent state may be required. If it runs entirely within one method call, a plain function may be enough. Keep the state transitions and ownership explicit.

Before introducing a mediator, draw the current dependency graph. If the graph is already a simple chain, the mediator may add needless indirection. If participants form a dense network and the coordination rules change independently, a mediator can clarify the sequence. Test one normal interaction and one participant failure so the coordination contract is tangible.

44

UML sketches as questions, not decoration

A small class diagram can clarify which object owns an operation, but a diagram is only useful if it answers a question. Show the classes involved in one behavior, their relationships, and the direction of important dependencies. Avoid drawing every model and field in the addon. A diagram that cannot fit the problem at hand often needs a narrower scope.

Sequence diagrams can show who calls whom and when a transaction or external request occurs. This is especially useful for Observer, Command, and Adapter designs, where timing and failure matter. Label asynchronous messages and indicate where state is persisted. If a remote response can be lost, show the uncertain outcome rather than drawing a perfectly reliable arrow.

Use the sketch to challenge assumptions: does the caller know too much about the adapter? Can another module extend the behavior? Is there a cycle in dependencies? Where is authorization enforced? Who owns a retry? If the diagram cannot answer these, add only the missing information or inspect the code to resolve it.

Keep diagrams synchronized with important decisions, not every implementation detail. A short diagram included in a review or decision note can save a later maintainer from rediscovering the call path. If the code changes and the sketch no longer tells the truth, update or remove it rather than letting it become misleading documentation.

45

A review checklist for pattern-heavy code

Read the code from the entry point rather than starting with the abstract base class. Identify the concrete operation a user or job requests. Trace its data, decisions, persistence, and side effects. Confirm that names describe business meaning and that one abstraction has not become a catch-all service.

Check the contract at every boundary. Are arguments explicit? Is recordset cardinality stated? Are errors normalized without being hidden? Is configuration validated? Does an event have a precise meaning? Is a strategy selection observable? Can another addon extend the intended method without losing `super()` behavior? These are practical questions that reveal whether a pattern makes the system easier to maintain.

Review security and transaction behavior. Does the model enforce rules for every entry path? Is `sudo()` narrowly justified? Does an external effect happen before or after commit? Is retry safe? Does a cache include company and user dimensions? Does a failure leave a state that can be explained and recovered?

Finally, compare the code with the simplest alternative. If a plain method would be easier to trace and just as safe, prefer it. If the abstraction makes a real variation local and gives it a testable contract, keep it and document why. A reviewer should be able to understand both the design’s benefit and its cost.

46

Factory and Abstract Factory in a provider integration

A Factory is useful when application code needs a capability but should not choose a concrete provider itself. A narrow factory might read a configured provider name, validate it against supported options, and return the corresponding adapter. The caller then asks that adapter to submit an order or retrieve a status. The factory should not become a central directory for every object in the application; it owns one meaningful construction choice.

An Abstract Factory earns its extra structure when the system needs a consistent family of collaborators. A shipping provider might supply both a label client and a tracking client. If one client is created with Provider A credentials and the other with Provider B identifiers, the integration is incoherent. A family factory can ensure that both belong to the same configuration. If callers only ever create one object, the abstract form adds little value.

In Odoo, configuration belongs at an explicit boundary. Validate that a company has the selected provider and required credentials before dispatching work. Avoid choosing a global provider when the business rule is company-specific. Do not log secrets while diagnosing an unsupported or incomplete configuration. A useful failure says which setting is missing and who can correct it.

As an exercise, sketch the caller, factory, adapter contract, and two provider implementations. Write down what adding a third provider should require and what should remain unchanged. If the stable business operation still imports provider-specific code, the boundary is incomplete. If the factory knows every business rule, it is doing too much. The design should make object selection explicit while leaving eligibility and authorization with their proper owners.

47

Adapter and Bridge: translation versus independent variation

Adapter and Bridge both help separate systems or concerns, but solve different problems. An Adapter translates one contract into another: external key names become domain field names, provider error codes become stable outcomes, and dates are normalized to the application’s convention. Its job is to make an outside system usable without allowing that system’s vocabulary to leak through every model method.

Bridge separates two dimensions that vary independently. A notification feature may have content policies and delivery channels. If every combination becomes a separate class, adding one policy and one channel multiplies the combinations. A bridge can let content policy use a delivery abstraction. This is useful only if those dimensions truly evolve independently and share stable contracts.

Do not ask an adapter to decide business policy. It may convert “ACCOUNT_SUSPENDED” into a normalized provider result, but the domain decides whether a suspended account blocks the order. Do not ask a bridge to normalize malformed data; that is an edge translation. Keeping the responsibilities distinct makes failures easier to localize.

Draw dependencies in both directions: who calls whom at runtime, and which code imports which contract. The business layer should generally depend on a stable interface, while provider-specific classes depend on the external SDK. A test can then exercise translation without making an actual provider request. The right separation reduces the cost of an outside change without making every ordinary call take a tour through unnecessary abstractions.

48

Composite and Decorator: uniform operations and added behavior

Composite lets a client use a single item and a group of items through a common operation. A tree of approval nodes or a hierarchy of reporting categories may fit. The design must say how a group behaves: does it apply to every child, stop on the first invalid child, aggregate results, or preserve a user-defined order? A shared method name is not enough if its meaning differs radically between a leaf and a group.

Decorator wraps an object with another responsibility while preserving the expected interface. It can add timing, caching, access-aware filtering, or retry policy around a service. The wrapper must preserve return values and exceptions unless the contract explicitly changes them. In Odoo, a cache key may need company, language, user, and configuration context. Omitting one can return a stale or unauthorized result. A retry wrapper must know whether the operation is idempotent.

Use Composite when clients benefit from uniform recursive behavior, not because the data happens to be hierarchical. Use Decorator when behavior can be added around a stable contract without editing the underlying implementation. If the wrapper changes the meaning of the method or hides an important failure, it weakens the contract.

For each design, write one example call and one failure example. Show what result a group returns when one child fails. Show whether a decorator logs, caches, retries, or propagates an exception. These examples turn a pattern diagram into a contract a teammate can implement and verify.

49

Singleton and Prototype: lifetime, copying, and hidden state

Singleton is intended to constrain an object to one instance, but “one” always has a scope: one request, worker, process, company, database, or deployment. Those scopes are not interchangeable. Odoo runs multiple workers and test transactions, and its registry has its own lifecycle. A module-level object can accidentally persist state across requests or tests. Before sharing an object, explain its lifetime and whether it contains mutable state. Prefer explicit configuration or a framework-managed service where possible.

Prototype creates a new object by copying an existing configured example. It can save repeated setup when the copy semantics are clear. For an ordinary Python value object, a shallow copy may be enough. For Odoo records, copying is a business operation with relationships, ownership, attachments, company fields, and identifiers. Decide which fields are copied, which relations remain linked, and which records are recreated. Use the framework’s copy behavior and review its defaults rather than applying Python’s `copy` module to persistent records.

Both patterns are risky when they hide state or lifecycle. A Singleton can make a dependency invisible. A Prototype can preserve a stale credential or foreign relation. If the application must support tests, multiple companies, or changing configuration, make those dimensions explicit. The most maintainable choice may be constructing a small object per operation or using a clear Odoo model method.

An exercise: identify an object you think should be shared or copied. List its mutable fields and relations, then write the intended scope. If that list is hard to complete, the pattern’s assumptions are not ready for implementation.

50

Strategy, State, and the difference between policy and lifecycle

Strategy selects among algorithms that perform a stable operation. State selects behavior based on an object’s lifecycle state and valid transitions. The two can appear together, but they answer different questions. A pricing policy may be a strategy chosen for a company. An order’s state determines whether pricing can still be changed. Treating both as a single conditional makes it difficult to see which rules vary by configuration and which are constraints on the record’s history.

For a Strategy design, define the contract and selection rule. Is the strategy chosen by product, company, date, or explicit user choice? Can an operator tell which strategy ran? What happens when no strategy matches? A small `if` statement may be clearer than a class family when the alternatives are few and stable.

For State, draw the state graph and label each transition with authorization and preconditions. Decide whether a transition creates a side effect, whether it can be reversed, and which evidence is retained. A “cancelled” state should not be a generic escape hatch if an external action already occurred. Enforce transitions on the server, not only through visible buttons.

The distinction is useful during review: a policy changes what calculation is applied; a lifecycle rule changes what an entity may do next. Keeping them separate reduces hidden combinations. It also gives tests clear names: one test exercises each algorithm, while another checks each allowed and forbidden transition.

51

Observer, Mediator, and keeping communication understandable

Observer lets several interested components react to a meaningful event without the producer calling each one directly. Mediator centralizes coordination among collaborators that otherwise communicate through many tangled references. Both can reduce coupling, and both can also make control flow harder to find if event meaning and dispatch are vague.

Use precise event names that describe a fact: “request approved” is more useful than “request changed.” Specify which data is included and whether it is a snapshot or a reference to current data. Decide if subscribers run synchronously or asynchronously. A synchronous observer may affect the original transaction; an asynchronous one may see later state. A failed subscriber needs an owner and a recovery route.

Use a Mediator when multiple participants have a real coordination protocol, such as a multi-step form or interaction among components with shared lifecycle. Do not route every method call through a mediator just to avoid direct references. A mediator can become a god object if all policy migrates into it. Keep domain rules near their owners and keep the mediator’s role to coordinating the interaction.

Before introducing either pattern, draw the message path and identify how a maintainer searches for all reactions. Decide how duplicate delivery is handled and what happens when one participant is unavailable. If the answer is unclear, an explicit method call may be easier to understand and support.

52

Transaction ownership in a pattern-based design

A database transaction groups local changes that should succeed or fail together. Design patterns do not change that guarantee automatically. If a method writes an approval and then calls a remote provider, the provider may act before the database transaction rolls back. If the call is retried after a timeout, the provider may see the same operation twice. The architecture must state which part is atomic and which part can be uncertain.

For a short, reliable operation, a direct call within the request may be acceptable. For slow or unreliable work, an outbox or queued job can record intent in the same transaction as the business change, then perform external work later. That design needs a durable status, duplicate protection, and an operator recovery path. Do not move a call to a queue solely because asynchronous systems sound more scalable; understand the user experience and support cost.

When reviewing a Command or Observer design, draw the transaction boundary. Mark what is committed before dispatch, what happens if dispatch fails, and how a consumer detects repeated delivery. If the provider supports idempotency keys, define how the key is derived and retained. If it does not, consider reconciliation or manual review for uncertain outcomes. A status such as “pending confirmation” may be more honest than “failed” when the remote result is unknown.

These questions connect patterns to production behavior. The useful design is the one that represents uncertainty clearly and gives users and operators a safe next step, not the one with the most elegant class diagram.

53

Domain services: a focused home for cross-record policy

Some rules do not naturally belong to one record. A policy might compare a request with company settings, product eligibility, and a customer’s current status. Putting the entire decision on one model can make that model depend on several unrelated concepts. A focused domain service can provide a name for the policy and accept the records or values it needs.

The service should remain close to the domain language. `eligibility_for_request` is more informative than `process_data`. Its inputs should be explicit enough that a reader can see which company, date, and record state matter. Its output should explain the result: eligible, rejected with a reason, or missing configuration. Avoid an ambient service locator that reaches into the environment for arbitrary models; that hides dependencies and makes the policy difficult to test.

Not every cross-record method needs a new class. A method on an established model may be the clearest owner, especially if the framework convention expects it there. Use a service when it creates a meaningful boundary or is reused by multiple entry points. Do not move code to a service only to make the model file shorter. The responsibility still needs an owner, and the call path should remain easy to trace.

In Odoo, be deliberate about recordsets and access. Does the service operate on records supplied by a trusted caller? Should it search under the current user? Does a system operation require a narrow elevated read? What company and language context apply? A service boundary can make those choices explicit, but it can also conceal them if designed carelessly. Review its authority alongside its business purpose.

54

An evaluation matrix for a proposed abstraction

Before introducing a pattern, rate the current design and the proposed one against a few practical dimensions. First, locality: when the policy changes, how many unrelated files or responsibilities must change? Second, visibility: can a maintainer tell which implementation ran and why? Third, safety: are authorization, transaction, and retry behavior preserved? Fourth, testability: can the important rule be verified without a full production-like setup? Fifth, comprehension: can a new teammate explain the call path quickly?

The proposed design should improve one or more dimensions without making the others materially worse. A strategy may improve locality but make selection invisible. An event can decouple modules but make failure timing harder to understand. A factory may clarify construction but introduce a registry that can be misconfigured. These tradeoffs should be written down in plain terms.

Include a “do nothing for now” option. If the current code is small, stable, and understood, the maintenance cost of an abstraction may exceed the cost of a future change. Include a targeted refactor option too; the choices are rarely limited to a total rewrite or no action. Look at actual change history where available: if the same branch has changed repeatedly, variation is real. If it has never changed, discuss whether that is because the code is stable or because nobody has touched a risky area.

The matrix is not a scoring system that produces an automatic answer. It is a way to surface the assumptions that influence the choice. A short written conclusion should state why one option fits the observed pressure, what risk remains, and what future evidence would justify revisiting it.

55

Security boundaries are architectural boundaries

Security is easier to preserve when the design makes ownership explicit. A controller receives untrusted input. A model method enforces domain rules. An adapter translates an outside response. A record rule limits which rows a user can access. If one layer quietly assumes another has already checked authorization, the assumption should be visible and verified at every public entry point.

Do not confuse encapsulation with permission. A private helper may keep implementation details tidy, but it does not prevent an RPC caller from invoking an exposed method. A hidden field does not make its value secret. A method with `sudo()` may intentionally perform a narrow system operation, but it also crosses an authority boundary. Describe which identity is acting and why it is permitted to see or change the data.

When a pattern introduces an interface, decide where authorization belongs. It may be checked by the model operation before a collaborator is called, or by a dedicated policy object used by every entry point. Avoid scattering slightly different checks through each adapter or UI handler. The business rule should have one authoritative owner, while the integration boundary should reject malformed or unsupported requests.

Review the design with a least-privilege question: what is the smallest set of records and actions this component needs? A useful architecture diagram can label both dependencies and trust boundaries. That helps reviewers spot a public controller that can read private records, an event consumer that assumes a trusted payload, or a service that elevates access beyond its stated responsibility.

56

Refactoring exercise: make one variation local

Choose a method that contains a real repeated decision, such as choosing a message format for two audiences or selecting a provider based on configuration. First write a behavior description and a few cases: each supported choice, missing configuration, and an unsupported value. Save the current behavior so you can detect accidental changes. Then mark the variation and the stable part of the method.

Make one change that localizes the variation. This might be a mapping to small functions, a focused adapter, or a strategy with a shared method. Keep the caller’s job simple and make the selection rule explicit. Do not add a generic framework for choices the application does not have. If the implementation requires a hierarchy of abstract classes, ask whether a dictionary and two functions would provide the same clarity.

Verify the cases and inspect the new dependency direction. Does the caller know less about the concrete variation? Is the selection visible enough for an operator to diagnose? Can a third choice be added without editing unrelated behavior? Did the new boundary make testing simpler? Did it make navigation or error handling harder? Record both benefits and costs.

Finally, ask a colleague to explain the resulting code without hearing the design discussion. If they can identify the stable operation, the variable policy, and the failure behavior, the boundary is communicating. If they need to memorize pattern terminology before they can trace the request, simplify the design or improve its names.

57

Price and next steps

The current product price is shown above and confirmed on the product page. Add the service to your cart there to begin checkout. The product description explains the included OdooClass Complete access and weekly working sessions; project scope and any additional terms are agreed separately after an initial discussion.

Choose your next step

Design Patterns for Odoo Mastery

Learn to recognize recurring design problems, choose a fitting pattern, and apply it in the shape of an Odoo module you can explain and maintain.

View price and add to cart

Current price $ 95.00 · Add to cart and checkout on the product page.