BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
Backend Engineering

Beginner · Lesson 3 of 12

Software Architecture

Give Request Handling a Clear Structure

Trace a missing notebook discount through checkout. Separate parsing, pricing and persistence, then test the rule without starting a server.

Order slips, a teal calculator, blue notebooks and a sales ledger on a shop counter.

The stationery shop announces an offer: buy at least three notebooks in one order and take five dirhams off the order total. The web checkout charges AED 70 for three notebooks at AED 25 each. The staff order screen charges AED 75 for the same purchase. Both screens produce valid receipts. The problem is that the discount lives inside the web request handler, and the staff screen uses a different handler. How do you fix the discrepancy and prove that the next price change reaches both customers?

Follow one order from the submitted fields to the saved receipt. We will keep the existing HTTP contract, put the calculation in a function you can run on its own, and decide which failures require a real database to test. Everything can live in one program. A useful boundary here is as small as a function whose caller can supply all the facts it needs.

Pin down a rule you could apply with a pencil

Our shop accepts one product per order and a quantity from one to ten. This offer applies to the blue notebook N7. At three or more units of that product, subtract 500 fils once from the line subtotal, with a floor of zero. There are one hundred fils in a dirham. The catalog supplies the current unit price in fils. Assume one currency, no taxes, no delivery charge and no other offers. These choices leave no hidden decision about whether delivery contributes to the threshold or whether discounts accumulate.

Write three examples before touching the handler. Two notebooks at 2,500 fils cost 5,000. Three cost 7,500 before the offer and 7,000 after it. Four cost 10,000 before the offer and 9,500 after it. The fourth notebook matters: a developer could accidentally subtract another 500 fils for every notebook after the second. A test containing only the three-notebook example would accept that implementation. Include another product, P4, at the same price and quantity to show that eligibility depends on the product as well as the number purchased.

Separate three questions in the existing handler

Imagine following the instructions in the old handler with your finger. It reads JSON, looks up a session, fetches a price, does multiplication, inserts rows and returns an HTTP response. Mark each line according to the question it answers. What did the caller ask for? How much should this order cost? Which facts must survive after this request ends? The bug sits in the middle question. It is possible to answer that question with ordinary values while the network and database are unavailable.

Responsibility Input for this purchase Result to inspect
Parse the request JSON containing N7 and quantity 3 A recognized product code string and an integer quantity
Price the order N7, 2,500 fils per unit, quantity 3 Subtotal 7,500, discount 500, total 7,000
Record the purchase Customer identity, product, quantity and calculated amounts A committed order with a stable identifier

The middle row has no reason to import a web framework, parse cookies, select a database connection or know the name of a JSON field. The last row needs the calculated amounts because the receipt must preserve the terms of this purchase. Recalculating later from a catalog that can change would make yesterday's receipt dependent on today's product price. The first row is allowed to know exactly how a mobile client spells a field, without forcing the pricing function to learn about mobile clients.

Give the calculation concrete inputs and outputs

Here is the calculation in Python. Its caller provides a recognized product code, an integer unit price in fils and an integer quantity. The function enforces the allowed range and rejects a negative price. At the HTTP boundary we separately check types, including rejecting a Boolean where a JSON integer is required. Integer arithmetic keeps the five-dirham reduction exact. The result carries all the numbers needed to explain the decision to the customer.

def quote(sku, unit_fils, quantity):
    if unit_fils < 0 or not 1 <= quantity <= 10:
        raise ValueError("invalid pricing input")
    subtotal = unit_fils * quantity
    eligible = sku == "N7" and quantity >= 3
    discount = min(500, subtotal) if eligible else 0
    return subtotal, discount, subtotal - discount

Trace the three-notebook order without executing anything. The multiplication produces 7,500. Both eligibility conditions hold. The smaller of 500 and 7,500 is 500. Subtracting that amount produces 7,000. This leaves room for an unusual but instructive catalog price. If the shop clears old stock at 100 fils per unit, three notebooks have a subtotal of 300. Capping the discount at 300 keeps the customer total at zero and the recorded discount equal to the actual reduction. Recording a discount of 500 beside a zero total would make the receipt impossible to reconcile.

Test the price without starting a server

Put the function above and the test below in a file called test_pricing.py. Run python -m unittest test_pricing from the same directory. Each row states an independent input and its expected result. You can change the threshold in the function from three to four to see the three-unit checks fail, then restore it. No fixture account, catalog import or network port is needed for this experiment. The assertions compare observable amounts, so the test still works if you later rearrange the arithmetic. Python’s unittest documentation

import unittest

class PricingTests(unittest.TestCase):
    def test_notebook_offer(self):
        cases = [
            ("N7", 2500, 2, (5000, 0, 5000)),
            ("N7", 2500, 3, (7500, 500, 7000)),
            ("N7", 2500, 4, (10000, 500, 9500)),
            ("P4", 2500, 3, (7500, 0, 7500)),
            ("N7", 100, 3, (300, 300, 0)),
        ]
        for sku, unit, quantity, expected in cases:
            with self.subTest(sku=sku, unit=unit, quantity=quantity):
                self.assertEqual(quote(sku, unit, quantity), expected)

Notice that the expected totals are literals worked out on paper. A tempting shortcut is to compute each expected value using the same condition as the implementation. That duplicates the mistake you are trying to catch. Another tempting test asks whether a helper called apply_discount was invoked. The customer could still be charged full price if the caller discarded the helper’s result. Match the test to what would convince the customer that their receipt is correct.

Wire the pieces together once

The HTTP handler decodes the request and obtains the authenticated customer from the session. It translates the two product fields into the values expected by an application operation called place_order. That operation loads the current unit price from the catalog, calls quote, and hands the result to the order store. Once the store confirms a successful commit and returns the order ID, the handler can construct the 201 response and the Location header. If parsing fails, no pricing or storage work should have started.

The staff screen also calls place_order after checking that the staff member may act for the selected customer. The two entry points can have different permissions and different input formats while sharing the pricing decision and purchase operation. One might later accept a spreadsheet row. It should resolve column names, identify the customer and convert the quantity before invoking the same operation. Martin Fowler’s description of a service layer explains why an application with several interfaces benefits from one place to coordinate an operation. Service Layer

Keep information flowing in the direction the calculation needs. Passing a whole request object to quote would grant it access to a cookie, a locale and unrelated headers. The first developer to read the locale for a promotion would silently change its inputs. A future test would need to construct a believable request just to obtain a price. Supplying the three values directly makes an extra dependency visible during review. If tomorrow’s offer depends on purchase date, add a date explicitly and test the first eligible day.

Know which promises need a different test

A passing price test establishes that the arithmetic works for its inputs. The staff screen can still send quantity one by mistake, or the storage code can insert the subtotal into the total column. For the first risk, send a real sample request through the handler and inspect the values received by the application operation. For the second, save the example using the real storage adapter in a test database, open the stored order and compare all three amounts. One good test at each boundary gives you more diagnostic information than repeating every price scenario through HTTP.

Suppose the store writes the order header and then fails before writing its only line. Persist the pair in one transaction and require a successful commit before reporting success. A storage integration test can induce the second failure and confirm that neither record remains. A fake store that appends to a list cannot demonstrate the transaction behavior of your database or driver. Conversely, a database outage should have no effect on the small table of pricing tests. Each test earns its place by answering a different question. PostgreSQL’s transaction tutorial

Do the extraction in steps you can review. Capture one successful receipt from the existing web flow. Move the calculation into the function and compare that receipt before and after the move. Next connect the staff operation and run the same purchase through both entry points. If staff orders used to charge full price, their new total is an intentional behavior change and deserves its own test. You do not need three deployments or an abstract base class for each function. For a shop this small, clearly named functions in the same module are enough until another caller or dependency gives you a concrete reason to separate files.

اقرأ الدرس بالعربية

Exercise: change the offer and locate a fault

The shop moves the minimum to four notebooks and keeps the five-dirham reduction. For N7 at 2,500 fils, predict the receipt for three and four units. Update the test cases, change the rule, and verify that P4 still receives no discount. Finally imagine that both pricing tests pass but the saved four-unit receipt shows 10,000 fils. Which two observations would tell you where the discount disappeared?

Answer. Three units now cost 7,500 fils and four cost 9,500. Adjust the low-price cap case to four units at 100 fils, producing a subtotal and discount of 400 with zero due. Inspect what place_order hands to storage, then read the committed record. A 9,500 total at the first boundary and 10,000 in the record points to the write mapping. If the record contains 9,500 but the screen shows 10,000, inspect the response mapping and display. You have turned a vague report about checkout into a question with a specific place to look.

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.

Software Architecture9 min read

Design Your First Resource API

Design and test an order API that creates a purchase, retrieves its original receipt and tells a shopper exactly how to fix an invalid quantity.

Read article ↗

Software Architecture10 min read

Follow an HTTP Request

Trace a two-notebook purchase from DNS and TLS to a committed order, and learn what a checkout timeout can actually prove.

Read article ↗