# Recognising a decision in the wrong place

## What you want to do

A rule put in the wrong place often still runs, and the shop's orders all go through. You want to recognise one when you read a step or a hook, before it hides a decision the shop can no longer see.

## The code

Here is a counter-example. This charge renews an expired card itself, tells the customer, and charges the new card:

Kotlin, from the program [`ch40_counter_example`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch40_counter_example.kt)

```kotlin
/**
 * Charges an order's amount to its card through the payment client, and gives back its receipt, and
 * the gift card's code when the order is a gift card. It gives every reporter the receipt as soon
 * as the bank gives it. When the card has expired, it renews it, tells the customer, and charges
 * the new card.
 */
@Step
class Charge(
    @Input private val order: String,
    @Input private val customer: String,
    @Input private val amount: Long,
    @Input private val card: String,
    @Input private val giftCard: Boolean,
) : ItineraStep {
    fun run(
        @Service payments: Payments,
        @Service cards: Cards,
        contributor: Contributor,
        reporter: StepReporter,
    ): Outcome {
        if (amount <= 0) return fail("nothing-to-charge")
        var receipt = payments.charge(order, card, amount)
        val renewed = if (receipt == null) cards.replacement(card) else null
        if (renewed != null) {
            println("email to $customer: card $card has expired, so we charged $renewed.")
            receipt = payments.charge(order, renewed, amount)
            contributor.contribute("card", renewed)
        }
        if (receipt == null) return fail("card-expired")
        reporter.setGlobalMetadata("receipt", receipt)
        contributor.contribute("receipt", receipt)
        if (giftCard) contributor.contribute("code", "G-$order")
        return succeed()
    }
}

```

Kotlin, the same in its asynchronous form, from the program [`ch40_counter_example_async`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch40_counter_example_async.kt)

```kotlin
/**
 * Charges an order's amount to its card through the payment client, and gives back its receipt, and
 * the gift card's code when the order is a gift card. It gives every reporter the receipt as soon
 * as the bank gives it. When the card has expired, it renews it, tells the customer, and charges
 * the new card.
 */
@Step
class Charge(
    @Input private val order: String,
    @Input private val customer: String,
    @Input private val amount: Long,
    @Input private val card: String,
    @Input private val giftCard: Boolean,
) : ItineraStep {
    suspend fun run(
        @Service payments: Payments,
        @Service cards: Cards,
        contributor: Contributor,
        reporter: AsyncStepReporter,
    ): Outcome {
        if (amount <= 0) return fail("nothing-to-charge")
        var receipt = payments.charge(order, card, amount)
        val renewed = if (receipt == null) cards.replacement(card) else null
        if (renewed != null) {
            println("email to $customer: card $card has expired, so we charged $renewed.")
            receipt = payments.charge(order, renewed, amount)
            contributor.contribute("card", renewed)
        }
        if (receipt == null) return fail("card-expired")
        reporter.setGlobalMetadata("receipt", receipt)
        contributor.contribute("receipt", receipt)
        if (giftCard) contributor.contribute("code", "G-$order")
        return succeed()
    }
}

```

It asks for [chapter 35](https://itinera-dev.org/book/kotlin/35-giving-the-rescue-step-a-service-of-its-own.md)'s `Payments` and `Cards`. In the asynchronous form, its `run` is a `suspend` function, as in [chapter 26](https://itinera-dev.org/book/kotlin/26-running-async-journeys-while-others-wait.md), and its reporter an `AsyncStepReporter`, as in [chapter 33](https://itinera-dev.org/book/kotlin/33-giving-every-reporter-what-it-needs.md).

Since the charge renews the card itself, the workflow gives it no rescue step, and the card registry goes to the charge itself: the provider for `cards` names `charge`, not `charge_rescue`:

Kotlin, from the program [`ch40_counter_example`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch40_counter_example.kt)

```kotlin
/**
 * The shop's workflow: it looks the order up, and finishes an order already completed. Otherwise it
 * works out what the order costs, then charges it, which renews an expired card itself, auditing a
 * charge that succeeds, then ships, and shipping may be tried once more. Once a journey has ended,
 * the customer is told, through the channel the shop configures.
 */
@Workflow(name = "orders", reporters = [Log::class, Desk::class], policies = [Notify::class])
@WithStep(Lookup::class, name = "lookup", policies = [AlreadyCompleted::class])
@WithStep(Price::class, name = "price")
@WithStep(Charge::class, name = "charge", policies = [Audit::class, Outage::class])
@WithStep(Ship::class, name = "ship", retryBudget = 1, policies = [FailedShipping::class])
class Orders(private val channel: String) : ItineraWorkflow, Messages, Refunds {
    override fun tell(customer: String, message: String) {
        println("$channel to $customer: $message")
    }

    override fun refund(receipt: String, amount: Long) {
        println("the bank gives $amount back on receipt $receipt")
    }

    /** The bank, as the payment client of the journey. */
    @Provider(key = "payments") fun bank(): Provided<Payments> = provide(Bank(thisYear = 2026))

    /** The bank's card registry in Europe, for the charge only. */
    @Provider(steps = ["charge"]) fun cards(): Provided<Cards> = provide(cardRegistry("eu"), "eu")

    /** A carrier for every attempt of a step: the main carrier first, the backup carrier after. */
    @Provider(perAttempt = true, key = "carrier")
    fun carriers(attempt: Attempt): Provided<Carrier> =
        if (attempt.isFirst) provide(MainCarrier()) else provide(BackupCarrier())

    /**
     * Gives the shipping the weight of the order's parcel, as the warehouse describes it. Every
     * other input of the shipping is read from the data bag.
     */
    @InputAdapter(steps = ["ship"])
    fun parcels(@Key key: String, @FromWorkflow parcel: Parcel): Supplied =
        if (key == "weight") supply(parcel.weight) else fromDataBag()

    /** Names each journey after its order. */
    @IdGenerator
    fun orderNumber(data: DataBag): String =
        data.read<String>("order").orNull() ?: error("an order without a number")

    /** The order book, which has the orders completed before today. */
    @Provider(key = "orderBook") fun ledger(): Provided<OrderBook> = provide(Ledger(listOf("A-13")))
}

```

Kotlin, the same in its asynchronous form, from the program [`ch40_counter_example_async`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch40_counter_example_async.kt)

```kotlin
/**
 * The shop's workflow: it looks the order up, and finishes an order already completed. Otherwise it
 * works out what the order costs, then charges it, which renews an expired card itself, auditing a
 * charge that succeeds, then ships, and shipping may be tried once more. Once a journey has ended,
 * the customer is told, through the channel the shop configures.
 */
@Workflow(name = "orders", reporters = [Log::class, Desk::class], policies = [Notify::class])
@WithStep(Lookup::class, name = "lookup", policies = [AlreadyCompleted::class])
@WithStep(Price::class, name = "price")
@WithStep(Charge::class, name = "charge", policies = [Audit::class, Outage::class])
@WithStep(Ship::class, name = "ship", retryBudget = 1, policies = [FailedShipping::class])
class Orders(private val channel: String) : ItineraAsyncWorkflow, Messages, Refunds {
    override suspend fun tell(customer: String, message: String) {
        network()
        println("$channel to $customer: $message")
    }

    override suspend fun refund(receipt: String, amount: Long) {
        network()
        println("the bank gives $amount back on receipt $receipt")
    }

    /** The bank, as the payment client of the journey. */
    @Provider(key = "payments")
    suspend fun bank(): Provided<Payments> = provide(Bank(thisYear = 2026))

    /** The bank's card registry in Europe, for the charge only. */
    @Provider(steps = ["charge"])
    suspend fun cards(): Provided<Cards> = provide(cardRegistry("eu"), "eu")

    /** A carrier for every attempt of a step: the main carrier first, the backup carrier after. */
    @Provider(perAttempt = true, key = "carrier")
    suspend fun carriers(attempt: Attempt): Provided<Carrier> =
        if (attempt.isFirst) provide(MainCarrier()) else provide(BackupCarrier())

    /**
     * Gives the shipping the weight of the order's parcel, as the warehouse describes it. Every
     * other input of the shipping is read from the data bag.
     */
    @InputAdapter(steps = ["ship"])
    suspend fun parcels(@Key key: String, @FromWorkflow parcel: Parcel): Supplied =
        if (key == "weight") supply(parcel.weight) else fromDataBag()

    /** Names each journey after its order. */
    @IdGenerator
    fun orderNumber(data: DataBag): String =
        data.read<String>("order").orNull() ?: error("an order without a number")

    /** The order book, which has the orders completed before today. */
    @Provider(key = "orderBook")
    suspend fun ledger(): Provided<OrderBook> = provide(Ledger(listOf("A-13")))
}

```

The workflow class's other methods are as earlier chapters show them: the role implementations in [chapter 19](https://itinera-dev.org/book/kotlin/19-letting-policies-act-on-the-outside-world.md) and [chapter 23](https://itinera-dev.org/book/kotlin/23-undoing-a-charge-when-the-shipping-fails.md), the bank's provider in [chapter 12](https://itinera-dev.org/book/kotlin/12-trying-again.md), the carriers' provider in [chapter 13](https://itinera-dev.org/book/kotlin/13-a-carrier-for-each-attempt.md), the input adapter in [chapter 21](https://itinera-dev.org/book/kotlin/21-deciding-where-a-steps-data-comes-from.md), the ID generator in [chapter 11](https://itinera-dev.org/book/kotlin/11-naming-a-journey.md) and the order book's provider in [chapter 22](https://itinera-dev.org/book/kotlin/22-finishing-a-journey-early.md). In the asynchronous form, `Orders` implements `ItineraAsyncWorkflow`, its roles, adapter and providers being `suspend` functions, as in [chapter 26](https://itinera-dev.org/book/kotlin/26-running-async-journeys-while-others-wait.md).

The other steps, policies and reporters it names are as earlier chapters show them: the lookup and `AlreadyCompleted` in [chapter 22](https://itinera-dev.org/book/kotlin/22-finishing-a-journey-early.md), the pricing in [chapter 20](https://itinera-dev.org/book/kotlin/20-an-optional-input.md), `Outage` and `Audit` in [chapter 34](https://itinera-dev.org/book/kotlin/34-saying-which-attempt-took-the-money.md), the shipping in [chapter 17](https://itinera-dev.org/book/kotlin/17-giving-up-a-step-early.md), `FailedShipping` in [chapter 23](https://itinera-dev.org/book/kotlin/23-undoing-a-charge-when-the-shipping-fails.md), `Notify` in [chapter 19](https://itinera-dev.org/book/kotlin/19-letting-policies-act-on-the-outside-world.md), the log in [chapter 33](https://itinera-dev.org/book/kotlin/33-giving-every-reporter-what-it-needs.md), [chapter 35](https://itinera-dev.org/book/kotlin/35-giving-the-rescue-step-a-service-of-its-own.md) and [chapter 36](https://itinera-dev.org/book/kotlin/36-orders-refused-before-they-start.md), and the desk in [chapter 11](https://itinera-dev.org/book/kotlin/11-naming-a-journey.md). `main` runs Jo's order, whose card has expired, and follows its result up with [chapter 34](https://itinera-dev.org/book/kotlin/34-saying-which-attempt-took-the-money.md)'s `followUp`. It prints:

What `ch40_counter_example` prints, recorded in [`ch40_counter_example.txt`](https://github.com/itinera-dev/book/blob/main/kotlin/expected/ch40_counter_example.txt)

```text
log orders A-8 for Jo #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-8 for Jo #2 attempt_started lookup, attempt 1
log orders A-8 for Jo #3 service_provided lookup gets orderBook from ledger, a ch40_counter_example.Ledger
the order book has no order A-8 yet
log orders A-8 for Jo #4 step_succeeded lookup
log orders A-8 for Jo #5 contribution_committed completed
log orders A-8 for Jo #6 hook_called alreadyCompleted: on step success of lookup
log orders A-8 for Jo #7 attempt_started price, attempt 1
log orders A-8 for Jo #8 optional_input_absent discount
log orders A-8 for Jo #9 step_succeeded price
log orders A-8 for Jo #10 contribution_committed amount
log orders A-8 for Jo #11 attempt_started charge, attempt 1
log orders A-8 for Jo #12 service_provided charge gets payments from bank, a ch40_counter_example.Bank
log orders A-8 for Jo #13 service_provided charge gets cards from cards, a ch40_counter_example.Registry, with eu
the bank declines card jo-2024: it has expired
the card registry in eu says card jo-2024 was replaced by jo-2029
email to Jo: card jo-2024 has expired, so we charged jo-2029.
the bank charges 30 for order A-8
log orders A-8 for Jo, receipt R-A-8 #14 global_metadata_set receipt
log orders A-8 for Jo, receipt R-A-8 #15 step_succeeded charge
log orders A-8 for Jo, receipt R-A-8 #16 contribution_committed card
log orders A-8 for Jo, receipt R-A-8 #17 data_overwritten card
log orders A-8 for Jo, receipt R-A-8 #18 contribution_committed receipt
log orders A-8 for Jo, receipt R-A-8 #19 hook_called audit: on step success of charge
log orders A-8 for Jo, receipt R-A-8 #20 contribution_committed audit
log orders A-8 for Jo, receipt R-A-8 #21 attempt_started ship, attempt 1
log orders A-8 for Jo, receipt R-A-8 #22 input_adapter_supplied ship gets weight from parcels
log orders A-8 for Jo, receipt R-A-8 #23 service_provided ship gets carrier from carriers, a ch40_counter_example.MainCarrier
the main carrier books order A-8
log orders A-8 for Jo, receipt R-A-8 #24 step_info ship: the parcel leaves with receipt R-A-8
log orders A-8 for Jo, receipt R-A-8 #25 step_succeeded ship
log orders A-8 for Jo, receipt R-A-8 #26 contribution_committed tracking
log orders A-8 for Jo, receipt R-A-8 #27 optional_input_absent code
email to Jo: Order A-8 is on its way, tracking T-A-8.
log orders A-8 for Jo, receipt R-A-8 #28 hook_called notify: on workflow success
log orders A-8 for Jo, receipt R-A-8 #29 journey_succeeded
the journey succeeded, with receipt R-A-8 and tracking T-A-8
audit: A-8: charge took 30 on attempt 1, receipt R-A-8
```

What the asynchronous form `ch40_counter_example_async` prints, recorded in [`ch40_counter_example_async.txt`](https://github.com/itinera-dev/book/blob/main/kotlin/expected/ch40_counter_example_async.txt)

```text
log orders A-8 for Jo #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-8 for Jo #2 attempt_started lookup, attempt 1
log orders A-8 for Jo #3 service_provided lookup gets orderBook from ledger, a ch40_counter_example_async.Ledger
the order book has no order A-8 yet
log orders A-8 for Jo #4 step_succeeded lookup
log orders A-8 for Jo #5 contribution_committed completed
log orders A-8 for Jo #6 hook_called alreadyCompleted: on step success of lookup
log orders A-8 for Jo #7 attempt_started price, attempt 1
log orders A-8 for Jo #8 optional_input_absent discount
log orders A-8 for Jo #9 step_succeeded price
log orders A-8 for Jo #10 contribution_committed amount
log orders A-8 for Jo #11 attempt_started charge, attempt 1
log orders A-8 for Jo #12 service_provided charge gets payments from bank, a ch40_counter_example_async.Bank
log orders A-8 for Jo #13 service_provided charge gets cards from cards, a ch40_counter_example_async.Registry, with eu
the bank declines card jo-2024: it has expired
the card registry in eu says card jo-2024 was replaced by jo-2029
email to Jo: card jo-2024 has expired, so we charged jo-2029.
the bank charges 30 for order A-8
log orders A-8 for Jo, receipt R-A-8 #14 global_metadata_set receipt
log orders A-8 for Jo, receipt R-A-8 #15 step_succeeded charge
log orders A-8 for Jo, receipt R-A-8 #16 contribution_committed card
log orders A-8 for Jo, receipt R-A-8 #17 data_overwritten card
log orders A-8 for Jo, receipt R-A-8 #18 contribution_committed receipt
log orders A-8 for Jo, receipt R-A-8 #19 hook_called audit: on step success of charge
log orders A-8 for Jo, receipt R-A-8 #20 contribution_committed audit
log orders A-8 for Jo, receipt R-A-8 #21 attempt_started ship, attempt 1
log orders A-8 for Jo, receipt R-A-8 #22 input_adapter_supplied ship gets weight from parcels
log orders A-8 for Jo, receipt R-A-8 #23 service_provided ship gets carrier from carriers, a ch40_counter_example_async.MainCarrier
the main carrier books order A-8
log orders A-8 for Jo, receipt R-A-8 #24 step_info ship: the parcel leaves with receipt R-A-8
log orders A-8 for Jo, receipt R-A-8 #25 step_succeeded ship
log orders A-8 for Jo, receipt R-A-8 #26 contribution_committed tracking
log orders A-8 for Jo, receipt R-A-8 #27 optional_input_absent code
email to Jo: Order A-8 is on its way, tracking T-A-8.
log orders A-8 for Jo, receipt R-A-8 #28 hook_called notify: on workflow success
log orders A-8 for Jo, receipt R-A-8 #29 journey_succeeded
the journey succeeded, with receipt R-A-8 and tracking T-A-8
audit: A-8: charge took 30 on attempt 1, receipt R-A-8
```

## How it works

What the counter-example shows:

1. **It works, and its journey records none of it.** Jo's order is charged and shipped. But the log says the charge succeeded on its first attempt, events 11 and 15, and that the card was overwritten, event 17. Nothing says the card had expired, that the registry renewed it, or that Jo was told: the email came from inside the step, as a `println` the journey never sees.
2. **It holds three decisions where one belongs.** Charging is the step's. Renewing the card is a repair, which the rescue step made visible as `step_rescuing` and `step_rescued` in [chapter 14](https://itinera-dev.org/book/kotlin/14-repairing-then-trying-once-more.md). Telling the customer is a reaction, which belongs to a policy, through a role, as [chapter 19](https://itinera-dev.org/book/kotlin/19-letting-policies-act-on-the-outside-world.md) showed. **A step does one thing of the business, and says how it went.**
3. **Back in their places, the journey records them.** With the renewal in the rescue step `charge_rescue`, as [chapter 35](https://itinera-dev.org/book/kotlin/35-giving-the-rescue-step-a-service-of-its-own.md) gave it its own card registry, the charge fails with the reason `card-expired` when the card has expired, the one failure the rescue step knows how to repair, and the journey records the repair as `step_rescuing` and `step_rescued`. With the message in a policy acting through a role, as `notify` does in [chapter 19](https://itinera-dev.org/book/kotlin/19-letting-policies-act-on-the-outside-world.md), the journey records the hook it ran as `hook_called`.
4. **The places it doesn't belong are recognisable.** A step that tries its work again in a loop, calls a second service when the first fails, or tells anyone anything has taken a decision that isn't its own. A hook that works out a price, or judges whether a card is good enough, has taken one of the business's. **When a step or a hook takes a decision the journey doesn't record, such as a repair, a retry or a message, that decision is out of its place.**

Now you can tell a decision in its place from one out of it. But the shop's first checkout, [chapter 1](https://itinera-dev.org/book/kotlin/01-but-why-itinera.md)'s, still runs beside the workflow, and moving a system like it is rarely done in one go.

## Outcomes

We have shown how to recognise a decision in the wrong place, and where to move it.

| The usual way                                                                   | With Itinera                                                                                  |
| ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| A rule put in the wrong place often goes unnoticed, since the code still works. | A rule in the wrong place is spotted from the journey, which records none of what it decided. |
