{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"","title":"Copyright","url":"https://ek9.io/books/getting-started-with-ek9/copyright.html","markdown":"# Copyright {.unnumbered .unlisted}\n\n*Getting Started with EK9*\n*A Beginner's Guide to Programming in a Language That Won't Let You Fail*\n\nWritten 2020–2026 by Stephen John Limb.\n\nThis book is dedicated to the public domain under CC0 1.0\n(https://creativecommons.org/publicdomain/zero/1.0/): its text, every code example in it, and\nevery file in its download, `examples.zip`. Anyone, AI companies included, may copy, change,\npublish and use any of it, for any purpose, without asking. `examples.zip` carries the same\nstatement in its `LICENSE.txt`. The whole book is also on the web, at\nhttps://ek9.io/books/getting-started-with-ek9/.\n\nThe EK9 compiler and tools it describes (the \"Software\") are the proprietary property of\nS&R Limb, and the CC0 dedication above does not extend to them. The Software is provided\nfor authorised use only. No license, express or implied, by estoppel or otherwise, to any\nintellectual property rights in the Software is granted by this document. The EK9 runtime, which\nthe compiler places in every program it builds, is licensed under the Apache License 2.0; see\nhttps://ek9.io/LICENSE.txt.\n\nWritten by Stephen John Limb, with Claude (Anthropic).\n\nEvery code example in this book was compiled and run with the EK9 compiler before publication.\n\nFor licensing inquiries, contact: ek9lang@gmail.com\n","examples":[]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"","title":"Preface","url":"https://ek9.io/books/getting-started-with-ek9/preface.html","markdown":"# Preface {.unnumbered}\n\nMost programming books start by warning you about what can go wrong: crashes, values that\nvanish for no clear reason, the one missing character that breaks a program at three in the\nmorning.\n\nThis book starts somewhere else. In EK9, if your program *compiles*, it is already good.\n\nThat is a strong claim, and the first chapter, *Hello, EK9*, explains why it holds. EK9's\ncompiler is strict on purpose, so a program that builds has already passed the checks that\ncatch whole families of common bugs. Its errors are guidance: each one points at the next\nthing to fix.\n\nEK9 is a modern language built for large, serious software. It is not a stepping-stone you\nwill throw away later. Along the way the book also teaches the computer science terms and\nideas you will meet in any language.\n\n## Nothing here is new — and that is the point {.unnumbered}\n\nAlmost nothing in this book is a *new* idea.\n\nProgrammers have known for fifty years that tests catch mistakes early, that data is safer when\nsomething controls how it may change, that a value which might be missing ought to say so, and\nthat tangled code is harder to change than tidy code. EK9 did not discover any of this. It was\nworked out, written down and argued over long before EK9 existed. The original papers are in\nthe footnotes, and some are older than most languages in use today.\n\nWhat has changed is *where the ideas live*. In most languages they sit *outside* the language:\ntesting is a separate tool you add, tidiness is a style guide someone wrote, and review is a\nstep that may or may not happen. They are advice, and advice is the first thing to go when a\ndeadline is close.\n\nEK9 moves the same ideas *inside*, into the language and the compiler. Testing is part of the\nlanguage, not a library added afterwards. Controlling what may change your data is a rule, not\na convention, whether a type hides its data or forbids other code from altering it. Keeping code\nloosely connected is a limit the compiler measures.\n\nTwo things make the difference. First, the ideas are *enforced*: the compiler keeps them, so\nthey do not slip when you are busy. Second, they *fit together*. Instead of separate tools that\nnever speak to one another, testing, controlled state, safe missing values and the quality\nmeasures are designed to **dovetail**, each making the others work better.\n\nSo expect not inventions but a great deal of hard-won practice, built into the language and\nheld in place by a compiler that will not let you drift from it. The compiler's error messages\nand its help also cite the research behind each rule.\n\n## Who this book is for {.unnumbered}\n\nThis book is for people who are **new to programming**, of any age. You do not need to have\nused another language. You do not need to know what a \"null pointer\" is, or why experienced\nprogrammers wince at \"switch fallthrough\". Starting fresh is an advantage: you learn good\nhabits without unlearning bad ones.\n\nThe ideas here are real, and some are deep. They are not watered down. Each is explained in\nplain words, one step at a time.\n\n## What you need {.unnumbered}\n\nYou need EK9 itself. We recommend the EK9 IDE (started with `ek9 -ide`), which puts the editor,\nthe compiler and the built-in help in one place, so the compiler's explanation of an error sits\nnext to your code. The *Installing and Running EK9* appendix lists the install steps. EK9 also\nmanages its own dependencies, so there is no extra build tooling to set up.\n\nThe book shows most commands as they are typed at a command line (a *terminal*), because a\ncommand is exact and the same everywhere. The IDE runs the same compiler.\n\nThe IDE also has more advanced tools: an AI assistant, and a link that lets outside AI tools\nwork directly with the compiler. This book does not use them. It teaches the language by hand,\nso that you understand what those tools do for you.\n\n## How to read this book {.unnumbered}\n\nWork through the chapters in order. Each builds on the ones before it, and the project at the\nend of the volume uses everything before it.\n\nEvery piece of code in this book is a real EK9 program that compiles, and you can run all of\nthem. They are collected in the download, `examples.zip`, with file names that match the\nlistings in the text.\n\n## How code looks {.unnumbered}\n\nCode appears in boxed listings, like this:\n\n```ek9\nstdout <- Stdout()\nstdout.println(\"Hello, World\")\n```\n\nNames of things you type — files, commands, pieces of code — appear in a `fixed-width` font\ninside a sentence. The arrows `<-`, `->`, `:=` and so on are EK9 *operators*. Each is explained\nwhen it first appears.\n\nNow and then you will see a boxed note:\n\n> **Note.** A note adds a useful detail or clears up a common mix-up.\n\nFootnotes point to real research.[^evidence] When EK9 leaves something out, it is usually\nbecause studies and real-world failures showed that feature caused bugs. If a paper looks hard,\nread its summary, or ask an AI tool to explain it. Each rule has a reason, and the footnote\ngives the source.\n\n## How this book was made {.unnumbered}\n\nThis book was written by Steve Limb together with Claude, an AI assistant made by Anthropic.\nSteve created the EK9 language and shaped every chapter; Claude did much of the writing. Every\ncode example was compiled and run against the real EK9 compiler, and every result printed is its\n*actual* output. A person and an AI building something together, with the work checked at every\nstep, is the kind of software development EK9 was made for.\n\n[^evidence]: Throughout this book, footnotes like this cite the research or real incidents\nbehind EK9's design choices. They are gathered, with plain-language notes, in the appendix *The\nEvidence: the research behind the rules*.\n","examples":[]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"","title":"How to use this book","url":"https://ek9.io/books/getting-started-with-ek9/how-to-use.html","markdown":"# How to use this book {.unnumbered}\n\nThere are three books in the EK9 set, and this is the first.\n\n*Getting Started with EK9*, the book you are reading, teaches the language by building small\nprograms. It assumes no prior experience. If you have written code before, some parts will be\nfamiliar and you can move quickly; if you have not, every idea is introduced in plain words and\nthen shown running.\n\n*EK9 in Depth*, the second volume, goes under the surface: how the mechanisms work, how to build\nlarger applications, and the ideas the language rests on. Read it after this one.\n\nTogether, those two volumes teach the language. The third book, *The EK9 IDE and Refactoring\nToolset*, is a separate companion that covers the EK9 development environment and its tools in\nfull. This book recommends the IDE and shows a few pictures of it, but it teaches the language\n*by hand*, so that you understand what those tools do for you. You do not need the companion\nbook to follow this one.\n\n## How the chapters work {.unnumbered}\n\nEach chapter builds one or more small programs. Every example was **compiled and run before\nprinting**, and the output shown is the real output. You can download all the examples as one\narchive (`examples.zip`) and open them in the IDE to change and re-run them. Changing a working\nprogram and seeing what happens is the best way to learn. The examples are yours to use as you\nlike: they are public domain (CC0 1.0), as the copyright page sets out.\n\nRead the chapters in order the first time. Each assumes the ones before it.\n\n## Conventions {.unnumbered}\n\n- Chapters refer to one another by title, such as *Functions* or *Guards and Safe Code*.\n- Code looks `like this`. A complete program starts with the line `#!ek9`.\n- A **Try it** box suggests a small change to make and re-run.\n- Where a rule exists because of a real, hard-won lesson, a footnote points to the evidence appendix,\n  *The Evidence: the research behind the rules*, which gathers the research and the well-known bugs\n  behind the rules. You can hand any of those papers to an AI and ask it to summarise them.\n- Compiler messages are copied exactly as the compiler prints them; long lines wrap on the page.\n  An error block shows the `Error` line and the lines under it (`See:` and sometimes `forAI:`);\n  the lines around them, which say the build failed and name the file, are left out. *Reading the\n  Compiler's Guidance* shows one message in full.\n\n## Getting set up {.unnumbered}\n\nThe smoothest start is the **EK9 IDE**: it bundles the editor, the compiler and built-in help in\none place. The *Installing and Running EK9* appendix lists the install steps, *Hello, EK9* takes\nyou through your first program, and the complete tour of the environment is in the companion\nbook.\n","examples":[]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 1","title":"Hello, EK9","url":"https://ek9.io/books/getting-started-with-ek9/hello-ek9.html","markdown":"# Hello, EK9\n\nA programmer's first step is the same in every language: make the computer say something back.\nBy the end of this chapter you will have written, built and run a complete EK9 program, you will\nunderstand every line of it, and you will have met the one idea that shapes the rest of the\nlanguage.\n\n## The one big idea\n\nThe hard part of programming is not the mistakes the computer *tells* you about. It is the ones\nit does not.\n\nA program runs and looks fine. An hour later it stops with a baffling message, or it quietly\ngives a wrong answer that nobody notices. Then the hunt begins: where did it go wrong, and why?\nThat hunt, sometimes for hours over something tiny, is the real cost of writing code.\n\nEK9 moves the hunt to *before* the program runs. A tool called the **compiler** turns your text\ninto a program the computer can run, and EK9's compiler is strict on purpose. It refuses to\nbuild a program that contains one of a long list of known bug patterns, and it points at the\nspot while the problem is still small.\n\nAn EK9 error is the compiler doing part of the bug-hunting for you, early. And when a program builds\nwith nothing to say, that means something: **once it builds, a whole set of mistakes has already been\nruled out.**\n\n## Your first program\n\nHere is a complete EK9 program. Type it into a file called `HelloWorld.ek9`, or find it in the\nexamples download. The `.ek9` ending tells the compiler what kind of file it is.\n\n```ek9\n#!ek9\ndefines module introduction\n\n  defines program\n\n    HelloWorld()\n      stdout <- Stdout()\n      stdout.println(\"Hello, World\")\n```\n\nTo run it, type the name of the tool, `ek9`, then the name of the file. (The *Installing and\nRunning EK9* appendix lists the install steps.)\n\n```console\nek9 HelloWorld.ek9\n```\n\nIt prints:\n\n```text\nHello, World\n```\n\nOn macOS or Linux you can also mark the file executable and run it on its own,\n`./HelloWorld.ek9`; that is what the `#!ek9` first line is for. The chapter *Programs, Input and\nOutput* shows the one-time step. Either way the result is the same.\n\nThe picture below shows the same program in the EK9 IDE, with the message changed to\n`Hello, World!`. The program is in the editor. Running it opens a window with a green\n**Success** bar and the program's output. Under the editor, the *Build Output* tab reads\n*\"Compilation successful: no errors\"*: the compiler has checked the program and found nothing to\nreport.\n\n![Running a first program in the EK9 IDE: the editor holds the program, the run window shows its output,\nand the Build Output tab confirms it compiled with no errors.](images/ek9-ide-helloworld.png){width=95%}\n\nThe program is six lines long. Here they are one at a time.\n\n## Reading the program, line by line\n\n**`#!ek9`** — The first line of every EK9 file is this short marker. It tells the system that\nwhat follows is EK9 code. Every EK9 file in this book starts with it.\n\n**`defines module introduction`** — Every EK9 file lives inside a *module*. A module is a named\nbox that keeps your work separate from everyone else's. This box is called `introduction`; the\nname is the label on the outside, and everything else goes inside.\n\n**`defines program`** — Inside the box we declare a *program*. A program is code you can run\ndirectly: the place the computer begins. One module can hold several programs, and other kinds of\nbuilding block that later chapters introduce.\n\n**`HelloWorld()`** — This names the program `HelloWorld`. The round brackets `()` mark it as\nsomething you can *call*, which means run. Everything indented under this line is the *body* of\nthe program: the instructions themselves.\n\n**`stdout <- Stdout()`** — This is the first instruction, and it does two things. `Stdout` is a\nbuilt-in tool for writing text to the screen; the name is short for \"standard output\". Writing\n`Stdout()` makes one. The `<-` operator then *declares* a new name, `stdout`, and gives it that\nnew tool. From now on, `stdout` means \"the screen-writer just made\".\n\n> **Note.** You did not have to tell EK9 that `stdout` is a screen-writer. It worked that out\n> from the `Stdout()` on the right. This is called *type inference*, and the book uses it\n> throughout.\n\n**`stdout.println(\"Hello, World\")`** — Now we *use* the screen-writer. The `.println(...)` part\nmeans \"print this line\". The text in double quotes, `\"Hello, World\"`, is the message. `println`\nadds a new line at the end, so the next thing printed starts on the line below.\n\n## No braces, no semicolons\n\nMany programming languages use punctuation to show structure: curly braces `{ }` around a block,\nand a semicolon `;` at the end of each line. EK9 has neither.\n\nInstead, EK9 uses **indentation**, the blank space at the start of a line. It shows which lines\nbelong together, like a nested list in ordinary writing.[^python] The two lines indented under\n`HelloWorld()` belong to it. The `HelloWorld()` line, indented under `defines program`, belongs\nto that. The shape you *see* on the page is the shape the compiler reads.\n\n<!-- listing: variant of examples/ch01-hello/HelloWorld.ek9 -->\n```ek9\n#!ek9\ndefines module introduction      // the box\n\n  defines program                //   a kind of thing inside it\n\n    HelloWorld()                 //   a specific program\n      stdout <- Stdout()         //   its instructions, indented\n      stdout.println(\"Hello, World\")\n```\n\nThe indentation *is* the syntax (the grammar the compiler reads), so keeping it even, the same\nnumber of spaces at each level, is part of writing correct EK9. Use **spaces, never tabs**: a tab\nis a build error. **Two spaces per level** is the standard step that the language and its\nformatter use.\n\nEK9 comes with a **formatter** that lays your code out in one standard way. The IDE has it built\nin, and at the command line `ek9 -f MyFile.ek9` formats a file. If the indentation is in a real\nmuddle, `ek9 -ff MyFile.ek9` tries to repair it. That leaves you to think about what the program\n*does*, not how it *looks*.\n\n> **Note.** The text after `//` is a *comment*. It is a note for human readers, and the compiler\n> ignores it. Use comments to remind yourself, or the next person, what something is for. `//`\n> runs to the end of the line. For a note that spans several lines, EK9 has a block comment that\n> starts with `<!-` and ends with `-!>`.\n\n## Doing a little more\n\nNow print two lines. The body of a program is a list of instructions, carried out in order, from\ntop to bottom.\n\n```ek9\n#!ek9\ndefines module introduction\n\n  defines program\n\n    Greeting()\n      stdout <- Stdout()\n      stdout.println(\"Hello, World\")\n      stdout.println(\"Welcome to EK9\")\n```\n\nRun it and you get:\n\n```text\nHello, World\nWelcome to EK9\n```\n\nThe screen-writer is made once and used twice; `stdout` still refers to the same tool. Using a\nname you have already declared is normal. What you may *not* do is declare the same name twice\nwith `<-`, because then it would be unclear which one you mean. The compiler stops you. This is\nthe kind of small, early check the whole language is built on.\n\n## Try it yourself\n\n1. Change the message so the program prints your own name.\n2. Add a third `println` line. Predict what will appear before you run it.\n3. Remove the indentation from the `stdout.println(...)` line so it lines up with\n   `HelloWorld()`. Try to build it, and read the error the compiler gives you. Reading errors is\n   a skill, and it starts here; *Reading the Compiler's Guidance* explains this very message.\n\n## Recap\n\nYou have written and run a real EK9 program. You met the shape of every EK9 file: a **module**\nthat holds a **program**. EK9 uses **indentation** instead of braces and semicolons. The `<-`\noperator declares a name and gives it a value, and **type inference** works out what kind of\nvalue that is.\n\nYou also met the idea that runs through the whole book: the EK9 compiler is strict on purpose,\nand that strictness works for you.\n\nThe next chapter looks at the values those names can hold, and at one of EK9's less usual ideas:\na value can be present and still not hold anything meaningful yet.\n\n[^python]: If you know Python, it uses indentation in the same way.\n","examples":["books/getting-started-with-ek9/ch01-hello/Greeting.ek9","books/getting-started-with-ek9/ch01-hello/HelloWorld.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 2","title":"Values and the Three States","url":"https://ek9.io/books/getting-started-with-ek9/values-and-state.html","markdown":"# Values and the Three States\n\nPrograms spend most of their time moving *values* around: numbers, words, dates, prices. This\nchapter shows how to hold a value under a name, introduces the kinds of value EK9 starts you\nwith, and explains an idea that prevents a well-known class of bugs: in EK9, a value can exist\nwithout yet holding anything meaningful.\n\n## Names for values\n\nIn *Hello, EK9* you wrote `stdout <- Stdout()`. The same `<-` operator works for ordinary values:\n\n```ek9\nname <- \"Ada\"\nage <- 36\npi <- 3.142\n```\n\nRead `<-` as \"is a new name for\". After these three lines, `name` refers to the text `\"Ada\"`,\n`age` to the number `36`, and `pi` to `3.142`. A name paired with a value like this is called a\n**variable**, because the value it refers to can change as the program runs.\n\nYou did not say what *kind* of value each name holds. EK9 reads `\"Ada\"` and works out that\n`name` holds text; it reads `36` and works out a whole number, and `3.142` a number with a\ndecimal point. This is type inference again, doing everyday work.\n\n> **Note.** Values written straight into the code, like `\"Ada\"`, `36` and `3.142`, are called\n> *literals*. A literal is a value spelled out in full, as opposed to one the program works out\n> while it runs.\n\n## The built-in value types\n\nA *type* is a kind of value. EK9 comes with a set of ready-made types; these five come first:\n\n- **`String`** — text, written between double quotes: `\"Ada\"`, `\"Hello, World\"`.\n- **`Integer`** — whole numbers: `36`, `0`, `-5`.\n- **`Float`** — numbers with a decimal point: `3.142`, `-0.5`.\n- **`Boolean`** — a yes/no value: `true` or `false`.\n- **`Character`** — a single letter or symbol, written between *single* quotes: `'a'`, `'?'`,\n  `'7'` (double quotes always mean a `String`, even for one letter).\n\nEK9 also has richer types that many languages leave you to build by hand: `Date` and\n`DateTime`, `Money`, `Duration`, and `Dimension` for measurements. They come later.\n\nLater still you will build your *own* types — a `Person`, a `Score`, a playing card — so a\nprogram can talk about the things it is about, in its own words. That has a chapter of its own.\n\nEach type knows how to behave. Numbers add and multiply; text joins together:\n\n```ek9\ngreeting <- \"Hello, \" + name\ntotal <- age + 4\n```\n\nWith `name` set to `\"Ada\"`, `greeting` becomes `\"Hello, Ada\"`, and `total` becomes `40`. `+` is\nan **operator**, a symbol that does a job, and it does the right job for the type it is given:\nbetween two pieces of text it joins them, between two numbers it adds them. You can also define\nwhat an operator like `+` means for *your own* types; the chapter *Using Operators* shows\nhow.\n\n## Putting values inside text\n\nJoining text with `+` soon gets fiddly. EK9 has a neater way, called **string interpolation**,\nwhich uses *backtick* quotes instead of double quotes:\n\n<!-- listing: fragment -->\n```ek9\nname <- \"Ada\"\nage <- 36\nstdout <- Stdout()\nstdout.println(`${name} is ${age} years old`)\n```\n\nThis prints:\n\n```text\nAda is 36 years old\n```\n\nInside backticks, anything between `${` and `}` is worked out and placed in the text. It reads\nbetter than gluing pieces together with `+`, especially with several values.\n\nTo turn the number `36` into text, EK9 asks the value for its text form using an operator\nwritten `$` — read it as \"give me this as a String\". Every built-in type has one, and when you\nbuild your own types you can give each its own `$`, so your values fit into text as neatly as a\nnumber does.\n\n> **Note.** Inside these strings the backtick and the `$` have a special meaning, so you write\n> `` \\` `` and `\\$` when you want those characters as plain text, just as you write `\\\"` for a\n> double quote inside a normal string.\n\n## New lines, tabs and other characters\n\nSome characters are awkward to type into a string, such as a new line or a tab. For those you use\na **backslash escape**: a `\\` followed by a letter that stands for the character. The two most\ncommon are `\\n` for a new line and `\\t` for a tab:\n\n```ek9\nstdout.println(\"Roses are red,\\nViolets are blue\")\nstdout.println(`Name:\\tAda`)\n```\n\n```text\nRoses are red,\nViolets are blue\nName:\tAda\n```\n\nThe `\\n` split the first line in two; the `\\t` moved `Ada` to the next tab stop. There is also\n`\\u`, followed by four hexadecimal digits (base 16, counting `0`-`9` then `A`-`F`), which stands\nfor *any* character by its Unicode number:\n\n```ek9\nstdout.println(`Caf\\u00E9 costs \\u00A31`)\n```\n\n```text\nCafé costs £1\n```\n\n`\\u00E9` is `é`, and `\\u00A3` is `£`.\n\nEK9 source is Unicode text, so if you can type the character you can also write it directly:\n\n```ek9\nstdout.println(`Café costs £1`)\n```\n\n```text\nCafé costs £1\n```\n\nThe `\\u` form is for characters you cannot easily type, or when you want to be exact about\nwhich one you mean.\n\nThese escapes work the same way in both kinds of string, `\"...\"` and `` `...` ``, so `\"a\\nb\"`\nand `` `a\\nb` `` each print across two lines. For a backslash itself, write `\\\\`.\n\n## Set and unset\n\nThis is the idea that sets EK9 apart, and later chapters lean on it.\n\nThink of a value as a box, and its name as a label with an arrow running to the box. In EK9 a\nvalue is in one of *three* states. Two are everyday; the third is brief:\n\n1. **Set** — the box has something useful in it. `age <- 36` puts `36` in the box.\n2. **Unset** — the box exists, but nothing useful is in it *yet*. It is a real box, and it is\n   empty.\n3. **Absent** — there is no box at all. The name has been written down, but it does not point at\n   anything yet.\n\nA passport makes the three concrete. *Set* is a filled-in passport: you can fly. *Unset* is a\nblank passport: a genuine document, but you still cannot fly with it. *Absent* is saying \"I have\na passport\" with nothing in your hand.\n\n![A value in EK9 is *set* — the box holds something — *unset*, where the box is there but empty — or\n*absent*, no box at all yet. EK9 makes you give a name a real box before anything reads\nit.](images/three-states.png){width=85%}\n\nThe third picture is where many languages come unstuck. In them, a name can point at no box at\nall; the Preface mentioned *null pointers*, and that missing box is exactly a null.\n\nHere is what goes wrong. `topScore` is an ordinary name, but it points at nothing. The program\nwants to print `topScore`, so it follows the arrow to fetch the value's text form — the `$` from\nearlier. There is no box. Nobody checked, so the program finds out only at that instant, and it\n**crashes**: the null-pointer error (some languages call it a *panic*), a well-known cause of\nsoftware failures.\n\nEK9 does not pretend the absent state cannot exist. You may still say a name has nothing yet.\nWhat EK9 is designed to take away is the *crash*: the compiler checks that a name has been given\na real box before anything reads it, just as you must pick up a passport before you set off for\nthe airport. When you have nothing useful to put in the box yet, make it *unset*: present but\nempty, an ordinary state to be in, not a trap. In place of a crash you get a state you can name\nand a check the compiler makes you keep.\n\n> **Note.** Some languages add this safety with a special wrapper type, often called `Optional`\n> or `Maybe`: you put a value inside it, and the wrapper makes you ask \"is anything in here?\"\n> before you use it. That only protects the values you remember to wrap. EK9 makes the question a\n> property of *every* value: the `?` check (next section) works on anything. EK9 also has an\n> explicit `Optional`, for when you want to say \"there may or may not be a value here\" out loud;\n> it has a chapter of its own.\n\nYou make an unset value by naming a type with empty brackets:\n\n<!-- listing: fragment -->\n```ek9\nselectedName <- String()      // a String box that exists but holds no text yet\nchosenAge    <- Integer()     // an Integer box with no useful number yet\n```\n\nCompare that with the set versions:\n\n<!-- listing: fragment -->\n```ek9\nselectedName <- \"Ada\"         // set: the box holds text\nchosenAge    <- 36            // set: the box holds a number\n```\n\nWhy would you want an empty box? Because programs often reach a point where \"we do not know this\nyet\" is the true answer: a form not filled in, a search not yet run, a choice not yet made. EK9\nlets you say exactly that, instead of faking it with a zero or an empty string that someone might\ntake for a real answer.\n\n## Asking whether a value is set\n\nBecause \"unset\" is a real state, EK9 gives you a way to ask about it: the `?` operator. Put `?`\nafter a value. It answers `true` if the value is set, and `false` if it is not.\n\n<!-- listing: fragment -->\n```ek9\nselectedName <- String()\nstdout <- Stdout()\nstdout.println(`Is selectedName set? ${selectedName?}`)   // prints: Is selectedName set? false\n```\n\nThe answer `?` gives back is itself a value, of type `Boolean`. And a `Boolean` can also be\n*unset*: \"not yet known\" is separate from both `true` and `false`. A question nobody has answered\nyet is exactly that. Where a yes/no type can hold only two values, \"not answered\" has to be\nfaked.\n\nUsing an ordinary unset value is allowed. It stays unset and carries that forward: arithmetic on\nan unset number gives an unset result. The example file `Values.ek9` shows it:\n\n<!-- listing: fragment -->\n```ek9\nchosenAge <- Integer()\nlater <- chosenAge + 4\nstdout.println(`Is later set? ${later?}`)   // prints: Is later set? false\n```\n\nThe `?` check is the base of EK9's safety. The compiler tracks when a value could be unset or\nabsent. It will not let you read a value *before* it has been given one, and, as later chapters\nshow, it will not let you reach *inside* an `Optional` or `Result` you have not checked. That is\naimed at a well-known and costly bug: code that assumes a value is there when it is not.\n\n## Naming the type yourself\n\nEvery declaration so far has used `<-`, and EK9 has worked out the type from the value on the\nright. That is the everyday way to declare a local variable, and the book uses it throughout.\n\nSometimes you want to *name the type yourself*. You do that with `as`:\n\n<!-- listing: fragment -->\n```ek9\nchosenAge    as Integer: 36      // an Integer called chosenAge, set to 36\nselectedName as String: \"Ada\"    // a String called selectedName, set to \"Ada\"\n```\n\n`chosenAge as Integer: 36` says the same as `chosenAge <- 36`, with the type written out. The\nvalue after the `:` is the starting value.\n\nThere are two reasons to write it this way. One is clarity: spelling out the type sometimes\nmakes code easier to read. The other is a convention of this book: when you build **records**\nand **classes**, the *fields* inside them are written with the type spelled out, as in\n`balance as Integer: 0`. (`balance <- 0` would compile there too; the spelled-out form makes a\ntype's insides read clearly.) The rule of thumb: for an everyday local variable, prefer `<-`; for\nthe field of a type, use `as Type:`.\n\nYou can also declare a typed name with no starting value:\n\n<!-- listing: fragment -->\n```ek9\nresult as Integer?    // an Integer, deliberately left absent for now\n```\n\nThe `?` on the end is required. It marks `result` as starting *absent* — no box at all yet —\nand it says \"there may be nothing here yet\" in the code where everyone can see it. The compiler\nthen checks that `result` is given a real box, set or unset, before anything reads it.[^javadecl]\nThe chapter *Classes* has the rules that apply to the fields of your own types. Use this form only\nwhen you cannot supply a starting value yet.[^assignsymbols]\n\nSometimes that is a necessity. The usual case is inside a type you build yourself: a field may\ndepend on what the code creating the object hands over, so it cannot be filled until that code\nruns, usually inside a *constructor* (introduced with classes). Prefer to give a name its value\nwhen you declare it; when the value does not exist yet, the `?` form says so, and the compiler\nchecks the gap is filled before anything reads it.\n\n## Changing a value later\n\nThe `<-` operator *declares* a name for the first time. Once a name exists, you change what it\nrefers to with the `:=` operator:\n\n```ek9\nscore <- 0          //declare 'score', starting at 0\nscore := 10         //change it to 10\nscore := score + 5  //change it to 15\n```\n\nUsing `<-` twice for the same name is an error: you cannot declare a name twice. Using `:=` on a\nname that was never declared is also an error: you cannot change something that does not exist.\nEach operator has one job, and the compiler holds you to it.\n\nA name in EK9 *refers* to its value: picture the name pointing at the value, not holding a\nprivate copy of it. EK9 works this one way for every type, which keeps the rules simple.[^byref]\n\n> **Note.** There is a third assignment, `:=?`, called *assign-if-unset*: \"set this *only if* it is\n> currently unset\". It is introduced properly in *Guards and Safe Code*.\n\n[^javadecl]: In Java, `Integer result;` declares a name with nothing behind it, much like this.\nThe difference is what happens next: Java lets a program follow that reference and crash, while\nEK9 checks that `result` has been given a box before anything reads it.\n\n[^byref]: Some languages copy simple values (numbers, characters) automatically but *share*\nlarger objects, and you have to remember which is which. EK9 does not mix the two: a name always\nrefers to its value. This matters once you work with things you can change in place: two names\nfor the same thing then see the same changes. When you want a separate copy, EK9 has an explicit\ncopy operator, `:=:`. (For a built-in value such as an `Integer` it copies the value; for a type\nyou write yourself, the generated `:=:` is a *shallow* copy — the copy's fields refer to the same\nobjects — unless you write your own.) The formal terms for the two behaviours are *by value* and\n*by reference*; EK9 is uniformly *by reference*, with copying made explicit.\n\n[^assignsymbols]: EK9 is deliberately relaxed about the exact symbol here, because programmers\narrive from different languages with different habits. When giving a typed declaration its\nstarting value, `:`, `=` and `:=` are all accepted and mean the same thing — `x as Integer: 0`,\n`x as Integer = 0` and `x as Integer := 0` are identical — and the same three symbols also work\nfor *changing* a value later. This book uses `:` for a starting value and for setting a function's\nreturn value, and `:=` for every later change to a variable or a field, so the two read differently\nat a glance; the EK9 documentation advises picking a style and keeping to it.\n\n## Try it yourself\n\n1. Declare a `String` holding your home town and an `Integer` holding the year you were born.\n   Print a sentence about yourself using backtick interpolation.\n2. Declare an unset `Integer` and print its `?` check. Then give it a number with `:=` and print\n   the `?` check again. It changes from `false` to `true`.\n3. Declare the same name twice with `<-`, and read the compiler's error.\n\n## Recap\n\nYou can hold values under names, and you know EK9's starter types: `String`, `Integer`, `Float`,\n`Boolean` and `Character`. **String interpolation** with backticks builds text from values. A\nvalue is in one of three states — **set**, **unset**, or briefly **absent** — and the `?`\noperator asks whether it is set. EK9 has no `null` keyword by design: it aims to remove the\ncrashes that come from reading a value that is not there.\n\nNext, these values are used to make *decisions* and to *repeat* work, and the set/unset idea\nkeeps that safe too.\n","examples":["books/getting-started-with-ek9/ch02-values/Declarations.ek9","books/getting-started-with-ek9/ch02-values/Escapes.ek9","books/getting-started-with-ek9/ch02-values/Mutation.ek9","books/getting-started-with-ek9/ch02-values/Values.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 3","title":"Making Decisions and Repeating Work","url":"https://ek9.io/books/getting-started-with-ek9/decisions-and-loops.html","markdown":"# Making Decisions and Repeating Work\n\nSo far the programs have run straight down, top to bottom, doing the same thing every time. Real\nprograms need to *choose*: they behave differently depending on the values they are given. They\nalso need to *repeat*: do something many times without writing it out many times. This chapter\ncovers both. It also shows one of EK9's less expected choices: some familiar features are left\nout, because clearer and safer tools take their place.\n\n## Making a choice with `if`\n\nThe `if` statement runs a block of instructions only when a condition is true.\n\n<!-- listing: variant of examples/ch03-decisions-and-loops/Weather.ek9 -->\n```ek9\n#!ek9\ndefines module decisions\n\n  defines program\n\n    Weather()\n      -> temperature as Integer\n\n      stdout <- Stdout()\n\n      jacketBelow <- 18\n      if temperature < jacketBelow\n        stdout.println(\"Bring a jacket\")\n```\n\nTwo lines need explaining.\n\nThe line `-> temperature as Integer` means the program is *given* a temperature when it runs, so\nit can react to different values. The next section shows how that works and how to run a program\nwith a value. For now, read it as: a temperature comes in.\n\nThe line `jacketBelow <- 18` may look odd. Why not write `if temperature < 18`? Because EK9 will\nnot let you compare against a bare number like `18`; you must give it a name first. The name does\nreal work: it says what `18` *means*. \"Below the jacket temperature\" is clearer than a lone `18`\ninside a condition. Two values are exempt, because they seldom hide a meaning: `0` and `1`. So\n`countdown > 0`, later in this chapter, needs no name.\n\nNow the condition itself. `temperature < jacketBelow` uses the `<` operator to compare two\nnumbers. It gives back a `Boolean`, `true` or `false`. When the condition is `true`, the indented\nblock runs; when it is `false`, the block is skipped.\n\n> **Note.** EK9 also refuses a different mistake here. Suppose you had written\n> `temperature <- 14` and then `if temperature < 18`. EK9 would not build it: the compiler can\n> see that `14` is always less than `18`, so the answer never changes. An `if` whose answer is\n> already known is pointless, and usually a sign of a real bug. That is why the temperature comes\n> in from outside: so the answer depends on the value.\n\nYou can offer another path with `else`, and test more conditions with `else if`. Each number\ncompared against gets a name, for the same reason as before:\n\n```ek9\nwarm <- 25\ncold <- 10\nif temperature > warm\n  stdout.println(\"It is warm\")\nelse if temperature < cold\n  stdout.println(\"It is cold\")\nelse\n  stdout.println(\"It is mild\")\n```\n\nEK9 checks each condition from the top. The first one that is true wins: its block runs, and the\nrest are skipped. If none is true, the `else` block runs. Exactly one of the three messages prints,\nevery time.\n\n> **Note.** EK9 writes this as `else if`, two ordinary words. Some languages use one word, such\n> as `elif`; in EK9 that is a syntax error.\n\n## Giving a program a value\n\nThe weather program needs a temperature. You give it to the program when you run it.\n\nLook again at the first lines of the program:\n\n```ek9\n    Weather()\n      -> temperature as Integer\n```\n\nThe `->` means \"this comes in\". So `temperature as Integer` says: the program is given one value,\na whole number, called `temperature`. To run it with a temperature of `12`, type this at the\ncommand line:\n\n```console\nek9 Weather.ek9 12\n```\n\nOn the command line, everything you type is text: `12` is the characters \"1\" and \"2\". The program\nasked for an `Integer`, so EK9 turns that text into an `Integer` before your code runs. If you type\nsomething that is *not* a whole number, EK9 stops with a message instead of running with nonsense.\nThe value is checked and correctly typed from the moment it arrives.\n\nA program can ask for other types too, and EK9 converts the text you type: `String`, `Integer`,\n`Float`, `Boolean`, `Character`, `Date`, `Time`, `DateTime`, `Duration`, `Money`, `Dimension`,\n`Colour`, and a few more. A program could ask for `-> chosenDay as Date`, and you would pass a date\nlike `2027-03-14`. (Typed as `2027-3-14`, it is refused: the month and day each need two digits.)\n\nA program can also take several values, read files, and handle options like `-v`; the chapter\n*Programs, Input and Output* covers those. One value coming in is enough for now.\n\n## The same idea, spelled `when`\n\nEK9 lets you write `when` in place of `if`. The two behave the same:\n\n<!-- listing: fragment -->\n```ek9\nwhen temperature < jacketBelow\n  stdout.println(\"Bring a jacket\")\n```\n\nCode reads better when the word fits the meaning. `if` suits an either/or choice; `when` reads\nmore naturally for \"whenever this is true, do this\". Use whichever makes the line clearer.\n\n## Joining conditions\n\nYou can join conditions with `and`, `or` and `not`, which mean what they mean in English:\n\n<!-- listing: fragment -->\n```ek9\nchilly <- 18\nhot <- 26\nif temperature > chilly and temperature < hot\n  stdout.println(\"Pleasant\")\n```\n\nThis block runs only when *both* parts are true. Use `or` when *either* part is enough, and `not`\nto reverse a condition. When a condition grows long, you may break it across several lines, lining\nthe parts up under the first one.\n\n## Choosing among many values with `switch`\n\nA long chain of `if` / `else if` is hard to read when you are checking one value against many\npossibilities. For that, use `switch`:\n\n```ek9\n#!ek9\ndefines module decisions\n\n  defines program\n\n    //Choosing among several values with 'switch'.\n    //One 'case' can list several values, and there is no fall-through.\n    DayKind()\n      -> day as Integer\n\n      stdout <- Stdout()\n\n      switch day\n        case 1, 2, 3, 4, 5\n          stdout.println(\"Weekday\")\n        case 6, 7\n          stdout.println(\"Weekend\")\n        default\n          stdout.println(\"Not a day of the week\")\n```\n\n`switch day` looks at the value of `day`. Each `case` lists one or more values to match. The first\nmatching case runs, and the `default` case runs when nothing else matched. Run it with `6` and it\nprints:\n\n```text\nWeekend\n```\n\nThree things here are deliberate.\n\nFirst, **one case can list several values**: `case 1, 2, 3, 4, 5` matches any weekday, so you do\nnot need five separate cases.\n\nSecond, **there is no \"fall-through\"**. In some older languages, a `switch` keeps running into the\nnext case unless you add a word (`break`) to stop it, and forgetting that word is a classic bug,\nrecorded both in the CERT C coding standard (recommendation MSC17-C) and in the weakness list\nCWE-484, \"Omitted Break Statement in Switch\". In EK9 the matching case runs, and that is all.\n\nThird, **the `default` is required**. Every `switch` must end with one, so there is always an\nanswer for a value no `case` listed. Leave it out and the program does not build\n(`E07320: 'default' is required in this 'switch' statement`). No unhandled value slips through\nunnoticed.\n\n### Cases can compare, not just match\n\nSo far each `case` has listed exact values. `case 6, 7` means \"is the value `6`, or is it `7`?\" —\na test of *equality*, and often all you need.\n\nA `case` can also compare, using `<`, `>` or any of EK9's comparisons:\n\n```ek9\n#!ek9\ndefines module decisions\n\n  defines program\n\n    Grade()\n      -> score as Integer\n\n      stdout <- Stdout()\n\n      passMark <- 40\n      meritMark <- 60\n      distinctionMark <- 75\n\n      switch score\n        case < passMark\n          stdout.println(\"Fail\")\n        case < meritMark\n          stdout.println(\"Pass\")\n        case < distinctionMark\n          stdout.println(\"Merit\")\n        default\n          stdout.println(\"Distinction\")\n```\n\nRun it with a score of `55`:\n\n```text\nPass\n```\n\nHere **order matters**. A score of `55` is below `60` *and* below `75`, so two cases are true at\nonce. EK9 checks the cases **from the top down, and the first one that matches wins**; nothing\nbelow it is looked at. `55` fails the first test (`< 40`), passes the second (`< 60`), and stops\nthere, printing `Pass`.\n\nSo write comparison cases from the **lowest boundary upward**, letting each case assume the ones\nabove it have already ruled out the lower values. Put `< 75` first and *every* passing score would\nmatch it; nobody would ever see `Merit` or `Distinction`. The order is part of the meaning.\n\nSo `switch` is two tools under one word. With value cases (`case 6, 7`) it is a lookup where\norder does not matter, because a value can equal only one thing. With comparison cases\n(`case < 60`) it is a **chained `if` / `else if`**, checked top to bottom, where order is\neverything. You can mix the two in one `switch`. In both, `default` is the final **`else`**: the\ncatch-all that runs when no case above it matched.\n\n> **Note.** Because equality is the most common test, a bare `case 6` is shorthand for\n> `case == 6`. You can write the `==` out when it makes the intent clearer.\n\n> **Coming later.** Here the switch is on plain numbers. Often you are really choosing among a\n> small, *fixed* set of named things — the suits in a deck of cards, the days of the week, the\n> states of a traffic light. EK9 lets you define such a set, called an **enumeration**, and\n> `switch` works well with one. The chapter *Records and Enumerations* brings this `switch` back\n> with real names like `Monday` in place of `1`.\n\n## Repeating with a range\n\nTo do something a fixed number of times, count over a **range** with `for`:\n\n<!-- listing: variant of examples/ch03-decisions-and-loops/Counting.ek9 -->\n```ek9\n#!ek9\ndefines module repetition\n\n  defines program\n\n    Counting()\n      stdout <- Stdout()\n\n      for i in 1 ... 10\n        stdout.println(`Value [${i}]`)\n```\n\n`1 ... 10` is a range from 1 to 10, including both ends. The loop runs its block once for each\nvalue, and each time the name `i` holds the current number. This prints `Value [1]` through\n`Value [10]`, ten lines. The loop makes `i` itself; you do not declare it.\n\nYou can change the step with `by`:\n\n```ek9\nfor i in 0 ... 10 by 2\n  stdout.println(`Even [${i}]`)\n```\n\nThis counts `0, 2, 4, 6, 8, 10`. A negative step counts down:\n\n```ek9\nfor i in 10 ... 0 by -2\n  stdout.println(`Down [${i}]`)\n```\n\n## Repeating while something is true\n\nSometimes you do not know how many times to repeat; you only know the *condition* for carrying on.\nThen use `while`:\n\n```ek9\ncountdown <- 5\nwhile countdown > 0\n  stdout.println(`${countdown}...`)\n  countdown := countdown - 1\nstdout.println(\"Lift off\")\n```\n\nThe `while` block runs as long as its condition is true. Each pass prints the number, then makes\n`countdown` one smaller with `:=`. After five passes `countdown > 0` is false, and the loop stops.\n\n## Running at least once: `do` / `while`\n\nA plain `while` checks its condition *first*, so if the condition is false at the start, the\nblock never runs. When the block should run *once* before the check, use `do` / `while`:\n\n```ek9\n#!ek9\ndefines module repetition.countup\n\n  defines program\n\n    //'do ... while' runs the block once, then keeps going while the test is true.\n    Countup()\n      -> stopAt as Integer\n\n      stdout <- Stdout()\n\n      n <- 1\n      do\n        stdout.println(`${n}`)\n        n++            //short for n := n + 1\n      while n <= stopAt\n```\n\nThe `do` block always runs at least once. Then the `while` line is checked, and the block repeats\nas long as it is true. Run it with a `stopAt` of `3` and it prints:\n\n```text\n1\n2\n3\n```\n\n`stopAt` is a value the program is given when it runs, like the temperature earlier. `n++` is\nshort for `n := n + 1`, \"add one to `n`\"; `n--` takes one away. The only difference from a plain\n`while` is *when the check happens*: `while` checks before the first run, `do` / `while` after it.\n\n## The features that are not here\n\nMany languages have three instructions for jumping out of the middle of code: `break`, to leave\na loop early; `continue`, to skip to the next pass; and `return`, to leave a block of code partway\nthrough. **EK9 has none of them.** This is deliberate.\n\nThe reason is evidence, not taste. Jumps out of the middle make it hard to see, from the shape of\nthe code, which lines will run — the argument Edsger Dijkstra made against unstructured jumps in\n1968.[^jumps] The results are loops that exit at the wrong moment, checks that get skipped, and\nsecurity holes from leaving a block earlier than intended. One well-known case, \"goto fail\",\nskipped a security check on Apple's iOS and macOS because of a single stray jump.[^gotofail]\nRather than warn you about misusing these tools, EK9 removes them: the idea from *Hello, EK9*,\napplied to control flow.\n\nWhat you use instead are tools that say what you *mean*:\n\n- Instead of looping and `break`-ing out once you have what you need, you describe the result you\n  want, and EK9 stops at the right point.\n- Instead of `continue`-ing past items you do not want, you *filter* them out before the loop sees\n  them.\n- Instead of `return`-ing a value from the middle of a block, you name the result up front, and the\n  compiler checks that every path through your code sets it.\n\nThe first two replacements come from EK9's **stream pipelines**, which process a collection of\ndata in a line that reads almost like a sentence:\n\n<!-- listing: fragment -->\n```ek9\n// cat = \"take each item\", filter = \"keep the ones that match\"\n//   cat readings | filter by inComfortRange | collect as List of Integer\n```\n\nPipelines have a chapter of their own. Nothing was taken away without something clearer put in\nits place.\n\n## A map of what is coming\n\nYou now have the everyday tools for choosing and repeating. EK9 has a few more ways to control\nwhat happens and in what order. They work differently, and each gets its own chapter, but it helps\nto know they exist:\n\n- **Stream pipelines** control flow *over a whole collection of data*. Instead of a loop, you write\n  a line like `cat items | filter by ... | map with ...`, and the data flows through it. This is\n  how EK9 replaces loops with `break` and `continue`. *(Streams and Pipelines.)*\n- **Exceptions** control flow *when something goes wrong*. A `try` block runs your code, and a\n  `catch` block takes over if it fails. *(Errors and Exceptions, in the second volume,\n  EK9 in Depth.)*\n- **Guards** take a value *and* check it is really there, in one step. The same pattern works\n  inside `if`, `while`, `for` and `switch`. *(Guards and Safe Code.)*\n- **Expression forms** let a choice or a loop *hand back a value*. A `switch`, a `for` or a\n  `while` can produce a result you store in a variable. An `if` cannot; a simple either/or uses a\n  short form called the *ternary*, first used in *Speaking Every Language*. *(Guards and Safe Code.)*\n\n## Try it yourself\n\n1. Write a program that prints whether a number is negative, zero, or positive. Use `if` /\n   `else if` / `else`. (The number must come *in* to the program, and any value you compare\n   against needs a name, except `0` and `1`.)\n2. Use a `switch` to turn a month number (`1`–`12`) into its season. Group the months with\n   multi-value cases, and use `default` for anything out of range.\n3. Use a `for` loop to print the two-times table, from `2` to `20`.\n4. Rewrite exercise 3 as a `while` loop, then as a `do` / `while` loop. Which reads most clearly to\n   you, and why?\n\n## Recap\n\nYou can make decisions with `if`, `else if`, `else` and `when`, join conditions with `and`, `or`\nand `not`, and choose among many values with `switch`: several values per case, comparison cases\nlike `case < 40`, first match wins, and no fall-through. You can repeat work with `for` over a\nrange, with `while`, and with `do` / `while` when the block must run at least once. EK9 has no\n`break`, `continue` or `return`, and you have seen what replaces them. And you have a map of the\nlarger control-flow ideas to come: stream pipelines, exceptions, guards and expression forms.\n\nRemove the sharp edge, supply a better tool: that pattern recurs throughout EK9. Functions are\nnext, so you can name and reuse pieces of logic instead of repeating them.\n\n[^jumps]: Edsger W. Dijkstra, \"Go To Statement Considered Harmful\", *Communications of the ACM*,\n1968 — the classic argument for structured control flow over unstructured jumps. See the evidence\nappendix for plain-language notes.\n\n[^gotofail]: The Apple \"goto fail\" bug (2014, CVE-2014-1266): a duplicated `goto fail;` line\nskipped TLS signature verification on iOS and macOS, weakening secure connections. It is one of\nthe clearest real-world arguments for removing mid-block jumps from a language.\n","examples":["books/getting-started-with-ek9/ch03-decisions-and-loops/Countdown.ek9","books/getting-started-with-ek9/ch03-decisions-and-loops/Counting.ek9","books/getting-started-with-ek9/ch03-decisions-and-loops/Countup.ek9","books/getting-started-with-ek9/ch03-decisions-and-loops/DayKind.ek9","books/getting-started-with-ek9/ch03-decisions-and-loops/Grade.ek9","books/getting-started-with-ek9/ch03-decisions-and-loops/Weather.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 4","title":"Functions","url":"https://ek9.io/books/getting-started-with-ek9/functions.html","markdown":"# Functions\n\nSo far, each program has been one block of instructions from top to bottom. Real programs do the\nsame job in many places — squaring a number, greeting a person, checking a price — and copying the\nsame lines again and again invites mistakes. A **function** lets you write a piece of work once,\ngive it a name, and use it as often as you like.\n\nYou have already *used* one: `stdout.println(...)` calls a function. In this chapter you write\nyour own.\n\n## Your first function\n\nHere is a function that squares a number, that is, multiplies it by itself.\n\n<!-- listing: variant of examples/ch04-functions/Functions.ek9 -->\n```ek9\n#!ek9\ndefines module functions.demo\n\n  defines function\n\n    square() as pure\n      -> n as Integer\n      <- result as Integer: n * n\n\n  defines program\n\n    Demo()\n      -> start as Integer\n      stdout <- Stdout()\n      stdout.println(`square of ${start} is ${square(start)}`)\n```\n\nRun it with a `5` and it prints:\n\n```text\nsquare of 5 is 25\n```\n\nLook at the function on its own:\n\n```ek9\n    square() as pure\n      -> n as Integer\n      <- result as Integer: n * n\n```\n\nIt has three parts, all built from pieces you have met. (The `as pure` on the first line is\noptional and is explained in its own section below.)\n\n`square()` names the function. The round brackets mark it as something you can *call*, like a\nprogram.\n\n`-> n as Integer` is the **input**, also called a *parameter*. The `->` means \"this comes in\", as\nit did for a program's command-line value in *Making Decisions and Repeating Work*. This function\nis given one whole number, and inside the function that number is called `n`. You must *use* it:\ndeclare an input and ignore it in the body, and EK9 will not build the function (`E08091`). An\nunused input is nearly always a leftover or a slip.\n\n`<- result as Integer: n * n` is the **output**, also called the *return value*. The `<-` here\nmeans \"this goes back out\". The function returns one `Integer`, called `result`, and its value is\n`n * n`.\n\nThe return value is a *variable*, like those in *Values and the Three States*: declared, given a\nstarting value, and handed back when the function ends. Here the starting value *is* the answer.\nSometimes it reads better to give the return value a plain starting value and settle it inside\nthe body, with an `if`, say. When that starting value is simple — a literal like `0`, or a new\nunset value like `String()` — you can let EK9 infer the type with `<-`, as for ordinary variables:\n\n<!-- listing: fragment -->\n```ek9\n    describe()\n      -> known as Boolean\n      <- result <- String()      // start empty, fill it in below\n      if known\n        result: \"known\"\n      else\n        result: \"unknown\"\n```\n\nA *computed* value, worked out with an operator or another call like `n * n`, keeps the longer\n`as Type:` form; the short `<-` is only for a simple starting value. The same short form returns\nlater, when `Result` and `Optional` are declared with an empty starting value.\n\n## Calling a function\n\nTo *use* a function, you call it by name and give it the value it asks for (an *argument*):\n\n<!-- listing: fragment -->\n```ek9\nsquare(start)\n```\n\nIf `start` is `5`, then `square(start)` works out to `25`. A call stands for the value it\nproduces, so you can put it inside a larger expression — here, inside a string:\n\n<!-- listing: fragment -->\n```ek9\nstdout.println(`square of ${start} is ${square(start)}`)\n```\n\nThat is the point of a function: you write the \"how\" once, and everywhere else you use the name.\n\n> **Note.** You cannot *run* a function on its own; it does something only when something else\n> calls it. So far, that is a **program**: \"run it\" means run the program, which calls the\n> function. The next chapter shows another way to exercise a single function — a **test** — and\n> the habit of writing the test *before* the code.\n\n## More than one input\n\nA function can take more than one value. List them in an indented block under a single `->`:\n\n```ek9\n    add() as pure\n      ->\n        a as Integer\n        b as Integer\n      <- total as Integer: a + b\n```\n\n`add` takes two numbers, `a` and `b`, and returns their sum. You call it with two values:\n\n<!-- listing: fragment -->\n```ek9\nadd(2, 3)     // works out to 5\n```\n\n> **Note.** Write the `->` once, then list the inputs under it. A separate `->` for each input is\n> a compile error.\n\n## Functions can use other functions\n\nA function's body is ordinary code, so it can call other functions, including your own. This one\nadds up two squares by reusing `square` and `add`:\n\n```ek9\n    sumOfSquares() as pure\n      ->\n        a as Integer\n        b as Integer\n      <- total as Integer: add(square(a), square(b))\n```\n\n`square(a)` and `square(b)` are worked out first, and their results are handed to `add`. With `a`\nof `5` and `b` of `3`, that is `25 + 9`, so `sumOfSquares(5, 3)` is `34`. Small functions built\nfrom smaller functions are how large programs stay understandable.\n\n## Sometimes there is nothing to return\n\nNot every function gives a value back. Some do a job: print a message, save a file, start\nsomething off. When a function has nothing to return, *leave out the `<-` line*:\n\n```ek9\n#!ek9\ndefines module functions.noreturn\n\n  defines function\n\n    //No '<-' line: this function does its work and returns nothing.\n    announce()\n      -> name as String\n      stdout <- Stdout()\n      stdout.println(`Hello, ${name}`)\n\n  defines program\n\n    Demo()\n      announce(\"Ada\")\n      announce(\"Grace\")\n```\n\n`announce` has an input (`->`) but no output line, so it returns nothing. Run it and it prints:\n\n```text\nHello, Ada\nHello, Grace\n```\n\nWith no value to use, you call such a function as a line on its own: `announce(\"Ada\")`. There is\nno keyword to write for \"returns nothing\"; leaving out the `<-` line says it.[^void]\n\n## `pure`: a promise not to change things\n\n`as pure` is a promise about *change*.\n\nA pure function may **declare** as many variables as it likes; what it may not do is **change**\none once it is set. It cannot reassign its variables, and it cannot alter the inputs it was given.\nThe result it is building is the exception: filling that in is the point of the function.\n\nReassign an ordinary variable inside a pure function and EK9 stops you:\n\n<!-- listing: fragment -->\n```ek9\ncount <- 0\ncount := count + 1     // not allowed inside a pure function\n```\n\nThe compiler refuses the second line and suggests `:=?`, the assign-if-unset operator, which\n*Guards and Safe Code* introduces. `square`, `add` and `sumOfSquares` are pure with no effort:\neach declares a result, works it out, and returns it.\n\n`pure` does *not* forbid real work. A pure function can print (the printing operations are\nthemselves pure). It may only call other pure functions, so the promise holds all the way down.\n\nEK9 uses the word in its own way.[^purity] In mathematics, and in functional languages, a *pure*\nfunction has no effect on the outside world at all: it may not print or touch a file, only\ncompute. EK9's `pure` is a rule about **change**, not about **effects**: do not reassign, do not\nalter what you were given. Printing a line changes none of your program's own values, so EK9\nallows it; reassigning a variable does, so EK9 forbids it. That is what lets `pure` be a promise\nyou keep in ordinary code, including code that writes to the screen.\n\nWhy does it matter? Nothing changes under you while you read a pure function. `square(5)` always\ngives `25`, because `square` uses only its input. (`pure` itself promises only that nothing is\nreassigned or altered, not that every pure function gives the same answer each time.) Code you can\ntrust like that is code you can build on; the idea returns in later chapters.\n\n> **A fair question.** If you cannot reassign a variable, how do you work out a result that\n> *depends* on a condition, or one built up in a loop? EK9's answer is to let a choice or a loop\n> *produce a value*, which sets your result in one go. For a simple either/or there is a short\n> **ternary** form; for a bigger choice, a `switch` that hands back a value; for a loop, a `for`\n> that hands back a value. They exist *because* a pure function needs them. *Guards and Safe Code*\n> covers them.\n\n## `require`: saying what must be true first\n\nSometimes a function only makes sense if its input meets a condition. You state that condition with\n`require`. It is a **precondition**: something that must be true *before* the work runs.[^contract]\n\n```ek9\n    halve() as pure\n      -> n as Integer\n      <- result as Integer?\n      require n?\n      result: n / 2\n```\n\n`require n?` says `n` must be *set*. If it is not, the program **stops** completely. It *panics*:\nit halts with a message naming the broken requirement, and exits with a non-zero code. To see it,\nhere is a caller with a deliberate bug: it hands `halve` an unset `Integer()` (the file is\n`HalveNothing.ek9`, with the same `halve` as above):\n\n```ek9\n    Broken()\n      stdout <- Stdout()\n      stdout.println(`half is ${halve(Integer())}`)\n```\n\nRunning it prints:\n\n```text\nException in thread \"main\" Panic: Requirement failed: `n?` at ./HalveNothing.ek9:10:7: Exit Code: 1\n```\n\nA non-zero exit code is how a program tells whatever ran it \"I failed\". This is a hard stop, not a\nwarning, and that is what you want, because of what a broken `require` *means*.\n\nA `require` is a promise the *caller* must keep. If it is broken, a value arrived that never should\nhave: a **bug in the code that called the function**, not something a person using your program\ndid. Stopping loudly at the broken promise is far better than carrying on and producing a wrong\nanswer that is found days later.\n\nSo `require` is for things that should *always* be true. It is **not** for input you *expect* might\nbe wrong, such as someone mistyping their age or leaving an answer blank. That is normal, and you\nhandle it by checking the value (with `?` and the tools in later chapters) and telling the person\nwhat to fix. `require` says: \"this can never happen, and if it does, there is a defect, so stop.\"\n\n> **Note.** `require` is not the same as `assert`, which the next chapter introduces. `require`\n> guards real code: it states what a function needs. `assert` belongs to tests, where you check\n> that code did the right thing.\n\n## One value out\n\nA function returns *at most one* value: one (like `square`) or none (like `announce`). That is\ndeliberate. A call stands for one value, so you always know what you are getting.\n\nTo hand back several pieces of information at once, say a name *and* an age, you bundle them into\none thing, called a **record**, and return that. Records are introduced in *Records and\nEnumerations*.\n\n## Try it yourself\n\n1. Write a function `cube` that returns `n * n * n`. Call it from a program and print the cube of\n   a number you pass in.\n2. Write a function `bigger` that takes two numbers and returns the larger. (Hint: an `if` inside\n   the function, setting the return value.)\n3. Add `require n?` to your `cube` function. Does it still work for normal numbers?\n4. Write two `->` arrows, one per input, on a two-input function. Read the compiler's error, then\n   change it to a single `->` with an indented list.\n\n## Recap\n\nA **function** is a named piece of work you can use again and again. It takes inputs with `->`,\nreturns at most one value with `<-`, and is called by name. Functions can call other functions,\nwhich is how large programs are built from small, understandable pieces. **`as pure`** promises\nthat a function changes nothing except the result it is producing; it can still do work, even\nprint. **`require`** states a precondition, and stops the program if it is broken, because a\nbroken `require` means a bug in the calling code.\n\nNext, you check that your functions do what you think. You will write your first *test*, and see\nwhy, in EK9, testing is part of writing code from the start.\n\n[^void]: Many languages have a word such as `void` for \"returns nothing\". EK9 has no such keyword\nto write.\n\n[^purity]: Two familiar reference points frame where EK9 sits. Most mainstream languages — Java,\nPython, JavaScript, C# — have no `pure` keyword: nothing stops a function reassigning its variables\nor changing shared state, and any discipline lives in convention and review. The functional\nlanguages that *do* enforce purity, such as Haskell, take the strict view: a pure function may\nperform no side effect at all, so even printing goes through special machinery. EK9 sits between\nthe two: purity is checked by the compiler, as in Haskell, but scoped to *change* rather than *all\neffects*. Treat EK9's meaning as its own rather than mapping it onto one you met elsewhere.\n\n[^contract]: Preconditions and postconditions are long-standing ideas in software engineering. A\n*precondition* is what must be true *before* a piece of code runs; a *postcondition* is what it\npromises *after*. C. A. R. Hoare gave the formal basis in \"An Axiomatic Basis for Computer\nProgramming\" (1969). Bertrand Meyer built it into a whole method, *Design by Contract*, in the\nEiffel language (1986), described in his book *Object-Oriented Software Construction* (1988). A\ncentral rule of that method is the one used here: if a precondition is broken, the **caller** is\nat fault, so the program should fail fast rather than carry on. `require` is EK9's precondition.\n","examples":["books/getting-started-with-ek9/ch04-functions/Announce.ek9","books/getting-started-with-ek9/ch04-functions/Describe.ek9","books/getting-started-with-ek9/ch04-functions/Functions.ek9","books/getting-started-with-ek9/ch04-functions/Halve.ek9","books/getting-started-with-ek9/ch04-functions/HalveNothing.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 5","title":"Testing as You Go","url":"https://ek9.io/books/getting-started-with-ek9/testing.html","markdown":"# Testing as You Go\n\nYou can now write functions. How do you *know* a function hands back the right answer? And a\nsmaller puzzle sits underneath: so far the only thing you could run was a *program*. A function is\nnot a program; it is called by other code. So how do you run a single function on its own, to see\nwhat it does?\n\nThe answer to both is a **test**: a small piece of code that runs one of your functions with an\ninput you choose and checks the answer. It is the clean way to exercise a function by itself, and,\nkept as you go, it is how you stay sure your code is still right tomorrow.\n\n## Why test, and why early\n\nIt is tempting to treat testing as something done at the end, once the \"real\" work is finished.\nLeft to the end, tests get rushed, skipped, or written to pass rather than to catch anything.\n\nEK9 takes a firm line. You cannot *publish* a library in EK9 unless enough of its code is covered\nby tests: the compiler measures it and refuses to package work that falls short.[^coverage] You\nmeet the same bar before publishing: **every** `ek9 -t` run requires 80% of your code to be\nexercised, and reports a shortfall (with a non-zero exit code) even when every test passed. A test\nis part of writing the code, in the same way that getting it to compile is. So test *as you go*:\nwrite a little, check a little, and never build on a floor you have not stood on.\n\nNone of this is new. The value of testing early is old, settled advice. What EK9 changes is\n*where* testing lives: inside the language and the compiler, not in a separate tool you are\ntrusted to reach for. That is the approach of the whole book in miniature: a well-proven practice,\nturned from a suggestion into a rule.\n\n## A function worth checking\n\nHere is a small file with two functions to test. Put them in a file called `maths.ek9`.\n\n```ek9\n#!ek9\ndefines module book.maths\n\n  defines function\n\n    square() as pure\n      -> n as Integer\n      <- result as Integer: n * n\n\n    cube() as pure\n      -> n as Integer\n      <- result as Integer: n * n * n\n```\n\nThese are two `pure` functions, each taking an `Integer` and returning one, as in the last\nchapter. `square(3)` should give `9`, and `cube(2)` should give `8`. A test makes the computer\nconfirm it.\n\n## Where tests live\n\nTest code goes in a directory named `dev/`, next to your program. Anything under `dev/` is\n*development* code — tests and scratch work — kept apart from the code you ship. Your tests can be\nas thorough as you like without adding a line to the program you deliver.\n\nInside `dev/`, make a file `tests.ek9`:\n\n```ek9\n#!ek9\ndefines module book.maths.tests\n\n  references\n    book.maths::cube\n    book.maths::square\n\n  defines program\n\n    @Test\n    SquareTest()\n      assert square(3) == 9\n\n    @Test\n    CubeTest()\n      assert cube(2) == 8\n```\n\nThree new things do the work here.\n\n**`references`** brings in the functions to test. `book.maths::square` is the full name of\n`square`: its module, then `::`, then the function. Listing it under `references` lets this file\nuse `square` and `cube` by their short names.\n\n**`@Test`** marks the program that follows as a test. The test runner looks for this mark to know\nwhat to run. A test program's name, like `SquareTest`, says what it checks.\n\n**`assert`** states something that must be true. `assert square(3) == 9` says: \"`square(3)` equals\n`9`.\" If the claim holds, the test passes; if not, the test fails and tells you so. A test must\ncheck *something*: a `@Test` with no `assert` (and no file of expected output, which the second\nvolume covers) will not compile (`E81007`), because a test that checks nothing would pass without\nproving anything.\n\n> **Note.** `cube` is listed before `square` under `references`, even though the tests use\n> `square` first. EK9 requires references in alphabetical order, and the compiler reports it if\n> they are not, so a long list of references is always easy to scan.\n\n## Running the tests\n\nRun your tests with the `-t` flag, `t` for *test*:\n\n```console\nek9 -t maths.ek9\n```\n\nThe runner compiles everything, finds the tests, runs them, and reports:\n\n```text\nℹ️ Found 2 tests:\n  2 assert (unit tests with assertions)\n\nExecuting 2 tests...\n\n✅ PASS book.maths.tests::CubeTest [Assert] (3ms)\n✅ PASS book.maths.tests::SquareTest [Assert] (3ms)\n\nSummary: 2 passed, 0 failed (2 total)\nTypes: 2 assert\nDuration: 7ms\n```\n\nEach test has a `✅ PASS` line, and the summary reads `2 passed, 0 failed`. Both claims held, and\nthe proof can be run again at any time.\n\nThe IDE shows the same run. In the picture below, the *Tests* tab lists both tests with a green\ntick, and the bodies of `square` and `cube` in the editor are shaded to show the lines your tests\nran. That shading is **coverage**: a picture of which code your tests have exercised. Here every\nline is covered.\n\n![Running the tests in the EK9 IDE. The Tests tab reports both tests passed, and the shading over the\nbodies of `square` and `cube` shows the lines the tests\ncovered.](images/square-cube-coverage.png){width=100%}\n\n> **Note.** On a colour terminal EK9 also colours this output: `PASS` in green, test names in\n> cyan, timings dimmed. The page shows the same text without colour. The timings in brackets will\n> differ on your machine.\n\n## Covered is not the same as tested\n\nCoverage here is 100%: every line of `square` and `cube` ran. That does not mean \"fully tested\".\n\nLook at what was tried: `square(3)` and `cube(2)`, two small *positive* numbers. Not zero, not a\nnegative, not a huge number or the largest an `Integer` can hold, not an *unset* value. Each of\nthose is a different *kind* of input, and the two tests touched one kind between them. A function\ncan run every one of its lines and still have been asked only the easiest question. **100% coverage\nmeans every line *ran*, not that your code is *right*.** Coverage counts how much of the code you\nvisited, not the *variety* of inputs you visited it with.\n\nThe tool that builds your code can also report that variety: how many *kinds* of input your tests\ndrove, shown beside the coverage, together with a figure for how *complex* each function\nis.[^tooling] Only coverage is a hard rule; the variety figure is a report that shows where your\ntests are thin.\n\nTools in the IDE can help write the missing edge cases; the IDE companion book (`ek9.io/ide/`)\ncovers them, and the second volume goes into testing in depth. For now: **a full coverage bar is\nwhere good testing starts, not where it finishes.**\n\n## When a test fails\n\nA test earns its keep on the day it *fails*. Suppose you write `n + n` where you meant `n * n`\nwhile editing `square`:\n\n<!-- listing: fragment -->\n```ek9\n    square() as pure\n      -> n as Integer\n      <- result as Integer: n + n\n```\n\nIt still compiles: `n + n` is valid code, just not a square. For `n` of `2` the two even agree\n(`2 + 2` and `2 * 2` are both `4`), so a quick check might miss it. Run the tests:\n\n```text\nℹ️ Found 2 tests:\n  2 assert (unit tests with assertions)\n\nExecuting 2 tests...\n\n✅ PASS book.maths.tests::CubeTest [Assert] (3ms)\n❌ FAIL book.maths.tests::SquareTest [Assert] (3ms)\n    Assertion failed: `square(3) == 9` at ./dev/tests.ek9:12:7\n\nSummary: 1 passed, 1 failed (2 total)\nTypes: 2 assert\nDuration: 6ms\nek9: tests failed (exit 11)\n```\n\nThe `❌ FAIL` line names the claim that broke, `square(3) == 9`, and where it is: `dev/tests.ek9`,\nline 12. `square(3)` came back as `6`, not `9`. There is no hunt; the test points at the problem.\nIt is the strict compiler's idea moved one step on: catch the mistake when it happens, and point\nat it.\n\n## `assert` is for tests only\n\n`require`, from the last chapter, states what must be true of a function's input and stops the\nprogram if that is broken. `assert` looks similar but has a different job, and EK9 keeps them\napart. `assert` belongs to **tests**: it checks that your code produced the right answer. `require`\nbelongs to **real code**: it guards what a function needs. The compiler rejects `assert` in a\nprogram you ship, so each word always means one thing.\n\n## Writing the test first\n\nOne way to use tests feels back to front at first: write the test *before* the function. State the\nanswer you want — `assert square(3) == 9` — run it, and watch it fail, because `square` does not\nexist yet or does nothing useful. Then write just enough to make it pass. The failing test is a\nsmall, clear target, and you are done when it passes.\n\nThis book does not insist on working this way, but try it once on your next function. Deciding what\n\"right\" means *before* writing the code tends to make the code simpler, because you build it to a\nknown answer.[^testfirst]\n\n## Try it yourself\n\n1. Add a `@Test` for `square(4)`. What answer should you assert? Run the tests.\n2. Break `cube` on purpose (say, `n * n`). Run the tests and read which line the runner points to,\n   then fix it and confirm the `✅ PASS` returns.\n3. Write the test first: add a `dev/` test that asserts `square(10) == 100` *before* the function\n   is right, see it fail, then make it pass.\n\n## Recap\n\nEK9 treats **testing** as part of writing code: you cannot publish without it, and every `ek9 -t`\nrun checks coverage. To run a single function by itself, write a **`@Test`** program in the\n**`dev/`** directory, using **`references`** to bring the function in and **`assert`** to state what\nmust be true. **`ek9 -t`** runs the tests and reports `✅ PASS`, or a `❌ FAIL` naming the broken\nclaim and its line. `assert` (for tests) and `require` (for real code) divide the work between them.\n\nYou now have the essentials: programs, values, decisions, loops, functions and tests. One skill\nremains before real data — reading the compiler when it stops you — and that is the next chapter.\n\n[^coverage]: \"Coverage\" is the share of your code that tests exercise. Requiring a minimum before\npublishing makes sure a library's promises have been checked, not just claimed. How it is measured\nis covered in the second volume.\n\n[^testfirst]: Writing the test first is the heart of *test-driven development* (TDD), set out by\nKent Beck in *Test-Driven Development: By Example* (Addison-Wesley, 2002). The claim is not that\ntests find every bug, but that deciding the expected result up front leads to simpler, better-shaped\ncode. The second volume returns to it.\n\n[^tooling]: In most languages, coverage and quality are *add-on* tools you choose, install and\nconfigure yourself — for example JaCoCo (Java) or Istanbul (JavaScript) for coverage, and\nSonarQube, Checkstyle or PMD for quality and complexity — usually wired into a separate build step\nor a continuous-integration server. In EK9 the same measurements come from the compiler, with\nnothing extra to install or configure, when you run `ek9 -t`.\n","examples":["books/getting-started-with-ek9/ch05-testing/dev/tests.ek9","books/getting-started-with-ek9/ch05-testing/maths.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 6","title":"Reading the Compiler's Guidance","url":"https://ek9.io/books/getting-started-with-ek9/reading-errors.html","markdown":"# Reading the Compiler's Guidance\n\nThis short chapter is about a habit rather than a feature of the language: how to *read* what the\ncompiler tells you, and treat each message as your next step. Once you can read the compiler, you\ncan teach yourself much of the rest.\n\n## An error is an instruction\n\nWhen a program will not build, the natural reaction is \"I did something wrong\". In EK9 an error is\nbetter read as: *here is the next thing to fix, and here is where it is.* The compiler found the\nproblem now, while you are looking at the code, instead of leaving it to surface later.\n\nSo when you see an error, do not guess and change things at random. **Read it.** EK9's messages\nare written to be read, and they carry more than \"something is wrong\".\n\n## The anatomy of a message\n\nHere is a real error. The program that caused it comes in a moment; first, look at the shape of\nthe message. This is everything the compiler prints:\n\n```text\nek9: compilation failed (exit 8)\nEK9     : PRE_IR_CHECKS: Errors in ./tautology.ek9\nEK9     : Error   : E08086: '<' on line 9 position 21: 'temperature < 18': condition is always true based on data flow analysis\n             See: ek9 -h E08086\nEK9     : Compilation failed\n```\n\nThe first line says the build failed, and the second names the file and the stage of checking that\nfound the problem. The lines that matter are the `Error` line and the `See:` line under it. Each part\nhas a job:\n\n- **`E08086`** — the error's *code*: a stable name you can look up, quote or search for. Every\n  distinct rule has one.\n- **`'<' on line 9 position 21`** — *where*: the exact token, line and column.\n- **`'temperature < 18'`** — the *offending piece*, quoted back to you, so you know which part it\n  means without counting characters.\n- **`condition is always true ...`** — the *explanation*: what is wrong and why.\n- **`See: ek9 -h E08086`** — *how to learn more*. Every message tells you how to get the full\n  explanation, covered below.\n\nWith those five parts in view, an EK9 error is a location, a snippet, a reason, and a pointer to\nmore help.\n\nHere is the same error in the IDE:\n\n![The always-true error (E08086) in the EK9 IDE. The `<` on line 9 is marked in the editor; the *Hovers*\npane on the right gives the message, its explanation and the suggested actions; and the *Answers* tab\nbelow shows a related question and answer with worked\nexamples.](images/ide-error-anatomy.png){width=100%}\n\n## Four errors you will meet\n\nHere are four mistakes beginners make. Each is a small, broken program, shown with its message,\nwhat the message means, and the fix. The point is not to memorise them but to see the pattern of\nreading and responding.\n\n### The condition that is always true\n\n```ek9\ntemperature <- 14\nif temperature < 18\n  stdout.println(\"Bring a jacket\")\n```\n\n```text\nEK9     : Error   : E08086: '<' on line 9 position 21: 'temperature < 18': condition is always true based on data flow analysis\n             See: ek9 -h E08086\n```\n\n(From here on, only the `Error` line and the lines under it are shown.) `temperature` is set to\n`14`, then the program asks whether it is below `18`. It always is. The compiler followed the\nvalues and saw that the `if` can only go one way, so the check is pointless and the unwritten\n\"else\" can never run. The fix is the one from *Making Decisions and Repeating Work*: let the value\ncome from *outside* the program — an argument, an input, a real reading — so the answer is unknown\nuntil the `if` runs.\n\n### The magic number at a decision\n\n<!-- listing: fragment -->\n```ek9\nCheck()\n  -> score as Integer\n  if score > 50\n    stdout.println(\"pass\")\n```\n\n```text\nEK9     : Error   : E11064: '50' on line 9 position 17: '50' literal in comparison/range - give it a meaningful name\n             See: ek9 -h E11064\n```\n\nHere `score` does come from outside, so the condition is fair. The complaint is the bare `50`. A\nraw number at a decision point does not tell the reader *why* fifty. The fix is to give it a name\nthat says what it means:\n\n<!-- listing: fragment -->\n```ek9\nCheck()\n  -> score as Integer\n  passMark <- 50\n  if score > passMark\n    stdout.println(\"pass\")\n```\n\nNow the line states its intent, and if the pass mark changes there is one place to change it.[^magic]\n\n![The magic-literal error (E11064) on `if score > 50`. The editor marks the bare `50`, and the Hovers\npane and the Answers tab explain why a value at a decision point needs a\nname.](images/ide-error-magic.png){width=100%}\n\n### Changing a value inside `pure`\n\n```ek9\ntally() as pure\n  -> start as Integer\n  <- result as Integer: start\n  running <- start\n  running := running + 1\n  result: running\n```\n\n```text\nEK9     : Error   : E08100: ':=' on line 10 position 14: 'running as Integer': reassignment not allowed when scope is marked as 'pure' (':=?' is supported)\n             See: ek9 -h E08100\n           forAI: purityRules\n```\n\nThe function is marked `pure`, which, as *Functions* explained, means each value is set once and\nnot reassigned. The line `running := running + 1` breaks that promise. The message also names the\noperator you *can* use, `:=?`. Here the simplest fix is to compute the value once instead of\nchanging it:\n\n<!-- listing: fragment -->\n```ek9\ntally() as pure\n  -> start as Integer\n  <- result as Integer: start + 1\n```\n\n### Indentation that does not line up\n\n```ek9\nGreeting()\nstdout <- Stdout()\nstdout.println(\"hello\")\n```\n\n```text\nSyntax  : '<-' on line 7 position 11: mismatched input '<-' expecting 'pure', 'as', 'with', 'dispatcher', 'abstract', '(' or newline\nSyntax  : '.' on line 8 position 10: mismatched input '.' expecting 'pure', 'as', 'with', 'dispatcher', 'abstract', '(' or newline\n```\n\n(After those two lines comes `Unable to parse source file`, with the full path of your file.) This\nis a different kind of message: a **syntax** error, raised before the compiler gets as far as\nmeaning. Indentation *is* the structure in EK9. Here the two `stdout` lines are not indented under\n`Greeting()`, so they do not belong to it, and the compiler cannot make sense of them. The fix is to\nindent them so the shape on the page matches the shape you intend:\n\n<!-- listing: fragment -->\n```ek9\nGreeting()\n  stdout <- Stdout()\n  stdout.println(\"hello\")\n```\n\n\"Mismatched input\" is the compiler's way of saying \"this is not where that belongs\". When you see a\nsyntax error, check your indentation first; it is the usual cause.\n\n> **Note.** The formatter (`ek9 -f`, or `ek9 -ff` to force it) tidies *layout*, but it does not\n> *guess structure*. On this program it declines and says why: *\"Force format: the source still\n> does not parse - line 7: mismatched input '<-' ...\"*. It cannot know whether you meant those two\n> lines to sit inside `Greeting()` or somewhere else, so it does not pick one silently. Fix the\n> indentation yourself; the formatter will then keep it tidy.\n\n![A syntax error from mis-aligned indentation. The two un-indented lines are marked in the editor and\nlisted in the *Problems* tab below, each with its file, line and\nreason.](images/ide-error-indent.png){width=100%}\n\n## Asking the compiler for the full explanation\n\nEvery message ends with `See: ek9 -h E<code>`. Run it for the always-true error:\n\n```console\nek9 -h E08086\n```\n\nand the compiler explains the rule in full: what it diagnoses, what to do, the common causes, and\nworked examples. Its `[ACTION]` section reads:\n\n```text\n[ACTION]\n1. Remove the redundant condition and its else/default branch\n2. If the condition is needed on some paths, restructure the logic\n3. Check if a variable was intended to be reassigned before this check\n4. Verify this isn't a copy-paste error from a similar condition\n```\n\nAround it are a `[DIAGNOSIS]` (what is wrong), `[EXAMPLES]` (questions you can open with `ek9 -q`),\n`[COMMON CAUSES]`, `[SEE ALSO]` (related error codes) and a compiled `[EXAMPLE]` of the error and\nits fix.\n\nThe IDE shows the same explanation without leaving the editor: in the screenshots above, it is in\nthe *Hovers* pane when you rest the pointer on the marked code, and the *Answers* tab carries the\nrelated question and answer. (The IDE companion book, `ek9.io/ide/`, covers the IDE in full.)\n\nThree tools are worth knowing by name:\n\n- **`ek9 -h E<code>`** — the full explanation of any error code.\n- **`ek9 -q <words>`** — search EK9's built-in questions and answers, each with a worked example,\n  when you want the idea behind a rule rather than a fix.\n- **Hover** — in the IDE, rest the pointer on the marked code for the same message and help.\n\n## Guide, not gatekeeper\n\nThe compiler is not standing at a gate deciding whether to let your code through. It is standing\nnext to you, pointing: *this line, this reason, here is how to learn more.* Each error points toward\ncode that will still be correct next month. And when the compiler has nothing to say, that silence\nmeans something: each problem it checks for is absent, not merely unnoticed.\n\nSo when something will not build, read the message, find the spot, understand the reason, and ask\nfor more if you need it.\n\n## Try it yourself\n\n1. Open `tautology.ek9` from the `error-examples` folder of the examples download. Read the error.\n   Then fix it by making `temperature` come in as a program argument, and see the error clear.\n2. In `magicLiteral.ek9`, from the same folder, give `50` a name, and see the error go.\n3. Break a program you wrote earlier on purpose: remove an indent, or compare against a bare\n   number. Read the message, then look up its code with `ek9 -h E<code>` and read the full\n   explanation.\n\n## Recap\n\nAn EK9 error message has **five parts**: code, location, snippet, reason, and the pointer to more.\nYou met four errors beginners hit, and saw that each message leads to the fix. For the full\nexplanation, use **`ek9 -h`**, a **hover** in the IDE, or **`ek9 -q`**. Treat each error as an\ninstruction.\n\nYou can now write small programs, hold and test values, make decisions and loops, build functions,\ncheck them with tests, and read the compiler's messages. The next chapters use those foundations to\nwork with real data.\n\n[^magic]: Naming a value is not only tidiness. Research on duplicated code (Juergens, Deissenboeck,\nHummel and Wagner, \"Do Code Clones Matter?\", ICSE 2009) found that changes made to some copies but\nnot to others are frequent, and that many of those unintended differences are bugs. A named value\nhas one home, so it changes in one place. EK9 turns that guideline into a rule the compiler\nenforces.\n","examples":[]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 7","title":"Text, Numbers, Time and Money","url":"https://ek9.io/books/getting-started-with-ek9/data-types.html","markdown":"# Text, Numbers, Time and Money\n\nSo far you have held text in a `String`, whole numbers in an `Integer` and decimals in a `Float`.\nReal programs also deal in *prices*, *dates*, *durations* and *measurements*. In many languages\nthose have no type of their own: a price is \"just a number\", a date \"just a string\", and the awkward\ndetails — pennies, leap years, currencies, units — are left to you or to a library you have to find.\n\nEK9 ships a set of built-in types so that the things programs talk about have a proper, safe home.\nYou do not import anything; they are there, and they know how to behave. This chapter introduces\nthem.\n\n## The ones you already know\n\n**`String`** holds text. You build it with double quotes, and you place values into it with\nbacktick interpolation:\n\n<!-- listing: fragment -->\n```ek9\nname <- \"Ada\"\ngreeting <- `Hello, ${name}`\n```\n\nA `String` can also join, trim, change case and search; later chapters use those as they need them.\n\n**`Integer`** holds whole numbers; **`Float`** holds numbers with a decimal point. They do the\narithmetic you expect with `+`, `-`, `*` and `/`. One warning leads into the next section: **do not\nuse `Float` for money.** A `Float` cannot hold `0.10` exactly, so pennies drift. EK9 gives money its\nown type.\n\n## Money\n\nHere is a small shop receipt. It totals a few items and prints the bill:\n\n```ek9\n#!ek9\ndefines module book.receipt\n\n  defines program\n\n    Receipt()\n      stdout <- Stdout()\n      enGB <- Locale(\"en_GB\")\n\n      applePrice <- 0.35#GBP\n      breadPrice <- 1.10#GBP\n      milkPrice <- 0.85#GBP\n\n      apples <- 6\n      loaves <- 2\n      bottles <- 1\n\n      appleLine <- applePrice * apples\n      breadLine <- breadPrice * loaves\n      milkLine <- milkPrice * bottles\n\n      total <- appleLine + breadLine + milkLine\n\n      stdout.println(`Apples  x${apples}   ${enGB.format(appleLine)}`)\n      stdout.println(`Bread   x${loaves}   ${enGB.format(breadLine)}`)\n      stdout.println(`Milk    x${bottles}   ${enGB.format(milkLine)}`)\n      stdout.println(`Total        ${enGB.format(total)}`)\n```\n\nIt prints:\n\n```text\nApples  x6   £2.10\nBread   x2   £2.20\nMilk    x1   £0.85\nTotal        £5.15\n```\n\nA **money literal** is a number, a `#`, and a three-letter currency code: `0.35#GBP`, `1.10#GBP`.\nThe currency is part of the value, not a note kept on the side. The codes are the international\nstandard ones: `GBP`, `USD`, `EUR`, and so on.\n\nThe **arithmetic is exact**. `applePrice * apples` multiplies a price by a whole number of apples and\ngives money back; `appleLine + breadLine + milkLine` adds money to money. There is no rounding drift,\nbecause `Money` keeps exact decimal values, not the approximations a `Float` would.\n\n**Formatting** is a job for a `Locale`, which represents a place. `Locale(\"en_GB\")` knows that\nBritish money is shown with a `£` and two decimal places, so `enGB.format(total)` gives `£5.15`. A\ndifferent locale presents the same value for its own country. You never assemble a currency string by\nhand.\n\nNow the safety point. What is ten pounds plus five dollars? It is *not a number*: the question has\nno answer without an exchange rate. So EK9 does not invent one:\n\n<!-- listing: fragment -->\n```ek9\npounds <- 10#GBP\ndollars <- 5#USD\nmixed <- pounds + dollars      // different currencies\n```\n\n`mixed` comes back **unset**: not zero, not fifteen of something, but the \"no meaningful value\" state\nfrom *Values and the Three States*. Check it with `?` and you get `false`. Silently adding\nincompatible currencies cannot produce a plausible wrong number. When you do need to combine\ncurrencies, you convert first, with a real rate, and say so.\n\n## Dates, times and durations\n\nTime is the other place where \"just a string\" and \"just a number\" cause trouble: leap years, month\nlengths, time zones. EK9 has proper types for it, with literals you write directly:\n\n- a **`Date`** is a calendar day: `2026-01-15`.\n- a **`Time`** is a time of day: `14:25` or `09:30:00`.\n- a **`DateTime`** is both, with a zone: `2026-01-15T10:30:00Z`.\n- a **`Duration`** is a span of time, written in the international (ISO 8601) style: `P1M15D` is\n  \"one month and fifteen days\", `PT1H30M` is \"one hour and thirty minutes\".\n\nThey work together through operators. Adding a duration to a date gives a date; subtracting one date\nfrom another gives the duration between them:\n\n```ek9\n#!ek9\ndefines module book.dates\n\n  defines program\n\n    Deadline()\n      stdout <- Stdout()\n      enGB <- Locale(\"en_GB\")\n\n      start <- 2026-01-15\n      notice <- P1M15D\n      due <- start + notice\n\n      stdout.println(`Start: ${enGB.mediumFormat(start)}`)\n      stdout.println(`Due:   ${enGB.mediumFormat(due)}`)\n\n      span <- due - start\n      stdout.println(`Notice period is ${span}`)\n      stdout.println(`Due falls on day-of-week ${due.dayOfWeek()}`)\n```\n\nwhich prints:\n\n```text\nStart: 15 Jan 2026\nDue:   2 Mar 2026\nNotice period is P1M15D\nDue falls on day-of-week 1\n```\n\n`start + notice` moved the date on by a month and fifteen days, stepping correctly over the length\nof January without you writing any rule about month lengths. `due - start` gave back the span between\nthe two dates. A `Date` can also describe itself: `due.dayOfWeek()` gives `1` (a Monday), and there\nare matching `.day()`, `.month()` and `.year()` methods. As with money, a `Locale` does the\nformatting: `mediumFormat` gives `15 Jan 2026`, and `shortFormat`, `longFormat` and `fullFormat`\ngive other lengths.\n\n## Measures, colours and more\n\nThe same idea extends to types many languages do not provide at all.\n\nA **`Dimension`** is a measurement with a unit: `20cm`, `10px`, `4.5em`, `8mile`. It does arithmetic,\nwith the same safety as money. Here is what happens when the units do not match:\n\n```ek9\n#!ek9\ndefines module book.measures\n\n  defines program\n\n    Measures()\n      stdout <- Stdout()\n\n      width <- 20cm\n      doubled <- width * 2\n      wider <- width + 5cm\n      mismatch <- width + 3px\n\n      stdout.println(`Width:    ${width}`)\n      stdout.println(`Doubled:  ${doubled}`)\n      stdout.println(`Wider:    ${wider}`)\n      stdout.println(`20cm + 3px is set? ${mismatch?}`)\n```\n\n```text\nWidth:    20.0cm\nDoubled:  40.0cm\nWider:    25.0cm\n20cm + 3px is set? false\n```\n\n`20cm` doubled is `40.0cm`; `20cm + 5cm` is `25.0cm`. But `20cm + 3px` mixes centimetres and pixels,\nwhich has no meaning, so, as with the mixed currencies, the answer is **unset**. The pattern repeats\nacross the language: when an operation does not make sense, EK9 gives you a value you can *check*,\nnot a wrong answer that looks right.\n\nTwo more, so you know they exist. A **`Colour`** is written as a hex value, `#FF5500` (or, with an\nalpha channel *first*, `#80FF5500`, where the leading `80` is the transparency), and can be\nlightened, blended and taken apart. A **`Resolution`** captures pixel density, `96dpi` or `300dpc`,\nfor print and screen work.\n\n## The common thread\n\nThese types share a few habits you can rely on:\n\n- Every value answers **`$`**, \"give me this as text\", so any of them fits into a backtick string.\n- Every value answers **`?`**, \"are you set?\", so you can always ask whether it holds something\n  meaningful.\n- A **`Locale`** turns values into text suited to a place — the right currency symbol, the right\n  date order — without you formatting by hand.\n- When an operation has no meaning — pounds plus dollars, centimetres plus pixels — the result is\n  **unset**: a gap you can test for, not a plausible wrong answer.\n\nA type that knows what it is can refuse to give you a wrong answer. That idea runs through the whole\nbook.\n\n## Naming fixed values\n\nSome values never change: the number of retries you allow, a greeting, the price of a ticket, the\ntime the doors open. Instead of scattering a bare `3` or `\"Hello\"` through your code, you can name a\nfixed value once, with `defines constant`:\n\n```ek9\n#!ek9\ndefines module book.constants\n\n  defines constant\n    maxRetries <- 3\n\n    greeting <- \"Hello\"\n\n    ticketPrice <- 12#GBP\n\n    openingTime <- 09:00\n\n  defines program\n    Show()\n      stdout <- Stdout()\n      stdout.println(`retries allowed: ${maxRetries}`)\n      stdout.println(`${greeting} — doors open at ${openingTime}, entry ${ticketPrice}`)\n```\n\n```text\nretries allowed: 3\nHello — doors open at 09:00:00, entry 12.00#GBP\n```\n\nEach line names a value with `<-` and a **literal**: a number, a string, a `Money` amount, a time.\nThat is the first rule: a constant is always a literal of one of the built-in types in this chapter.\nYou can name a `12#GBP` or a `09:00`, but not a value of a type you define yourself. Constants are\nfor small, fixed facts; EK9 has a different tool for a single shared thing of your own type, which\ncomes later.\n\nThe second rule is the point of the name: a constant is **immutable**, its value can never change.\nThat matters because values get passed around. A function you hand a value to can sometimes change\nit; *Classes* explains when and why. A function can never change a *constant*, and the way EK9\nguarantees it is simple: it hands the function a **copy** of the constant, never the constant\nitself.\n\nYou can see it happen. Here `useOne` subtracts one from whatever it is given (`lives -= 1` is short\nfor \"take one from `lives`, in place\"):\n\n```ek9\n#!ek9\ndefines module book.constantcopy\n\n  defines constant\n    startingLives <- 3\n\n  defines function\n\n    useOne()\n      -> lives as Integer\n      lives -= 1\n\n  defines program\n    Show()\n      stdout <- Stdout()\n\n      myLives <- 3\n      useOne(myLives)\n      stdout.println(`my variable is now:  ${myLives}`)\n\n      useOne(startingLives)\n      stdout.println(`the constant is still: ${startingLives}`)\n```\n\n```text\nmy variable is now:  2\nthe constant is still: 3\n```\n\nBoth started as `3`. The variable `myLives` came back **changed**: `useOne` did subtract one from it.\nThe constant `startingLives` came back **unchanged**, because the function only saw a copy. The\nimmutability does not depend on anyone's care; it is built into how the value is passed. (That the\n*variable* changed at all previews a larger idea: most values in EK9 are shared, not copied, when\npassed around, which is why `useOne` could change `myLives`. Constants are the deliberate exception.\n*Classes* has the full story.)[^goloopvar]\n\n## Try it yourself\n\n1. Change the receipt to use `USD` prices and format it with `Locale(\"en_US\")`. See the symbol and\n   layout change.\n2. In the deadline program, make `notice` a duration of `PT48H` (forty-eight hours) added to a\n   `DateTime` instead of a `Date`. What does the result look like?\n3. Add two `Dimension` values with the *same* unit and print the result. Then add two with different\n   units and print the `?` check, to confirm the mismatch is unset.\n4. Add a `defines constant` block with a `Duration` (say `PT30M`) and a `Colour`, and print them.\n   Then pass one to a function that tries to change it, and confirm the constant is unchanged.\n\n## Recap\n\nEK9 gives real-world values real types: **`Money`** (exact, with the currency in the value, written\n`0.35#GBP`), a family of **date and time** types whose operators read as you would say them\n(`date + duration`, `date - date`), and **`Dimension`**, **`Colour`** and **`Resolution`**. A\n**`Locale`** formats them for a place; every one answers `$` and `?`; and each returns unset rather\nthan a wrong answer when an operation has no meaning. **Constants** (`defines constant`) are named,\nimmutable literals, kept safe by being *copied* whenever they are passed.\n\nThe next chapter, *Speaking Every Language*, uses `Locale` further: it shows how one program can\nspeak to its users in their own language.\n\n[^goloopvar]: \"Is this value shared or copied?\" is subtle enough to catch mainstream languages. For\nmore than a decade, Go's `for`-loop variable was a *single* variable reused across every iteration\nrather than a fresh one each time, so closures and goroutines created inside a loop all captured the\n*same* variable and saw only its final value. Go 1.22 (February 2024) changed the language to give\neach iteration its own copy. The lesson EK9 draws is to make the question explicit: know when you\nhold a shared reference and when you hold a copy.\n","examples":["books/getting-started-with-ek9/ch07-data-types/ConstantCopy.ek9","books/getting-started-with-ek9/ch07-data-types/Constants.ek9","books/getting-started-with-ek9/ch07-data-types/Deadline.ek9","books/getting-started-with-ek9/ch07-data-types/Measures.ek9","books/getting-started-with-ek9/ch07-data-types/Receipt.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 8","title":"Speaking Every Language","url":"https://ek9.io/books/getting-started-with-ek9/localisation.html","markdown":"# Speaking Every Language\n\nIn *Text, Numbers, Time and Money*, a `Locale` presented a value for a place: the right currency\nsymbol, the right date order. A program also says words — \"Welcome\", \"Your basket is empty\", \"Are\nyou sure?\" — and to reach people in another country those words have to change too. This chapter\nshows how EK9 handles that, which is differently from most languages.\n\n## Why translation usually goes wrong\n\nIn most languages, translations live *outside* the program, in separate files, one per language,\nfull of \"key = text\" lines. The code looks up a message by a string key while it runs.\n\nThat arrangement has two failure modes, and both appear in production. Mistype a key, and nothing\ncomplains until the program reaches that line and finds nothing. Add a new message in English but\nforget the French file, and the program runs until a French user reaches the gap and sees a blank, a\nraw key, or a crash. Nothing checked that every language was complete, because nothing *could*: the\ntranslations were text files the compiler never saw.\n\nEK9 brings the words *into* the language, where the compiler can see them.\n\n## Text in the language itself\n\nHere is a greeting in three languages. Look at the shape first; the explanation follows.\n\n```ek9\n#!ek9\ndefines module book.greetings\n\n  defines text for \"en\"\n    Greeting\n      welcome()\n        -> name as String\n        `Hello, ${name}! Welcome to EK9.`\n\n  defines text for \"fr\"\n    Greeting\n      welcome()\n        -> name as String\n        `Bonjour, ${name} ! Bienvenue dans EK9.`\n\n  defines text for \"de\"\n    Greeting\n      welcome()\n        -> name as String\n        `Hallo, ${name}! Willkommen bei EK9.`\n\n  defines program\n    Greet()\n      stdout <- Stdout()\n      me <- \"Ada\"\n\n      english <- Greeting(\"en\")\n      stdout.println(english.welcome(me))\n\n      french <- Greeting(\"fr\")\n      stdout.println(french.welcome(me))\n\n      german <- Greeting(\"de\")\n      stdout.println(german.welcome(me))\n```\n\nRun it and each language speaks for itself:\n\n```text\nHello, Ada! Welcome to EK9.\nBonjour, Ada ! Bienvenue dans EK9.\nHallo, Ada! Willkommen bei EK9.\n```\n\nRead from the top. **`defines text for \"en\"`** opens a block of messages for one language, here\nEnglish. Inside it, **`Greeting`** is a named group of related messages. Inside *that*,\n**`welcome()`** is a single message: it takes a `name`, and its body is a backtick string with\n`${name}` placed in the sentence. The blocks for `\"fr\"` and `\"de\"` repeat the same structure,\ntranslated.\n\nThe language code has a fixed shape: lower-case language, optionally followed by an underscore and\nan upper-case region: `\"en\"`, `\"fr\"`, or `\"en_US\"`. Write `\"en-US\"` (with a hyphen) or `\"EN\"`\n(upper-case) in a `text` block and the compiler rejects it (`E07900`), naming the form it wants. A\n`Locale` is more forgiving: `Locale(\"en_US\")` and `Locale(\"en-US\")` both work. This book uses the\nunderscore form everywhere, so one spelling serves both.\n\n> **Note.** Building your own *types* comes later, with records and classes. A `text` block is a\n> special-purpose relative of that idea: a named set of messages, one version per language. Read\n> `Greeting` as a small group of functions that come in several languages; nothing else is needed to\n> follow this chapter.\n\nAt the bottom, the program *picks* a language and uses it. `Greeting(\"en\")` gives the English\nmessages, `Greeting(\"fr\")` the French. From then on, `welcome(me)` returns the sentence for the\nchosen language. The choice can come from anywhere — a setting, the user's country, a menu — so one\nprogram greets everyone in their own words.\n\nThe translations are part of your program, in plain sight, and the compiler reads them like\neverything else.\n\n## Letting the user choose\n\nThat program *hardwired* each language. A real program lets the *user* decide. The choice usually\narrives as a **command-line argument** given when the program starts, or as an **environment\nvariable** the user has set. Either way it arrives as a `String`, and either way the user might ask\nfor a language you have not translated.\n\nHere is the program taking the language as a command-line argument, as in *Making Decisions and\nRepeating Work*:\n\n```ek9\n#!ek9\ndefines module book.greeting.choice\n\n  defines text for \"en\"\n    Greeting\n      welcome()\n        -> name as String\n        `Hello, ${name}!`\n\n  defines text for \"fr\"\n    Greeting\n      welcome()\n        -> name as String\n        `Bonjour, ${name} !`\n\n  defines text for \"de\"\n    Greeting\n      welcome()\n        -> name as String\n        `Hallo, ${name}!`\n\n  defines program\n    Greet()\n      -> requestedLang as String\n      stdout <- Stdout()\n      me <- \"Ada\"\n\n      chosen <- Greeting(requestedLang)\n      greeter <- chosen? <- chosen : Greeting(\"en\")\n      stdout.println(greeter.welcome(me))\n```\n\nHere are three separate runs — `ek9 Greet.ek9 fr`, then `ek9 Greet.ek9 de`, then\n`ek9 Greet.ek9 xx` — with their output one after another:\n\n```text\nBonjour, Ada !\nHallo, Ada!\nHello, Ada!\n```\n\nTwo lines carry the idea:\n\n```ek9\nchosen <- Greeting(requestedLang)\ngreeter <- chosen? <- chosen : Greeting(\"en\")\n```\n\nThe first *tries* to load the requested language. If it is one you defined,\n`Greeting(requestedLang)` gives back its messages. If it is not, as with `\"xx\"`, it comes back\n**unset**. Nothing crashes; \"no such language\" arrives as a value you can check.\nThat can only happen with a language worked out while the program runs. Write a language you have\nnot translated into the source itself, `Greeting(\"xx\")`, and the program does not compile: the\ncompiler (E07157) names the languages `Greeting` does have.\n\nThe second line is a **ternary**, a one-line either/or. Read it as a question and two answers:\n`chosen?` (is it set?), then after `<-` the value to use if so, `chosen`, and after `:` the value\notherwise, `Greeting(\"en\")`. A supported language is used as it is, and anything else falls back to\nEnglish, so the user always gets a greeting.[^ternary]\n\nThe environment-variable route has the same shape, with the language coming from the user's\nsettings instead:\n\n```ek9\nenv <- EnvVars()\nrequestedLang <- env.get(\"APP_LANG\")\n\nchosen <- Greeting(requestedLang)\ngreeter <- chosen? <- chosen : Greeting(\"en\")\n```\n\n`EnvVars().get(\"APP_LANG\")` reads an environment variable. If the user has not set it, *that* comes\nback unset too, and the same ternary falls back to English. One pattern covers both sources, because\nan unknown language and a missing setting are both \"unset\".\n\n## Formatting values, the local way\n\nA translated message usually carries a value as well: a price, a date, a quantity. Those need\nlocalising too. British English writes a price as \"£1,234.56\" and a date as \"15 Jul 2026\"; French\nwrites \"1 234,56 €\" and \"15 juil. 2026\", with a space between thousands and a comma for the decimal\npoint. A message that says \"Bonjour\" and then prints its numbers in the English style is only\nhalf-translated.\n\nYou can format values *inside* a text message, so the words and the values are localised together.\nA text block already knows its language, so it provides the matching locale under the name\n**`locale`**; you call `locale.format(...)` without constructing one. Here an order confirmation\ncarries a total and a delivery date:\n\n```ek9\n#!ek9\ndefines module book.orders\n\n  defines text for \"en_GB\"\n    OrderText\n      confirmation()\n        ->\n          total as Money\n          arrival as Date\n        `Your order comes to ${locale.format(total)}, arriving ${locale.mediumFormat(arrival)}.`\n\n  defines text for \"fr_FR\"\n    OrderText\n      confirmation()\n        ->\n          total as Money\n          arrival as Date\n        `Votre commande s'élève à ${locale.format(total)}, livrée le ${locale.mediumFormat(arrival)}.`\n\n  defines text for \"de_DE\"\n    OrderText\n      confirmation()\n        ->\n          total as Money\n          arrival as Date\n        `Ihre Bestellung beträgt ${locale.format(total)}, geliefert am ${locale.mediumFormat(arrival)}.`\n\n  defines program\n    Show()\n      stdout <- Stdout()\n      total <- 1234.56#EUR\n      arrival <- 2026-07-15\n      for lang in [\"en_GB\", \"fr_FR\", \"de_DE\"]\n        order <- OrderText(lang)\n        stdout.println(order.confirmation(total, arrival))\n```\n\n```text\nYour order comes to €1,234.56, arriving 15 Jul 2026.\nVotre commande s'élève à 1 234,56 €, livrée le 15 juil. 2026.\nIhre Bestellung beträgt 1.234,56 €, geliefert am 15.07.2026.\n```\n\nEvery language receives the *same* `1234.56#EUR` and the *same* date, and presents them in its own\nstyle. Because `locale` comes from the block's own `for \"...\"` language, the formatting cannot fall\nout of step with the words: you cannot format French numbers with an English locale by mistake, as\nyou could if you named the locale by hand each time.\n\n(The `for lang in [...]` loop goes through a *list* of language codes; lists are introduced properly\nin *Collections*.)\n\n> **Note.** A text message's body is a *single* interpolated string. It may *present and format*,\n> but never *decide*: no `if`, no `else`, no calculation. A message can lay a value out with\n> `${locale.format(...)}`, but it cannot choose what to do. The limit is deliberate. It keeps the\n> program's *logic* in the program and its *wording* in the text, so business rules cannot hide in a\n> translation, and a translator editing the French never has to read, or risk breaking, a line of\n> code.\n\n## Placement, and the trouble with placeholders\n\nThere are two common shortcuts for putting a value into a sentence, and both go wrong. The first is\nto *join strings together*: `\"It's \" + name + \"'s birthday\"`. The second, used by most localisation\nsystems, is a **placeholder**: a template kept in an external file, like `\"It's {0}'s birthday\"` or\n`\"It's %s's birthday\"`, with the value put into the numbered gap at run time. Both fail for the same\nreason: where a value sits in a sentence, and what type it is, belong to the *language*, not the\nprogram.\n\nTake placement first. The position of a name differs between languages:\n\n```ek9\n#!ek9\ndefines module book.birthday\n\n  defines text for \"en\"\n    Party\n      announce()\n        -> name as String\n        `It's ${name}'s birthday today!`\n\n  defines text for \"fr\"\n    Party\n      announce()\n        -> name as String\n        `C'est l'anniversaire de ${name} aujourd'hui !`\n\n  defines text for \"de\"\n    Party\n      announce()\n        -> name as String\n        `Heute hat ${name} Geburtstag!`\n\n  defines program\n    Show()\n      stdout <- Stdout()\n      who <- \"Sam\"\n      for lang in [\"en\", \"fr\", \"de\"]\n        party <- Party(lang)\n        stdout.println(party.announce(who))\n```\n\n```text\nIt's Sam's birthday today!\nC'est l'anniversaire de Sam aujourd'hui !\nHeute hat Sam Geburtstag!\n```\n\nIn English the name comes early, inside \"Sam's\"; in French it comes *after* \"l'anniversaire de\"; in\nGerman it follows \"hat\". Join the pieces in a fixed order and the name is fixed to the place English\nputs it. Because each `text` block writes the *whole* sentence, `${name}` goes wherever that language\nneeds it, and, as the previous section showed, the *format* moves too.\n\nA placeholder has a second failing: it is **not type-safe**. A template like `\"You owe {0} on {1}\"` is\nonly text. Nothing checks that exactly two values are passed, that the first is a `Money` and the second\na `Date`, or that a translator did not swap `{0}` and `{1}`. Those mistakes appear only when the program\nruns, as a crash or, worse, a plausible but wrong line.[^formatstrings]\n\nA text message has no anonymous gaps. Its parameters are **named and typed** — `total as Money`,\n`arrival as Date` — and `${total}` refers to one of them by name. Pass the wrong type, too few\nvalues, or a misspelled name, and it is a *compile* error. A check that elsewhere needs an extra tool\nis here part of the language.\n\n> **Note.** Use a message in *two* steps: name the text object first, then call it —\n> `party <- Party(lang)`, then `party.announce(who)`, as above. It reads more clearly than doing both\n> on one line, and it is the form used throughout this chapter.\n\n## The compiler keeps every language complete\n\nBecause the messages are in the language, the compiler can enforce a rule: **every language must\ndefine exactly the same messages.** Suppose English gains a `farewell()` but German does not:\n\n```ek9\n  defines text for \"en\"\n    Greeting\n      welcome()\n        -> name as String\n        `Hello, ${name}!`\n      farewell()\n        -> name as String\n        `Goodbye, ${name}!`\n\n  defines text for \"de\"\n    Greeting\n      welcome()\n        -> name as String\n        `Hallo, ${name}!`\n```\n\nThis does not compile (the whole file is `missingTranslation.ek9`, in the `error-examples` folder of\nthe download):\n\n```text\nEK9     : Error   : E07150: 'Greeting' on line 14 position 4: 'public String <- farewell(name as String) as abstract': text method missing for language variant\n             See: ek9 -h E07150\n```\n\nThe compiler compared the messages in each language, found German missing one, and stopped. A\nprogram with a missing translation cannot be built, so the failure from the start of this chapter —\na missing message nobody noticed until a user in another country reached it — cannot reach users.\nThe check moved to compile time, and that kind of bug cannot get through.\n\n## Adding a language with the IDE and an AI\n\nIf every language must be complete, then adding one message means writing it in *all* your\nlanguages, which you may not speak. Tools help here, and EK9's design helps them.\n\nThe EK9 IDE can add a new language for you (the IDE companion book, `ek9.io/ide/`, covers these\ntools in full). To add Portuguese, choose **Add Locale**, name it `pt`, and pick an existing\nlanguage to *clone from*, such as English.\n\n![The IDE's *Add Locale* dialog: name the new locale and choose a language to clone from. Preview shows\nthe exact insertions before anything is changed.](images/add-locale-dialog.png){width=95%}\n\nThe tool copies every message into a new `defines text for \"pt\"` block, with each body replaced by an\nempty message and a `//AI: translate the message` comment. This still *compiles*, because an empty\nmessage is a valid message. The tool also records a **translation debt**: a list of every message\nstill waiting to be translated.\n\n![After cloning: the new `pt` block mirrors the English one, with the message stubbed as `\"\"` and a\n`//AI: translate the message` comment. It compiles, but says nothing\nyet.](images/locale-added.png){width=95%}\n\nAn AI assistant can work through that list, reading each hint and the original wording, and fill in\nthe translations — `Hello, ${name}! Welcome to EK9.` becomes `Olá, ${name}! Bem-vindo ao EK9.` — and\nyou review the results.\n\n![After translation: the `pt` message now holds the Portuguese text, and the build is still\nclean.](images/locale-translated.png){width=95%}\n\nBe clear about what each part guarantees. The compiler guarantees that every language defines every\nmessage (`E07150` otherwise) and that each `${...}` matches its typed parameter. It does not, and\ncannot, check that a stub was ever translated: an empty message compiles. The IDE's translation debt\nrecords which stubs are still waiting. You decide *what* to say; the IDE keeps the languages in step\nand records what is owed; the AI drafts the translations; and the compiler guarantees the set is\ncomplete and consistent.\n\n## Unicode throughout\n\nThe German `ä` and the French spacing above needed no special handling. EK9 text is Unicode\nthroughout, so accents, other alphabets and non-Latin scripts — Greek, Cyrillic, Arabic, Japanese —\nare ordinary text.\n\n## Try it yourself\n\n1. Add a `farewell()` message to each of the three languages and print it after the welcome.\n2. Add a fourth language of your choice, with the `welcome()` message, so the program still\n   compiles.\n3. Delete one translation and read the compiler's error: EK9 refusing to build a program with a\n   missing translation.\n\n## Recap\n\nEK9 treats translation as part of the language, not a set of external files. The **`text`\nconstruct** — `defines text for \"en\"`, a named group of messages, each a small method with an\ninterpolated body — keeps your wording in plain sight and lets a program pick a language at run time.\nA text block provides a matching **`locale`**, so values inside a message are formatted for its\nlanguage. The compiler enforces that **every language defines every message** (`E07150`) and that\nthe interpolated values match their types, so a language that is *missing* a message cannot be\nbuilt. Whether each message has actually been translated is tracked by the IDE, not the compiler: an\nempty stub compiles.\n\nNext come EK9's **collections**: the tools for holding many values at once.\n\n[^ternary]: *Guards and Safe Code* returns to the ternary and adds its relatives that check for set\nvalues. The form is always `condition <- valueIfTrue : valueIfFalse`.\n\n[^formatstrings]: Format-string mistakes are a well-studied source of bugs; see Konstantin Weitz, Gene\nKim, Siwakorn Srisakaokul and Michael D. Ernst, \"A Type System for Format Strings\" (*ISSTA 2014*). The\ncommon localisation tools all use positional, untyped placeholders in template strings — Java's\n`MessageFormat` (from JDK 1.1, 1997) with `{0}`, the `gettext` library and C printf-style\nAPIs with `%s`, C#'s `string.Format` and `.resx` resources with `{0}`. Compile-time\nchecking is available, but as an add-on — for example the Checker Framework's format-string checker for\n`javac` — rather than as part of the language itself.\n","examples":["books/getting-started-with-ek9/ch08-localisation/Birthday.ek9","books/getting-started-with-ek9/ch08-localisation/EnvGreet.ek9","books/getting-started-with-ek9/ch08-localisation/Greet.ek9","books/getting-started-with-ek9/ch08-localisation/Greetings.ek9","books/getting-started-with-ek9/ch08-localisation/Order.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 9","title":"Collections","url":"https://ek9.io/books/getting-started-with-ek9/collections.html","markdown":"# Collections\n\nSo far each name has held a single value: one number, one price, one date. Real programs deal in\n*many* values at once: a shopping basket, a price list, the scores in a game, the words in a\nsentence. For that you need a **collection**, a value that holds other values. EK9 starts you with\ntwo that cover most needs: the **`List`** and the **`Dict`**.\n\n## A list of things\n\nA `List` is an ordered sequence of values. You write one with square brackets:\n\n<!-- listing: fragment -->\n```ek9\nbasket <- [\"Apples\", \"Bread\", \"Milk\"]\n```\n\nThat is a list of three `String`s, in that order. You did not have to say \"list of String\": EK9\nworked it out from the values, by type inference.\n\nA list knows how many things it holds, whether it contains a particular value, and how to give you\nits items one at a time. You add to it with `+=`:\n\n<!-- listing: fragment -->\n```ek9\nbasket += \"Cheese\"\n```\n\nAnd you can go through it with a `for` loop:\n\n<!-- listing: fragment -->\n```ek9\nfor item in basket\n  stdout.println(item)\n```\n\n## A dictionary of pairs\n\nOften you want to look something *up*: the price of an item, the phone number for a name. For that,\nEK9 has the **`Dict`** (short for *dictionary*): a set of **key → value** pairs. You write one with\ncurly braces and colons:\n\n```ek9\nprices <- {\"Apples\": 0.35#GBP, \"Bread\": 1.10#GBP, \"Milk\": 0.85#GBP}\n```\n\nHere each *key* is an item name (a `String`) and each *value* is its price (a `Money`). Given a key,\nthe `Dict` gives back its value. The safe way to ask is `getOrDefault`, which takes the key *and* a\nfallback to use if the key is not there:\n\n<!-- listing: fragment -->\n```ek9\napplePrice <- prices.getOrDefault(\"Apples\", Money())\n```\n\nIf `\"Apples\"` is in the dictionary you get its price; if not, you get the fallback. The fallback you\nchoose matters. It is tempting to write `0#GBP`, but that *means* \"if we have no price for this, it\ncosts nothing\": a made-up answer. A missing price is not a *free* item, it is an *unknown* one. The\ntruthful fallback is an **unset** `Money()`: \"we do not have a price for that\". `getOrDefault` is\nonly as safe as the default you give it; a careless `0` turns a gap in your data into a wrong number.\n\n## Putting them together\n\nHere is a shopping basket that uses both, and behaves like a real shop, where some things are not in\nstock. A `List` holds what you are trying to buy; a `Dict` holds the prices of what the shop\n*sells*. The program totals what is available and collects what is not:\n\n```ek9\n#!ek9\ndefines module book.basket\n\n  defines program\n    Basket()\n      stdout <- Stdout()\n      enGB <- Locale(\"en_GB\")\n\n      prices <- {\"Apples\": 0.35#GBP, \"Bread\": 1.10#GBP, \"Milk\": 0.85#GBP}\n      basket <- [\"Apples\", \"Bread\", \"Kiwi\", \"Milk\", \"Mango\"]\n\n      labelWidth <- 8\n      total <- 0#GBP\n      unavailable <- List() of String\n      for item in basket\n        price <- prices.getOrDefault(item, Money())\n        if price?\n          total += price\n          label <- item + \":\"\n          stdout.println(`${label.rightPadded(labelWidth)}${enGB.format(price)}`)\n        else\n          unavailable += item\n\n      totalLabel <- \"Total:\"\n      stdout.println(`${totalLabel.rightPadded(labelWidth)}${enGB.format(total)}`)\n      stdout.println(`Not available: ${unavailable}`)\n```\n\nIt prints:\n\n```text\nApples: £0.35\nBread:  £1.10\nMilk:   £0.85\nTotal:  £2.30\nNot available: [\"Kiwi\", \"Mango\"]\n```\n\nFor each item the program looks up a price with the unset `Money()` default. If the price *is set*\n(the shop sells it), it is added to the total and printed. If it is *not* (Kiwi and Mango are not\nstocked), the item goes into an `unavailable` list, reported at the end. The total is the true total\nof what the customer can buy, and nothing is silently lost.\n\n(`label.rightPadded(labelWidth)` pads a label with spaces to a set width, so every amount starts in\nthe same column. There is a `leftPadded` too, for lining things up on the right.)\n\nBecause a missing price came back *unset* rather than `0#GBP`, the program could tell it apart from\na real price. A `0` default would have added nothing to the total for Kiwi and Mango, and hidden\nthat they were missing.\n\n## An empty collection is *set*, not missing\n\nA new, empty collection is **set**. It is a real, usable container that holds nothing, not\n\"nothing\". (There is a genuine \"nothing here\" case — asking a collection for an item it does not\nhave — but that is a property of the *lookup*, not of the collection; *Optional and Result* returns\nto it.)\n\n<!-- listing: fragment -->\n```ek9\nshopping <- List() of String     // a brand-new, empty list\nstdout.println(`New list set? ${shopping?}  items: ${length shopping}`)\n```\n\nprints:\n\n```text\nNew list set? true  items: 0\n```\n\nAn empty list is set, and `length shopping` — the `length` operator, written in front of the value,\ncounts the items — gives `0`. \"An empty basket\" and \"no basket at all\" are different\nsituations, and EK9 keeps them different. You can pass an empty list around, add to it, and loop over\nit (zero times). If you have a `List`, you have a real list, even when it holds nothing yet.\n\n## How EK9 works out a collection's type\n\nWhen you write a list or dictionary with values in it, EK9 has to decide what *type* it is.\n\nThe compiler looks at the values and tries to find **one type that every element fits**: a common\ntype. When the elements agree, that is the answer:\n\n```ek9\nwords <- [\"a\", \"b\", \"c\"]        // List of String\ncounts <- [1, 2, 3]             // List of Integer\namounts <- [1.0, 2.0, 3.0]      // List of Float\n```\n\nThe compiler is *conservative*. If the values do not share a clear common type, it does not guess;\nit stops with an error (E50030) that names the types it found:\n\n<!-- listing: fragment -->\n```ek9\nmixed <- [1, \"two\", 3.0]     // no common type -> error E50030\n```\n\nThe only type those three share is `Any`, which is so general that you can do almost nothing with\nthe items. If a list of anything really is what you want, you must *say so*:\n`mixed as List of Any: [1, \"two\", 3.0]`. That is almost always a sign of a mistake: you meant the\nvalues to be one kind and they were not. So **let a collection hold one kind of thing.** If you want\ndecimals, write decimals (`[1.0, 2.0, 3.0]`); if you want whole numbers, write whole numbers. A\nlist's type is fixed once it is made — a `List of Integer` is *not* a `List of Float` — so when you\nneed an empty list of a particular type, say so:\n\n<!-- listing: fragment -->\n```ek9\nscores <- List() of Float      // an empty List of Float, ready to fill\n```\n\nA `Dict` works the same way, deciding a type for its keys and a type for its values separately, so\n`{1: \"quick\", 2: \"brown\"}` is a `Dict of (Integer, String)`. The same advice — keep them consistent,\nor state the type — applies to each side.\n\n> **Note.** An *empty* literal cannot be inferred, because there are no values to look at, so\n> `x <- []` and `x <- {}` are syntax errors. Say what you want instead: `List() of String`, or\n> `Dict() of (String, Integer)`. This is the one time you *must* name the type.\n\nThe common type need not be a built-in like `String` or `Integer`. It can be a *shared parent* of\nyour own making. If a `Circle` and a `Rectangle` are both kinds of `Shape`, then a list holding one\nof each is a `List of Shape`: one list, several kinds, all handled through the type they have in\ncommon. Working with many different types through one shared type is called\n**polymorphism**, and the chapter *Abstract Types, Subtypes and Polymorphism* covers it.\n\n## Where the promotion comes from\n\nA whole number can sometimes stand in for a decimal. The reason is not a special rule buried in the\ncompiler.\n\nA whole number can become a decimal because the `Integer` type *says so*. It has a **promotion\noperator**, written `#^`, whose job is to answer \"what wider type can I become?\" For `Integer`, the\nanswer is `Float`:\n\n<!-- listing: fragment -->\n```ek9\nwhole <- 5\nasFloat <- #^ whole          // 5.0, an Integer promoted to a Float\n```\n\nBecause that operator exists, EK9 promotes a whole number wherever a `Float` is wanted: in a\ncalculation, or as an argument to something expecting a `Float`:\n\n<!-- listing: fragment -->\n```ek9\naddHalf() as pure\n  -> x as Float\n  <- rtn as Float: x + 0.5\n\nhalf <- addHalf(5)           // 5.5 - the 5 promotes to 5.0, then the work happens\n```\n\n`Float` has *no* `#^` operator — there is no wider number for it to become — so promotion runs only\none way: a whole number can rise to a decimal, but a decimal never silently drops to a whole number.\nPromotion is an operator a type either has or has not, and the compiler follows it, including when it\nworks out the common type for a collection.\n\nWhen you build your own types, you can give one its own `#^` — \"a `Pennies` can promote to `Pounds`\",\nsay — and it joins the same mechanism: promoted in calculations, accepted as arguments, consulted for a\ncommon type. EK9's conversions are operators you can read and, later, write yourself; *Using Operators*\ncovers them.\n\nPromotion is one of two ways a value can fit a wider type. Promotion **converts**: the `5` becomes a\nnew `5.0` to fit where a `Float` is wanted, a different value of a different type. The other way\nneeds no conversion. A `Circle` fits where a `Shape` is wanted because it already *is* one: the same\nobject, unchanged. That is polymorphism. From the outside the two can look alike — a `List of Float`\naccepting a whole number, a `List of Shape` holding a `Circle` — but one makes a new value and the\nother uses the value it already has.\n\n## Straight to JSON\n\nJSON is a common text format for exchanging data between programs. EK9 has a built-in **`JSON`**\ntype, and any collection can turn itself into JSON with the `$$` operator:\n\n<!-- listing: fragment -->\n```ek9\nbasket <- [\"Apples\", \"Bread\"]\nstdout.println(`${$$ basket}`)\n```\n\nprints:\n\n```text\n[\"Apples\",\"Bread\"]\n```\n\nRead `$$` as \"give me this as JSON\", as `$` means \"give me this as text\". A `Dict` becomes a JSON\nobject, a `List` a JSON array, and the values inside come along:\n\n<!-- listing: fragment -->\n```ek9\nprices <- {\"apple\": 35, \"bread\": 80}\nasJson <- $$ prices              // {\"apple\":35,\"bread\":80}\n```\n\nYou can read a field back out of a `JSON` value by name, with `get`:\n\n```ek9\napple <- asJson.get(\"apple\")\nstdout.println(`apple field: ${apple}`)\n```\n\n```text\napple field: 35\n```\n\nSo `JSON` is a type like any other: build it from a collection, read fields from it, pass it around.\nText arriving from *outside* is parsed into a `Result` (introduced in *Optional and Result*), so a\nmalformed document cannot slip past unnoticed; the second volume covers JSON in full.\n\n## Two very small collections\n\nTwo more container types belong to the same family; they are very small collections.\n\nAn **`Optional`** holds *zero or one* value: the smallest collection there is. It says \"there might\nbe a value here, and there might not\", and it will not let you reach the value without first checking\nthat it is there. A **`Result`** holds one of *two* things: the value if some work succeeded, or an\nerror if it did not. It is how a function hands back \"here is your answer\" or \"here is what went\nwrong\" without a crash.\n\nBoth are about *handling missing values and failures safely*, so they have a chapter of their own,\n*Optional and Result*, after *Guards and Safe Code*. They share the family likeness of `List` and\n`Dict`: containers where \"how many values are in here?\" is a question the compiler helps you answer.\n(There is also a **`PriorityQueue`**, a collection that keeps its items in order of importance,\nuseful in places such as scheduling.)\n\n## Try it yourself\n\n1. Build a `Dict` of three friends' names to their ages. Print each with a `for` loop. (Going\n   through a `Dict` gives you each pair; read them with `entry.key()` and `entry.value()`.)\n2. Look up a name that is *not* in your dictionary with `getOrDefault`. What default did you choose,\n   and why?\n3. Make a new empty `List of Integer`, print its `?` and `length`, then add three numbers and print\n   them again.\n4. Write a mixed list like `[1, \"two\"]`. Read the error, then fix it by keeping the list to one type.\n\n## Recap\n\nEK9's two core **collections** are the **`List`**, an ordered sequence of values (`[...]`, `+=`,\n`for item in list`), and the **`Dict`**, a set of key → value pairs (`{k: v}`, `getOrDefault`). An\n**empty collection is set, not missing**, which keeps \"empty\" and \"absent\" apart, and a truthful\ndefault (an unset `Money()`, not a made-up `0`) lets you see a gap instead of hiding it. EK9\n**infers a collection's type** by finding one common type for the values, and refuses a mix that\nshares none unless you declare a `List of Any`. Number promotion comes from the `#^` **promotion\noperator**, which your own types can define too. The **`JSON`** type comes from any collection with\n`$$`, and `get` reads a field back. `Optional` and `Result` are the smallest containers of all.\n\nNext comes *handling missing values safely*: guards, and then the `Optional` and `Result` types.\n","examples":["books/getting-started-with-ek9/ch09-collections/Basket.ek9","books/getting-started-with-ek9/ch09-collections/Collections.ek9","books/getting-started-with-ek9/ch09-collections/Inference.ek9","books/getting-started-with-ek9/ch09-collections/JsonTaste.ek9","books/getting-started-with-ek9/ch09-collections/Promotion.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 10","title":"Guards and Safe Code","url":"https://ek9.io/books/getting-started-with-ek9/guards-and-safe-code.html","markdown":"# Guards and Safe Code\n\nYou already know the central idea of this chapter: a value can be set, unset or absent, and the `?`\noperator asks \"is this set?\". This chapter builds sharper tools on that one idea. By the end you will\nwrite code that checks for a missing value at every step, with the compiler checking that you did,\nand you will have seen the one pattern EK9 uses for it everywhere.\n\nEach tool is a small step up from the one before.\n\n## The pattern that keeps repeating\n\nHere is a small problem. We ask for a name from somewhere that might not have one. If we do not get\na usable name, we fall back to a default.\n\nWith the tools so far, it looks like this:\n\n<!-- listing: fragment -->\n```ek9\nname <- lookupName()\nif not name?\n  name := \"Friend\"\nstdout.println(`Hello, ${name}`)\n```\n\nDeclare `name` from `lookupName()`. If it is *not* set, replace it with `\"Friend\"`. Then greet. This\nis correct and clear. But you will write this shape — *get a value, check whether it is set, act on\nthe answer* — many times a day, and EK9 has tighter ways to say it.\n\n> **Note.** `lookupName()` here is a function that returns a `String` which may be set or unset. How\n> it decides does not matter; what matters is that the result might not be there.\n\nThe one that fits *this* shape — \"use the value, or a fallback if it is missing\" — is the\n**ternary**, the one-line either/or you met in *Speaking Every Language*:\n\n<!-- listing: fragment -->\n```ek9\nname <- lookupName()\ndisplayName <- name? <- name : \"Friend\"\nstdout.println(`Hello, ${displayName}`)\n```\n\nAs before, the part before the `<-` is the question: `name?`, *is `name` set?* After it come the two\nanswers, separated by a colon: if yes, the part before the colon (`name`); if no, the part after\n(`\"Friend\"`). Either way `displayName` holds a set value, and the\ngreeting works as before, with the fallback in one line instead of three.\n\nThe next tool, the **guard**, is related but does a different job, and you will use it constantly.\nAfter it come more of these set-aware shortcuts.\n\n## The guard: check and use in one step\n\nOften you want to do two things together: take a value, *and* carry on only if it is set. EK9 has a\nsingle tool for that, called a **guard**:\n\n```ek9\nif name <- lookupName()\n  stdout.println(`Hello, ${name}`)\n```\n\nThe `if` line joins a `<-` declaration and a `?` set check. In plain words: \"declare `name` from\n`lookupName()`, and run this block only if `name` is set.\" Inside the block, `name` is certain to\nhold a usable value, and you never need to check it again.\n\nThe example file `Guards.ek9` shows both outcomes. Its program `Greet` has two guards: the first\ntakes its value from `lookupName()`, which returns an unset `String`; the second from `storedName()`,\nwhich returns `\"Ada\"`. Only the second block runs:\n\n```text\nHello, Ada\n```\n\nThis is the heart of the chapter. The guard does not test whether `name` is *true*, or empty in some\nloose sense. It tests one thing: **is the value set?** That is the question `?` has always asked.\n\n> **Common confusion.** `if name <- ...` does not mean \"if the assignment worked\" or \"if the value\n> is not zero\". It is the set check, nothing more. If `name` is set, the block runs; if not, it is\n> skipped.\n\n> **One exception: a `Boolean`.** If the guarded value is a `Boolean`, an `if` (or `else if`) guard\n> runs its block only when the value is set *and* `true`: `if allowed <- permitted()` skips a `false`\n> as it skips an unset value, because that is what anyone reading the line expects. A `switch` still\n> asks only \"is it set?\", so its `case false` can be reached.\n\nIf you need an *extra* condition beyond \"is it set?\", add it after `then`:\n\n```ek9\nminLen <- 2\nif name <- storedName() then length name > minLen\n  stdout.println(`Hello, ${name}`)\n```\n\n`length name` gives the length of the text. (The number `2` gets a name, `minLen`, as any number\ncompared against must.) Now the block runs only when `name` is both set *and* longer than `minLen`\ncharacters; with `\"Ada\"` it prints `Hello, Ada`. The guard always comes first, and the `then`\ncondition is checked only once the value is known to be safe to look at, so you can never ask the\nlength of a value that is not there.\n\n## The same pattern, everywhere\n\nThe *same* declaration guard can start every choice and loop EK9 has. It always means the same thing\n— *declare a value, and carry on only if it is set* — though what follows it differs a little from\none construct to the next.\n\nIn a `while` loop, the guard runs *once*, as the loop's setup, and a `then` clause gives the\ncondition that keeps the loop going:\n\n```ek9\nwhile iter <- lines.iterator() then iter.hasNext()\n  line <- iter.next()\n  stdout.println(line)\n```\n\nThe guard `iter <- lines.iterator()` runs a single time: it declares `iter` (an *iterator*, which\nhands out a collection's items one at a time) and would skip the whole loop if that value came back\nunset. `then iter.hasNext()` is the question the loop asks each time round: is there another item?\n\nA `for` loop uses the guard the same way, as a one-off setup step before the loop runs:\n\n```ek9\nfor prefix <- messagePrefix() then i in 1 ... 3\n  stdout.println(`${prefix} ${i}`)\n```\n\nThe same shape appears in `switch` and in `try`. There is really only *one* idea here — a\nset-checked declaration — shared by `if`, `while`, `for`, `switch` and `try`. In an `if` it *is* the\ntest; in the loops it is a guarded setup, with the ongoing condition after `then`. You learn one\nsafety pattern, not a different one for each construct.\n\n> **Note.** The variable a guard creates — `name`, `iter`, `prefix` — belongs only to its block; it\n> cannot be used outside. So you can never reach for a guarded value whose set state has not been\n> checked.\n\n## Setting a value only if it is missing\n\nSometimes you only want to supply a default *when* something is unset. That is the\n**assign-if-unset** operator, `:=?`:\n\n<!-- listing: fragment -->\n```ek9\nname <- lookupName()\nname :=? \"Friend\"\nstdout.println(`Hello, ${name}`)\n```\n\n`:=?` reads as \"set this *only if* it is currently unset\". If `lookupName()` gave a real name, `:=?`\nleaves it alone; if it gave an unset value, `:=?` fills in `\"Friend\"`. It behaves the same as the\nfirst version in this chapter, with one line in place of three.\n\n## Coalescing: choosing the set one\n\nThe tightest form is the **coalescing operator**, `?:` (often called *Elvis*). Use it when you want\n\"this value, or that one if the first is not set\":\n\n<!-- listing: fragment -->\n```ek9\nname <- lookupName() ?: \"Friend\"\nstdout.println(`Hello, ${name}`)\n```\n\n`lookupName() ?: \"Friend\"` means \"the result of `lookupName()` if it is set, otherwise `\"Friend\"`\".\nThe whole thing is an *expression* — it produces a value — so `name` can be declared from it\ndirectly.\n\nThe language choice in *Speaking Every Language* has the same shape. `Greeting(requestedLang)` is\nunset for a language you have not translated, so one line says what that chapter's ternary said:\n\n<!-- listing: fragment -->\n```ek9\ngreeter <- Greeting(requestedLang) ?: Greeting(\"en\")\n```\n\nThe coalescing operator is *set-aware*: it chooses a side by asking the set/unset question. EK9 has\na small family of these set-aware choosers: `?:`, and the **comparison coalescing** operators `<?`\nand `>?`, which pick the smaller or larger of two values safely (see below).\n*The Operator Reference* lists the whole family.\n\nSo the problem now has three answers.[^oneconstant] The example file `Defaulting.ek9` holds each as\nits own program, and all three print `Hello, Friend`:\n\n<!-- listing: fragment -->\n```ek9\n// Step 1 — plain\nname <- lookupName()\nif not name?\n  name := \"Friend\"\n\n// Step 2 — assign-if-unset\nname <- lookupName()\nname :=? \"Friend\"\n\n// Step 3 — coalescing expression\nname <- lookupName() ?: \"Friend\"\n```\n\nRead from top to bottom, they move from *explicit* to *terse*. Step 1 spells out every move, which\nmakes it the clearest while the ideas are new. Step 3 says the same thing in one line, the form an\nexperienced EK9 programmer writes for \"cope with a value that might be missing\". Step 2 sits between.\nUse whichever reads most clearly to you; as the set-aware forms become familiar, you will tend\ntowards the terse end.\n\nNow look at the three for *reassignment*. Step 1 declares `name` and then **changes** it:\n`name := \"Friend\"` is a second assignment. Step 3 works out the final value first and assigns it\n**once**. (Step 2's `:=?` sits between: it may *fill* an unset value, but never overwrite a set one.)\n\nThat difference matters. In *Reading the Compiler's Guidance* the compiler rejected a `:=` inside a\n`pure` function, because a pure function may not reassign. So in pure code the Step 1 shape is not\nallowed, while the coalescing expression is: it changes nothing, it only works out a value. This is a\nfirst sight of a broader rule: EK9's **expression forms** (like `?:`) are the preferred way to\n*produce* a value, because one expression replaces a declare-then-reassign sequence, and single\nassignment is what pure code needs.\n\n## The safe smallest and largest\n\nTwo more members of the family are used constantly: `<?` and `>?`, the **safe smallest** and **safe\nlargest**. `a <? b` gives the *lesser* of the two, but if one side is unset it gives back the other;\nonly if *both* are unset is the result unset. `>?` does the same for the *greater* value. If the two\nvalues are equal, both operators give back the *left* one.\n\nReal data has gaps. Imagine asking three shops for a price, where one never replied:\n\n```ek9\n#!ek9\ndefines module book.safeminmax\n\n  defines program\n    Show()\n      stdout <- Stdout()\n\n      // Three shops were asked for a price; one never replied (unset).\n      shopA <- 12\n      shopB <- Integer()\n      shopC <- 9\n\n      cheapest <- shopA <? shopB <? shopC\n      dearest <- shopA >? shopB >? shopC\n\n      stdout.println(`cheapest quote: ${cheapest}`)\n      stdout.println(`dearest quote:  ${dearest}`)\n\n      // Only when EVERY value is unset is the answer unset.\n      noQuotes <- Integer() <? Integer()\n      stdout.println(`no quotes at all -> set? ${noQuotes?}`)\n```\n\n```text\ncheapest quote: 9\ndearest quote:  12\nno quotes at all -> set? false\n```\n\n`shopA <? shopB <? shopC` works left to right, taking the smaller each time and passing over the shop\nthat gave no quote, and arrives at the cheapest *real* price, `9`. `>?` finds the dearest, `12`.\nHere is the safe smallest of only **two** possibly-missing values, written by hand:\n\n<!-- listing: fragment -->\n```ek9\n// The safe smallest of just two values, written by hand:\ncheapest as Integer?\nif shopA? and shopB?          // both shops replied — compare them\n  if shopA <= shopB\n    cheapest := shopA\n  else\n    cheapest := shopB\nelse if shopA?                // only A replied\n  cheapest := shopA\nelse if shopB?                // only B replied\n  cheapest := shopB\n// neither shop replied — nothing to choose from\n```\n\nThat is about ten lines to choose the smaller of *two* values, each branch a chance to slip. Each\nvalue you add doubles the set-and-unset combinations: two values give four cases, three give eight,\nfour give sixteen. `shopA <? shopB <? shopC` stays one expression however many shops you add, and has\nno branches to get wrong. As long as one value is set, the answer is set; only when *every* value is\nunset is the result unset, which is the true answer: there was nothing to choose from.\n\n## Control flow that gives back a value\n\nThe coalescing operator is an expression: it produces a value. EK9's larger choices and loops can do\nthe same. A `for` loop can hand back a result:\n\n```ek9\ntotal <- for i in 1 ... 5\n  <- rtn <- 0\n  rtn += i\nstdout.println(`Total is ${total}`)\n```\n\n```text\nTotal is 15\n```\n\nThe `<- rtn <- 0` line declares the loop's result, starting at `0`. Each pass adds `i` to it (`+=`\nadds to a value in place). When the loop finishes, `total` receives the final `rtn`. The loop has\nbeen used as an *expression*.\n\nThis fits code that *works out* a value without changing things elsewhere: `pure` code. A `pure`\nfunction may not reassign, so \"declare a variable, then keep changing it\" is not available to it. The\nexpression forms — a coalescing `?:`, a ternary, an expression `switch` or `for` — each let a choice\nhand back a value in one go, so you assign once.\n\nEK9 offers *expression* versions of much of its control flow: `switch`, `for`, `while` and even `try`\ncan each produce a value. One shape is deliberately missing: there is **no `if`-expression**. When you\nneed one value or the other, the **ternary** (`name? <- name : \"Friend\"`) says it more directly; when\nthe choice is bigger, an expression `switch` does the job. These forms exist because a value produced\nby an expression can be assigned *once*, which pure code needs and which makes all code easier to\nread. Wherever you might declare a variable and reassign it inside branches, EK9 tends to give you a\nconstruct that hands the answer back:\n\n<!-- listing: fragment -->\n```ek9\ngreetingFor() as pure\n  -> maybeName as String\n  <- rtn as String: `Hello, ${maybeName ?: \"Friend\"}`\n```\n\n`greetingFor` is `pure`, takes a name that might be unset, and returns a greeting, computing the\nresult in one expression and changing nothing. Called with `\"Ada\"` it gives `Hello, Ada`; called with\nan unset name, `Hello, Friend`. When code needs to change things outside itself, a plain statement\nis usually clearer. The second volume treats purity in full; for now, *expressions and purity go\ntogether*.\n\n## Why EK9 does this\n\nThe reason is evidence. A well-known and costly kind of bug is the one where a program assumes a\nvalue is there, and it is not. Most widely used languages have a *null reference*, a variable that\nrefers to nothing at all, and reading one crashes the program. The person who introduced it later\ncalled it his \"billion-dollar mistake\".[^null]\n\nEK9 has no `null` keyword. It is designed to eliminate that bug, and the compiler checks every read.\nThe tools in this chapter make checking a value's state so ordinary that it stops feeling like extra\nwork: the block after a guard runs only when the value is set, `:=?` cannot overwrite a value you\nwanted to keep, and `?:` with a set fallback always gives a set value.\n\n## Try it yourself\n\n1. Write a function `pickColour()` that returns a `String` which is sometimes set and sometimes\n   unset. Use a guard (`if colour <- pickColour()`) to print the colour only when one was chosen.\n2. Rewrite the same logic with `:=?`, so an unset result falls back to `\"grey\"`.\n3. Now do it in one line with `?:`. Which of the three reads most clearly to you? That judgement is\n   what this chapter is about.\n4. Take the plain `if not x?` example from the start of the chapter. Reduce it as far as you can\n   while keeping it easy to read.\n\n## Recap\n\nEvery tool in this chapter is the `?` set check in a new shape. The **guard** (`if name <- ...`)\nchecks that a value is set and uses it in one step, and the *same* guard works across `if`, `while`,\n`for`, `switch` and `try`. **Assign-if-unset** (`:=?`) supplies a default only when a value is\nunset. **Coalescing** (`?:`) and the safe smallest and largest (`<?`, `>?`) choose a set value in a\nshort expression. And control flow can be an *expression*, which suits pure code. Under all of it is\none aim: no crash on a missing value. Next, *Optional and Result*: two containers that put \"maybe a\nvalue\" and \"a value or an error\" into the type itself.\n\n[^null]: Tony Hoare, who introduced the null reference in 1965, called it his \"billion-dollar\nmistake\" in a 2009 talk (QCon London), estimating the cost of the resulting errors over the\nfollowing decades. *The Evidence: the research behind the rules* has the background.\n\n[^oneconstant]: These are three *alternatives*; a real program uses one, not all three. Each also\nspells out the same fallback, `\"Friend\"`. Write that literal three times in one real file and EK9\nstops you: its repeated-literal rule (`E11065`) asks you to name it once as a constant. The example\nfile does that — `DefaultName <- \"Friend\"`, declared once and used in every version — so the value\nhas a single home.\n","examples":["books/getting-started-with-ek9/ch10-guards/Defaulting.ek9","books/getting-started-with-ek9/ch10-guards/ForExpression.ek9","books/getting-started-with-ek9/ch10-guards/Guards.ek9","books/getting-started-with-ek9/ch10-guards/SafeMinMax.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 11","title":"Optional and Result","url":"https://ek9.io/books/getting-started-with-ek9/optional-result.html","markdown":"# Optional and Result\n\n*Collections* named two small containers and promised to return to them. `Optional` and `Result` are\nhow an EK9 program says two things it needs to say all the time: \"there might be a value here, or\nthere might not\", and \"this either worked, or it went wrong\". Many languages have versions of these.\nWhat EK9 adds is that the compiler *will not let you reach a value you have not checked*, and will not\nlet you quietly throw the answer away.\n\n## Optional: zero or one\n\nAn `Optional` holds either one value or none: the smallest collection, a box that holds at most one\nthing and says when it is empty.\n\nUse it when a function might not have an answer. Here is a phone book that looks up a number by name,\nwhere sometimes the name is not in it:\n\n```ek9\n#!ek9\ndefines module book.phonebook\n\n  defines function\n    lookupNumber() as pure\n      -> name as String\n      <- rtn <- Optional() of String\n      book <- {\"Ada\": \"0100 111\", \"Grace\": \"0100 222\"}\n      if book contains name\n        rtn: Optional(book.getOrDefault(name, String()))\n\n  defines program\n    Phone()\n      stdout <- Stdout()\n\n      ada <- lookupNumber(\"Ada\")\n      if ada?\n        stdout.println(`Ada: ${ada.get()}`)\n\n      zara <- lookupNumber(\"Zara\")\n      if zara?\n        stdout.println(`Zara: ${zara.get()}`)\n      else\n        stdout.println(\"No number for Zara\")\n```\n\nIt prints:\n\n```text\nAda: 0100 111\nNo number for Zara\n```\n\n`lookupNumber` returns an `Optional of String`. If the name is in the book, it returns\n`Optional(theNumber)`, a box *with* a value. If not, it returns the empty `Optional() of String` it\nstarted with. Either way the caller gets a real answer.\n\nNow look at how the caller *reads* it. To take the value out you call `.get()`, but only **after**\nchecking that the box is not empty, with `if ada?`. Inside that block, and only there, `ada.get()` is\nallowed. Leave out the check and the program does not compile.\n\n## Result: this worked, or it did not\n\nAn `Optional` says \"a value, or nothing\". Often you need to say *why* there is no value. That is a\n`Result`: it carries either a success value or an error. Here is a division that refuses to divide by\nzero:\n\n```ek9\n#!ek9\ndefines module book.divide\n\n  defines function\n    safeDivide() as pure\n      ->\n        a as Integer\n        b as Integer\n      <- rtn <- Result() of (Integer, String)\n\n      if b == 0\n        rtn: rtn.asError(\"cannot divide by zero\")\n      else\n        rtn: rtn.asOk(a / b)\n\n  defines program\n    Div()\n      stdout <- Stdout()\n\n      good <- safeDivide(10, 2)\n      if good.isOk()\n        stdout.println(`Answer: ${good.ok()}`)\n\n      bad <- safeDivide(10, 0)\n      if bad.isError()\n        stdout.println(`Cannot: ${bad.error()}`)\n```\n\nwhich prints:\n\n```text\nAnswer: 5\nCannot: cannot divide by zero\n```\n\nA `Result of (Integer, String)` holds an `Integer` on success or a `String` on failure. The return\nline, `<- rtn <- Result() of (Integer, String)`, declares the return value with an *empty* `Result`,\nwhich the body then fills in; this is the short, inferred form from *Functions*, allowed because a new\n`Result() of (...)` is a simple starting value. `safeDivide` fills it with `asOk(...)` or\n`asError(...)`. The caller asks which it got — `isOk()` or `isError()` — and only inside the matching\nblock may it read the matching value: `ok()` after `isOk()`, `error()` after `isError()`.\n\nThe two outcomes are in the type. There is no error code in a separate variable for a caller to\nforget, and you cannot reach either outcome without checking first.\n\n> **Note.** The check must *match* the accessor. Checking `isError()` and then reading `ok()` is a\n> compile error. You can read the success value only on the success path, and the error value only on\n> the error path.\n\n## The compiler is watching\n\nAll of this rests on one rule: you cannot read a value you have not checked. The compiler keeps it.\nTry a shortcut:\n\n```ek9\nmaybe <- Optional(\"hi\")\nstdout.println(maybe.get())\n```\n\nThis does not compile (the whole program is `uncheckedGet.ek9`, in the `error-examples` folder):\n\n```text\nEK9     : Error   : E08030: 'get' on line 9 position 27: 'maybe as Optional of String': has not been checked before access\n             See: ek9 -h E08030\n```\n\nThe compiler followed the code, found no `if maybe?` protecting the `get()`, and stopped. There is no\nway to force the value out unchecked; the safe path is the only path.\n\nTwo more rules come from the same thinking. You cannot *throw away* a `Result` or `Optional`: if a\nfunction hands one back, you must look at it (`discardedResult.ek9`):\n\n```text\nEK9     : Error   : E11052: 'work' on line 13 position 6: method returns Result or Optional but result is discarded - must always be checked\n             See: ek9 -h E11052\n```\n\nAnd inside a block that has checked a value, you cannot replace that value, because the check would\nthen no longer be true (`staleCheck.ek9`):\n\n```ek9\nmaybe <- Optional(\"hi\")\nif maybe?\n  maybe := Optional(\"bye\")\n  stdout.println(maybe.get())\n```\n\n```text\nEK9     : Error   : E08040: ':=' on line 10 position 14: 'maybe as Optional of String': Reassignment/mutation within possible 'safe method access' scope is not allowed\n             See: ek9 -h E08040\n```\n\nEach is a small rule; together they close off a whole category of mistake.\n\n## Why it matters when the check happens\n\nOptional and result types are common in modern languages.[^elsewhere] The difference is *when* a\nmistake is caught. In EK9, a value read without a check and an error left unexamined each become a\nprogram that does not build, with a message pointing at the exact spot. Catching it while you write\nthe code costs a moment; catching it in a running program costs far more. And there is no `null` to\nfall back on (*Guards and Safe Code* told that story): `Optional` and `Result` are two of the tools EK9\noffers in its place.\n\n## Try it yourself\n\n1. Add `\"Steve\"` to the phone book, look him up, and print his number inside an `if ... ?` check.\n2. Look up a name that is not there and handle the empty case with an `else`.\n3. In the division program, call `safeDivide(7, 0)` and print the error. Then try to read `good.ok()`\n   *without* the `if good.isOk()` check, and read the compiler's error.\n4. Change the last exercise to check `isError()` but read `ok()`, and see the compiler catch the\n   mismatch.\n\n## Recap\n\nEK9 has two containers for uncertainty. An **`Optional`** holds a value or nothing; you read it with\n`.get()` only inside an `if value?` check. A **`Result`** holds a success *or* an error; you read\n`ok()` only after `isOk()`, and `error()` only after `isError()`, with the check matching the\naccessor. The compiler enforces all of it: unchecked access (`E08030`), a discarded result\n(`E11052`), and a check made stale by reassignment (`E08040`) are compile errors.\n\nNext come **streams**: a way to run a whole collection of values through a pipeline of small steps.\n\n[^elsewhere]: In Rust, an `Option` or `Result` also provides `.unwrap()`, which crashes at run time\nif the value is missing. In Go, a function returns a value and an error side by side, but nothing\nforces the caller to look at the error. EK9 turns both of those mistakes into compile errors.\n","examples":["books/getting-started-with-ek9/ch11-optional-result/Divide.ek9","books/getting-started-with-ek9/ch11-optional-result/Phone.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 12","title":"Streams and Pipelines","url":"https://ek9.io/books/getting-started-with-ek9/streams.html","markdown":"# Streams and Pipelines\n\n*Making Decisions and Repeating Work* explained that EK9 has no `break` and no `continue`, the kind of\njump Dijkstra argued against in 1968, and promised a better tool for the jobs they usually do: running\na collection of values through a series of small steps, keeping some, changing others, and gathering a\nresult. That tool is the **stream**.\n\nA stream takes a collection, sends its values one at a time through a **pipeline** of stages joined by\n`|`, and ends by printing them or collecting them into a result. It reads left to right, like a\nsentence.\n\n## A first pipeline\n\nThis one takes the numbers one to six, keeps the even ones, doubles them, and prints the result:\n\n```ek9\n#!ek9\ndefines module book.nums\n\n  defines function\n    isEven() as pure\n      -> n as Integer\n      <- rtn as Boolean: n rem 2 == 0\n\n    doubleIt() as pure\n      -> n as Integer\n      <- rtn as Integer: n * 2\n\n  defines program\n    Numbers()\n      stdout <- Stdout()\n      for i in 1 ... 6 | filter by isEven | map with doubleIt > stdout\n```\n\nRun it and you get:\n\n```text\n4\n8\n12\n```\n\nRead the last line as a pipeline of four stages:\n\n- **`for i in 1 ... 6`** starts the stream. `1 ... 6` is a *range*, and the `for` feeds its numbers\n  into the pipeline one at a time. (A `for` followed by `|` is a stream *source*, not the counting\n  loop you met earlier.)\n- **`| filter by isEven`** lets a value through only if `isEven` says yes. `2`, `4` and `6` pass;\n  `1`, `3` and `5` are dropped. (`n rem 2` is the remainder after dividing `n` by 2.)\n- **`| map with doubleIt`** replaces each value with a new one, here its double.\n- **`> stdout`** ends the pipeline by writing what is left to the screen.\n\n`isEven` and `doubleIt` are ordinary named functions, like those in *Functions*. `filter` and `map`\nuse them.\n\nA stream can also start with the word **`cat`**, which sends out the items of an existing collection\none by one. Both `cat` and the `|` come from the Unix command line, where small tools are joined into\na pipeline, as in `cat file | grep error | sort`. EK9's streams bring that idea — small pieces that\neach do one thing, joined end to end — inside the language. Douglas McIlroy devised it for Unix over\nfifty years ago.[^pipes]\n\n## The functions a pipeline expects\n\n`filter by` needs a function that takes a value and answers *yes or no*: a test. `map with` needs a\nfunction that takes a value and returns a *new* value: a transformation. Your functions have exactly\nthose shapes: `isEven` takes an `Integer` and returns a `Boolean`; `doubleIt` takes an `Integer` and\nreturns an `Integer`.\n\nEK9 has names for these shapes. A pure test — one value in, a `Boolean` out — is a **`Predicate`**. A\npure transformation — one value in, one value out — is a **`Function`**. A **`Consumer`** takes one\nvalue and returns nothing, for a step that *does* something with each value. You do not write these\nnames: the compiler works out from their shapes that `isEven` *is a* `Predicate` and `doubleIt` *is a*\n`Function`. Give `filter` a function of the wrong shape and it will not compile.[^dynamic]\n\nThe rule of thumb: `filter` wants a test, `map` wants a transformation, and any named function of the\nright shape will do.\n\n## The shopping basket again\n\nThe basket from *Collections* had a list of items, a price list, and some things the shop does not\nstock. There it was totalled with a `for` loop and an `if`. A pipeline says the same thing more\ndirectly. The work gets a name, `basketTotal`, so that it can be tested:\n\n```ek9\n    priceOf() as pure\n      -> item as String\n      <- rtn <- Money()\n      prices <- {\"Apples\": 0.35#GBP, \"Bread\": 1.10#GBP, \"Milk\": 0.85#GBP}\n      rtn: prices.getOrDefault(item, Money())\n\n    isAvailable() as pure\n      -> price as Money\n      <- rtn as Boolean: price?\n\n    basketTotal() as pure\n      -> items as List of String\n      <- rtn <- Money()\n      rtn: cat items | map with priceOf | filter by isAvailable | collect as Money\n```\n\nThe pipeline in `basketTotal` reads like the numbers one:\n\n- **`cat items`** streams the shopping list, name by name.\n- **`| map with priceOf`** turns each name into its price, an unset `Money` if the shop does not stock\n  it (`priceOf` uses the unset `Money()` default from *Collections*).\n- **`| filter by isAvailable`** keeps only the prices that are set, dropping the items with no price.\n- **`| collect as Money`** ends the pipeline by *adding up* what is left into a single `Money` total.\n\n`collect as Money` turns a stream back into one value, as `> stdout` sent a stream to the screen. Give\n`basketTotal` a basket with two unstocked items and it still returns the right total for what the\nshop *can* sell.\n\n## Small pieces you can trust\n\nA pipeline is built from small, separate functions, and small, separate functions are *easy to test*.\nProve each piece on its own, and you can trust the whole.\n\nSo the pieces are tested as in *Testing as You Go*, with `@Test` programs in a `dev/` directory. One\nuseful pattern is a **table of cases** — inputs paired with the answers you expect — which lets one\ntest check many examples:\n\n```ek9\n    @Test\n    PriceOfTest()\n      known <- {\"Apples\": 0.35#GBP, \"Bread\": 1.10#GBP, \"Milk\": 0.85#GBP}\n      for entry in known\n        assert priceOf(entry.key()) == entry.value()\n\n    @Test\n    MissingPriceTest()\n      assert not priceOf(\"Kiwi\")?\n\n    @Test\n    IsAvailableTest()\n      assert isAvailable(priceOf(\"Bread\"))\n      assert not isAvailable(priceOf(\"Mango\"))\n\n    @Test\n    BasketTotalTest()\n      expected <- 2.30#GBP\n      assert basketTotal([\"Apples\", \"Bread\", \"Kiwi\", \"Milk\"]) == expected\n```\n\nRun them with `ek9 -t`:\n\n```text\nℹ️ Found 4 tests:\n  4 assert (unit tests with assertions)\n\nExecuting 4 tests...\n\n✅ PASS book.shop.tests::BasketTotalTest [Assert] (6ms)\n✅ PASS book.shop.tests::IsAvailableTest [Assert] (5ms)\n✅ PASS book.shop.tests::MissingPriceTest [Assert] (5ms)\n✅ PASS book.shop.tests::PriceOfTest [Assert] (5ms)\n\nSummary: 4 passed, 0 failed (4 total)\nTypes: 4 assert\nDuration: 23ms\n```\n\n`PriceOfTest` checks a table of names against their prices in one go. `MissingPriceTest` shows that an\nunstocked item comes back unset, not free. `IsAvailableTest` shows that the filter's test behaves. And\n`BasketTotalTest` checks the *whole pipeline*: `Kiwi` is not stocked, so a basket of four items totals\nonly what the shop sells. Each stage is checked, and then the way they combine is checked, so the\npipeline is something you have *shown* to work.\n\n## Why this replaces `break` and `continue`\n\nThink about the number example as a loop written with jumps: a counter, a loop, an `if` that skips the\nodd numbers with a `continue`, perhaps a `break` to stop early, and somewhere to gather the results.\nEach of those parts is a known source of bugs: the off-by-one count, the `continue` that skips one line\ntoo many, the `break` in the wrong loop.\n\nThe pipeline has none of them. There is no counter to miscount and no early exit to misplace. \"Skip\nthe ones I do not want\" is a `filter`. \"Stop after the first few\" is a `head` stage. \"Do this to each\"\nis a `map`. Each is a named stage with one job, and the whole reads in the order it runs. EK9 removed\n`break` and `continue` and put in their place something that does the same work with fewer ways to go\nwrong, and that you can test piece by piece.\n\n## There is more than this chapter shows\n\nThis chapter covers the everyday pipeline: start with `cat` or a `for`, then `filter` and `map`, and\nfinish with `collect` or `>`. EK9's streams go further. There are stages to `sort` values, drop\nduplicates with `uniq`, take or skip a few (`head`, `tail`, `skip`), `flatten` a stream of lists into a\nplain stream of values, and `group`, `join` or `split` items. A pipeline can be *teed*, in the Unix\nsense: a copy of the flow branches off to be logged or counted while the main stream carries on. And\n`collect` is the simplest ending; there are richer ways to *accumulate* a result as the values go by.\n`sort` returns in *Using Operators*; the rest are for the second volume. The stages in this chapter\nalready handle a great deal of real work.\n\n## Try it yourself\n\n1. Change the numbers pipeline to keep the *odd* numbers instead. Write an `isOdd`, or think about how\n   else you could do it, and which reads more clearly.\n2. Add a `| head 2` stage after the `map` in the numbers pipeline, and see how the output changes.\n3. Add `\"Cheese\"` to a basket you pass to `basketTotal`, with no price for it, and add a test showing\n   the total is unchanged. That test stays green as long as the pipeline keeps ignoring what the shop\n   does not sell.\n\n## Recap\n\nA **stream** sends a collection through a **pipeline** of stages joined by `|`. You start it with a\n`for` over a range or with `cat`, then `filter by` a test and `map with` a transformation, and finish\nby writing to output with `>` or gathering a result with `collect as`. The stages run ordinary\n**named functions**, which fit by shape — a **`Predicate`** for `filter`, a **`Function`** for `map` —\nand EK9 works out the fit. A pipeline of small functions is one you can *test*: check each piece, check\nhow they combine, and trust the whole. Streams are what replace `break`, `continue` and the loop with a\ncounter.\n\nThe next chapter, *Two Ways to Build: Data, Functions and Objects*, starts designing with types of\nyour own.\n\n[^pipes]: Douglas McIlroy conceived the Unix *pipe*, added to the system in 1973. He also summed up\nthe philosophy behind it: \"Write programs that do one thing and do it well. Write programs to work\ntogether.\" EK9's streams, and the small, testable functions this chapter builds them from, express\nthat idea in a type-safe language.\n\n[^dynamic]: There is also a shorter way to write a one-off pipeline function where you use it, without\ngiving it a name: a *dynamic function*. And the family of function types (`Predicate`, `Function`,\n`Consumer` and others) has more to it than shown here: a one-in, one-out function that is not `pure`,\nfor example, is a `Routine`. Both are covered in the second volume; named functions carry every idea\nneeded here.\n","examples":["books/getting-started-with-ek9/ch12-streams/Numbers.ek9","books/getting-started-with-ek9/ch12-streams/shop/dev/tests.ek9","books/getting-started-with-ek9/ch12-streams/shop/shop.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 13","title":"Two Ways to Build: Data, Functions and Objects","url":"https://ek9.io/books/getting-started-with-ek9/two-ways.html","markdown":"# Two Ways to Build: Data, Functions and Objects\n\nSo far you have built programs from the types EK9 provides — `String`, `Money`, `List` and the rest —\njoined together with functions. From here on you make your *own* types, named in the words of the\nproblem you are solving: a `Point`, a `Score`, a `Player`. Before the details, this chapter sets out\nthe choice you face when you do, because there is more than one good way to build, and EK9 lets you\nuse them together.\n\n## Two traditions\n\nProgramming has two long-standing ways of organising a program.\n\nThe first keeps *data* and *behaviour* apart. You describe your data as a plain bundle of named\nfields — a point is an `x` and a `y` — and write separate functions that take that data and do\nthings with it. The data is passive; the functions do the work. This is the tradition of the C\nlanguage and its `struct`, and it is simple and direct.\n\nThe second *bundles* data and behaviour together. A `Counter` is not just a number; it is a number\n*and* the operations that belong to it — `increment`, `current` — packaged as one thing, an\n**object**, that looks after itself. This is the tradition of Smalltalk, and later C++, Java and many\nothers.\n\nBoth have built large, successful systems. Neither is \"right\". They suit different problems, and\noften different *parts* of the same problem.\n\n## EK9 does not make you choose\n\nMany languages pick a side. C has structs and functions but no objects. Java made almost everything\nan object and, for a long time, had no free-standing functions at all. In either, you shape your\nproblem to fit the language.\n\nIn EK9, **data, behaviour and objects are equal partners**, and you pick whichever fits. There are\nthree building blocks, and you have already glimpsed each of them.\n\nA **`record`** is data — a bundle of named fields:\n\n```ek9\n    Point\n      x as Float: 0.0\n      y as Float: 0.0\n```\n\nA **`function`** is behaviour on its own. It takes something in, hands something back, and holds no\nstate, as in the *Functions* chapter:\n\n```ek9\n    add() as pure\n      ->\n        a as Integer\n        b as Integer\n      <- rtn as Integer: a + b\n```\n\nA **`class`** is an object: data *and* the behaviour that belongs with it:\n\n```ek9\n    Counter\n      count as Integer: 0\n\n      increment()\n        count += 1\n\n      current() as pure\n        <- rtn <- Integer(count)\n\n      default operator ?\n```\n\n`current` hands back `Integer(count)` — a copy of the count, not the field itself.[^copyout]\n\nNone of the three is second-class. A `record` is not a lesser class, and a `function` does not have to\nlive inside an object. Each is a complete way to build, and one program can use all three.\n\n## Which should you reach for?\n\nA rough guide, which the next chapters make precise:\n\n- When you mostly have **data to carry around** — a point, a row from a file, a message — use a\n  **`record`**, and write **`function`s** that work on it. This is often the right choice.\n- When a thing has **data that must be looked after** — kept valid, changed only in controlled ways —\n  use a **`class`**, so the data and the rules that protect it live together.\n- When you have **behaviour with no state** — a calculation, a step in a stream pipeline — a\n  **`function`** is all you need.\n\nYou do not have to decide perfectly. A program can mix all three, and you can change your mind later.\n\n## Protecting data without freezing it\n\nIf a record's fields can be read *and* written by any code, what stops a distant piece of code from\nchanging one when it should not?\n\nMany languages answer by freezing the data: an \"immutable\" record that can never be changed. EK9 does\nnot. It controls the *code* instead. A function or method marked **`pure`** — the word from the\n*Functions* chapter — may not change anything it is handed. Pass a record through pure code and it\ncomes back exactly as it went in.\n\nSo the record stays plain and open, and the protection sits on the *behaviour*, not on the *data*. A\nvalue that is frozen in one part of a program and changeable in another brings complications of its\nown; putting the rule on the code avoids them. `pure` gets its full treatment in the second volume.\n\n> **Note.** `record` and `class` are both kinds of **aggregate** — a construct that defines a type with\n> members of its own: fields, methods, operators. (A function is not an aggregate; of the three building\n> blocks, only `record` and `class` are.) Aggregates share a few rules (every aggregate that holds\n> fields defines a `?`, so it can answer \"am I set?\"), which the next chapter introduces. Later you will\n> meet three more aggregates: the **`trait`**, for behaviour shared across types (*Traits and\n> Composition*), the **`component`**, for putting a whole subsystem behind a simple interface\n> (*Components*), and, in the second volume, the **`service`**, for web services. The *Constructs at a\n> Glance* appendix summarises them all on one page.\n\n## Try it yourself\n\n1. Write a `pure` function `distanceFromOrigin` that takes a `Point` and returns how far it is from\n   `(0, 0)`. (`sqrt` written in front of a number gives its square root.) For the point `(3.0, 4.0)` it\n   should give `5.0`.\n2. Give `Counter` a `reset()` method that puts the count back to `0`, and print the count before and\n   after.\n3. For each of these, decide whether a record, a function or a class fits best, and say why in one\n   line: a name and an email address; a count of page visits; turning Celsius into Fahrenheit.\n\n## Recap\n\nThere are three ways to build: **data**, **behaviour** and **objects**. Two traditions lie behind\nthem — keeping data and functions apart, and bundling them into objects — and EK9 treats\n**`record`**, **`function`** and **`class`** as equal partners you can mix freely. A record's data\nstays open; `pure` is how EK9 protects it. Next: records and enumerations — how to declare your own\ntypes, give them fields, and give them a little behaviour.\n\n[^copyout]: Handing the field back directly would give the caller a reference to the counter's own\nstate, which they could then use to change it. Returning a copy, `Integer(count)`, keeps the counter in\ncharge of its value. The *Classes* chapter explains this in full; the examples adopt the habit from\nthe start.\n","examples":["books/getting-started-with-ek9/ch13-two-ways/ThreeWays.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 14","title":"Records and Enumerations","url":"https://ek9.io/books/getting-started-with-ek9/records-enums.html","markdown":"# Records and Enumerations\n\nOf the three ways to build, plain **data** needs the fewest new ideas, and the others build on it. This\nchapter makes your own **records** (bundles of data) and your own **enumerations** (a fixed set of\nnamed values).\n\n## A record is a bundle of data\n\nA **record** groups a few named values into one thing. Here is a point on a grid — an `x` and a `y`,\nkept together:\n\n```ek9\n#!ek9\ndefines module book.coord\n\n  defines record\n    Coord\n      x as Integer: Integer()\n      y as Integer: Integer()\n\n      default Coord() as pure\n\n      Coord() as pure\n        ->\n          initialX as Integer\n          initialY as Integer\n\n        x :=? Integer(initialX)\n        y :=? Integer(initialY)\n\n      operator $ as pure\n        <- rtn as String: `(${x}, ${y})`\n\n      default operator <=>\n      default operator ?\n\n  defines function\n    moveTo()\n      ->\n        point as Coord\n        toX as Integer\n        toY as Integer\n\n      point.x := toX\n      point.y := toY\n\n  defines program\n    Show()\n      stdout <- Stdout()\n\n      origin <- Coord(2, 3)\n      twin <- Coord(2, 3)\n      faraway <- Coord(9, 9)\n      stdout.println(`origin = ${origin}, its x is ${origin.x}`)\n      stdout.println(`origin == twin?    ${origin == twin}`)\n      stdout.println(`origin == faraway? ${origin == faraway}`)\n\n      blank <- Coord()\n      stdout.println(`a blank Coord is made   (set? ${blank?})`)\n      moveTo(blank, 5, 6)\n      stdout.println(`after moveTo: ${blank}     (set? ${blank?})`)\n```\n\nIt prints:\n\n```text\norigin = (2, 3), its x is 2\norigin == twin?    true\norigin == faraway? false\na blank Coord is made   (set? false)\nafter moveTo: (5, 6)     (set? true)\n```\n\n`defines record` opens the definition; `Coord` names it. Inside are its **fields**, `x` and `y`. Each\nis declared `as Integer` with a starting value of `Integer()`, an *unset* Integer: the field exists\nbut holds no number yet — the middle of the three states.[^fielddecl] A record's fields are **open**:\nany code holding a `Coord` can read them with a dot, so `origin.x` gives `2`. That openness is what a\nrecord is for: plain, visible data.\n\n## Building one in a single step\n\nThe program makes its points with `Coord(2, 3)`, not by creating an empty record and filling in its\nfields one at a time. That is a **constructor**: setup code that takes the values a `Coord` needs and\nreturns a finished one.\n\n```ek9\n      Coord() as pure\n        ->\n          initialX as Integer\n          initialY as Integer\n\n        x :=? Integer(initialX)\n        y :=? Integer(initialY)\n```\n\nIt reads like a function: two `Integer`s come in, and each is copied into a field. It stores\n`Integer(initialX)`, a fresh copy, rather than `initialX` itself.[^copyin] The `:=?` is the\nassign-if-unset operator — \"set this *only if it is not already set*\". Each field starts unset, so `:=?`\ngives it its first value.\n\nThe constructor is marked **`as pure`**. Pure code may not reassign a value, so inside pure code you\n*cannot* make an empty `Coord` and then set `.x` and `.y`: the second step is a reassignment, and the\ncompiler rejects it. A constructor avoids that by building the value complete, in one step. Use one\nwhenever a value should arrive fully formed; in `pure` code it is the only way to build one.\n\n## Or build it blank, and fill it in later\n\nAbove that constructor is a one-line second one:\n\n```ek9\n      default Coord() as pure\n```\n\nThis is the **default constructor**: it takes no values. `default` asks for the standard version,\nwhich leaves every field as it starts — *unset*. So `blank <- Coord()` is a real `Coord`, with an `x`\nand a `y`, but neither holds a number. Ask whether it is set, and it answers `false`:\n\n```text\na blank Coord is made   (set? false)\n```\n\nThat is the three-state model applied to your own type: a `Coord` can be *set* (built with values) or\n*present but unset* (built blank), and `?` tells them apart.\n\nThe `moveTo` function fills in a blank one:\n\n```ek9\n    moveTo()\n      ->\n        point as Coord\n        toX as Integer\n        toY as Integer\n\n      point.x := toX\n      point.y := toY\n```\n\nIt writes the two numbers into the fields with `:=`. It does not build a new `Coord`;\nit changes the one it was given. That works because a `Coord` is passed **by reference**: `moveTo` and\nthe caller hold the *same* record, so once `moveTo` sets the fields, the caller's `Coord` is set too:\n\n```text\nafter moveTo: (5, 6)     (set? true)\n```\n\nSo there are two ways to build: a constructor that delivers a complete value, or a blank one you fill\nin afterwards. `moveTo` is not marked `pure`: it changes the record it is given, and only non-pure\ncode may do that. Use build-complete in `pure` code; use build-blank-then-fill when a value really\ndoes arrive in pieces.\n\n## Giving data a little behaviour\n\nThe three declarations after the constructors are **operators**, the one kind of *behaviour* a record may\nhave. A record cannot hold general methods (that is what classes are for), but it can define\noperators from a small, fixed set that almost every value needs. Here they do three jobs:\n**printing**, **comparing** and **checking**.\n\n`operator $` handles **printing**: how a `Coord` becomes text, `(2, 3)`. It is the same `$` that gives\nevery built-in type its printed form; writing one for `Coord` is what lets `${origin}` inside a string\nshow the point.\n\n`default operator <=>` handles **comparing**. `default` asks the compiler to generate the obvious\nversion: compare the fields in order, which is what lets `Coord`s be sorted. From that one comparison\nthe compiler also *generates* `==`, `<>`, `<`, `<=`, `>` and `>=`, so two `Coord`s are equal exactly\nwhen `<=>` says they are the same. That is why `origin == twin` is `true` (both are `(2, 3)`) and\n`origin == faraway` is `false`. You did not write `==` or ask for it: a type says *once* what \"the\nsame\" means, and every other comparison follows, so they cannot disagree. (Asking for\n`default operator ==` beside `<=>` is an error, `E07181`.)\n\n`default operator ?` handles **checking**: whether the record is set.\n\nThe *Using Operators* chapter covers the full set. The idea to keep: a record is data first, with just\nenough operators to print, compare and check itself like any other value.\n\n### One line for all the obvious ones\n\nNaming every operator you want becomes tedious. Write `default operator` with **no symbol after it**,\nand the compiler generates *every* operator it can work out for itself, leaving alone any you wrote.\n`Coord` could end like this, with the same result:\n\n<!-- listing: fragment -->\n```ek9\n      operator $ as pure\n        <- rtn as String: `(${x}, ${y})`\n\n      default operator\n```\n\nRead it as a statement of intent: *how a `Coord` prints is my decision, so I write `$`; the rest is\nmechanical, so the compiler can have it.* Write the one or two operators that carry your own judgement,\nand default the rest. This chapter's example spells each operator out so you can see them by name;\nlater examples use the one-line form.\n\n> **Note.** Every aggregate that holds fields must define `?`, so it can answer \"am I set?\" like every\n> other value. `default operator ?` gives the standard one; leave it out and the compiler reports\n> `E07235`. A definition also has a fixed order: fields first, then constructors and methods, then\n> operators last.\n\n## Plain data is a virtue\n\nEven with its operators, a `Coord` is a small, open bundle of values with no agenda of its own.\nProgrammers call this a **DTO**, a *data transfer object*, and use it to carry related values from one\nplace to another.\n\nIt is tempting to think that locking data inside an object is always the better design. Often it is\nnot. A great deal of good software keeps its data plain and open, in records like this, and puts the\nwork in the **functions** that use it — the style of the stream pipelines in *Streams and Pipelines*.\nAlan Perlis put it this way: it is better to have a hundred functions operate on one data structure\nthan ten functions on ten of them.[^perlis] EK9 supports that style fully. A record and a set of\nfunctions is not a beginner's stage you grow out of; it is often the clearest design.\n\nThe *Classes* chapter shows the other path: a **class**, for data that must be protected rather than\npassed around freely. Neither is the \"right\" one, and you can combine them: a class can hold a record\nfor its plain data and add behaviour around it.\n\n## Enumerations: a fixed set of names\n\nIn *Making Decisions and Repeating Work* we wrote a `switch` on a day of the week using the numbers\n`1` to `7`. An **enumeration** does this properly: it is a type whose values are a small, fixed set of\n*names* — the days of the week, the suits in a pack of cards, the states of a traffic light:\n\n```ek9\n#!ek9\ndefines module book.days\n\n  defines type\n    Day\n      Monday\n      Tuesday\n      Wednesday\n      Thursday\n      Friday\n      Saturday\n      Sunday\n\n  defines function\n    kindOf() as pure\n      -> day as Day\n      <- rtn as String: \"weekday\"\n      switch day\n        case Day.Monday, Day.Tuesday, Day.Wednesday, Day.Thursday, Day.Friday\n          rtn: \"weekday\"\n        case Day.Saturday, Day.Sunday\n          rtn: \"weekend\"\n        default\n          rtn: \"no such day\"\n\n  defines program\n    Week()\n      stdout <- Stdout()\n      for day in Day\n        stdout.println(`${day} is a ${kindOf(day)}`)\n```\n\nwhich prints:\n\n```text\nMonday is a weekday\nTuesday is a weekday\nWednesday is a weekday\nThursday is a weekday\nFriday is a weekday\nSaturday is a weekend\nSunday is a weekend\n```\n\n`defines type` with a name and an indented list of values declares the enumeration. You refer to its\nvalues by name — `Day.Monday`, `Day.Saturday` — never by number, so a `Day` can only ever be a real\nday. `for day in Day` loops over the whole set, and `${day}` prints the name.\n\n`Day.Saturday` says what it means; `6` did not. And a `Day` cannot hold `9`, or a value from some other\nlist.\n\n## An enumeration comes with operators\n\nA record's operators had to be asked for. An enumeration gets a set of them the moment you declare it.\nYou wrote only a list of names, yet all of this works:\n\n```ek9\n      mon <- Day.Monday\n      wed <- Day.Wednesday\n\n      stdout.println(`as text: ${mon} and ${wed}`)\n      stdout.println(`mon == wed?  ${mon == wed}`)\n      stdout.println(`mon < wed?   ${mon < wed}`)\n      stdout.println(`first day:   ${#< mon}`)\n      stdout.println(`last day:    ${#> mon}`)\n\n      fromText <- Day(\"Friday\")\n      stdout.println(`from \"Friday\": ${fromText}   (set? ${fromText?})`)\n\n      nonsense <- Day(\"Blursday\")\n      stdout.println(`from \"Blursday\" set? ${nonsense?}`)\n```\n\nwhich prints:\n\n```text\nas text: Monday and Wednesday\nmon == wed?  false\nmon < wed?   true\nfirst day:   Monday\nlast day:    Sunday\nfrom \"Friday\": Friday   (set? true)\nfrom \"Blursday\" set? false\n```\n\nThat is four kinds of behaviour:\n\n- **Text:** `$` (and `${mon}` inside a string) gives a value's name.\n- **Comparing:** `==` for equality, and `<` and `<=>` for order. Values compare in the order you\n  listed them, so `Monday < Wednesday`.\n- **Ends:** `#<` gives the first value of the type and `#>` the last — `Monday` and `Sunday`.\n- **From text:** `Day(\"Friday\")` builds a `Day` from a string. A name that is not in the list does not\n  raise an error; it gives an *unset* `Day`, and `?` reports `false`.\n\nTurning outside text — a line from a file, a word from a form — into a typed value is where programs\nmeet bad input. An enumeration turns that into a set-or-unset question: build it, ask `?`, carry on.\n\n## The switch that cannot forget\n\nWhen you `switch` on an enumeration, the compiler insists you handle **every** value. Suppose\n`kindOf` listed only `Day.Saturday` in its weekend case and left out `Day.Sunday`\n(`missingCase.ek9`, in the `error-examples` folder). It would not build:\n\n```text\nEK9     : Error   : E07310: 'switch' on line 18 position 6: should cover values: (Monday as Day, Tuesday as Day, Wednesday as Day, Thursday as Day, Friday as Day, Saturday as Day, Sunday as Day) : 'cases' should cover all enumerated values in 'switch'\n             See: ek9 -h E07310\n```\n\nOur `kindOf` covers all seven days — the five weekdays in one `case`, the two weekend days in another\n— and adds a `default` for the remaining possibility: a `Day` can be unset, like any other value. The\n`default` is required even when the cases name every value; EK9 asks for one on *every* switch\n(`E07320`).\n\nThis matters most when the enumeration changes. Suppose next month you add `Day.Holiday`. In many\nlanguages every `switch` with a catch-all would carry on, treating a holiday as an ordinary weekday —\na bug found only when someone notices. In EK9, every switch that does not handle the new value stops\ncompiling, and each error points at a place that now needs a decision. \"Remember to update every\nplace\" becomes a list of errors from the compiler, so a forgotten case cannot survive.\n\n## Try it yourself\n\n1. Add a `name as String` field to `Coord` and print it. Nothing else has to change.\n2. Add a `TrafficLight` enumeration (`Red`, `Amber`, `Green`) and a function that returns what a driver\n   should do for each. (Not `Colour`: that name belongs to the built-in type, and the compiler refuses\n   it with `E01090`.) Name every value, and add a `default` as well: EK9 requires one even when every\n   value is listed (`E07320`), because the value could be unset.\n3. Add a fourth value, `Flashing`, to `TrafficLight` and build. Read the error, and follow it to the\n   switch that no longer handles every case.\n\n## Recap\n\nA **record** is an open bundle of named **fields** (`defines record`), read and set with a dot. It\ngets a little behaviour from **operators**: `$` for its text form, and a `default <=>` from which `==`\nand the other comparisons are generated. A **constructor** builds a complete value in one step; the\n**default constructor** builds a blank one to fill in later. An **enumeration** (`defines type`) is a\nfixed set of **named values** that can never hold a wrong one, and it comes with `$`, `==`, `<` and\n`<=>`, `#<` and `#>`, and safe build-from-text, with no `default operator` to write. A `switch` over an\nenumeration must handle **every** value, so adding a value turns \"did I update every place?\" into\ncompile errors. Next, *Constrained Types* applies the same \"a value cannot be wrong\" idea to familiar\ntypes: a driving age that is an `Integer`, but never `-5`.\n\n[^perlis]: Alan Perlis, *Epigrams on Programming* (1982), epigram number 9: \"It is better to have 100\nfunctions operate on one data structure than 10 functions operate on 10 data structures.\" Perlis was\nthe first recipient of the Turing Award, in 1966.\n\n[^fielddecl]: A field can also be declared with `<-`, as an ordinary variable is — `x <- Integer()` —\nand the compiler infers the type. It is shorter, especially for collections, where the explicit form\nnames the type twice (`scores as List of Integer: List() of Integer`) and the `<-` form names it once\n(`scores <- List() of Integer`). This book uses the explicit `as Type:` form for fields, so every\nfield's type is written out while you learn the shapes; the second volume moves to the shorter form.\n\n[^copyin]: Why copy, rather than store `initialX`? An `Integer` in EK9 is an object held by reference.\nKeeping the caller's object would let the caller change this `Coord`'s field later, through their own\nvariable. Taking a fresh `Integer(initialX)` means the `Coord` owns its value. For the literals in this\nexample — `Coord(2, 3)` — it makes no difference; the habit matters when a value comes from code that\nmight change it. The *Classes* chapter gives the full reasoning, under the name *representation\nexposure*.\n","examples":["books/getting-started-with-ek9/ch14-records-enums/Coord.ek9","books/getting-started-with-ek9/ch14-records-enums/DayOperators.ek9","books/getting-started-with-ek9/ch14-records-enums/Days.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 15","title":"Constrained Types","url":"https://ek9.io/books/getting-started-with-ek9/constrained-types.html","markdown":"# Constrained Types\n\nAn **enumeration** can only hold one of the names you listed: a `Day` is `Monday` to `Sunday` and\nnothing else, so a wrong value cannot exist at all. This chapter applies the same idea to familiar\ntypes. A driving age is an `Integer`, but not *any* `Integer`: it is one between 16 and 100. A\n**constrained type** lets you say exactly that, and the compiler and the running program hold you to it.\n\n## Declaring one\n\nA constrained type is a new, named type built on an existing one, with a rule attached:\n\n```ek9\n  defines type\n    DrivingAge as Integer constrain as\n      >= 16 and <= 100\n```\n\n`DrivingAge` is an `Integer` *constrained* to values `>= 16 and <= 100`. It is a distinct type with its\nown name, but it keeps everything an `Integer` can do: you can add it, compare it, print it and ask\nwhether it is set. What it adds is the rule: no `DrivingAge` may hold a number outside 16 to 100.\n\nThe rule can be any condition the underlying type understands. Numbers take ranges; text takes a\npattern (both are in `Rules.ek9`):\n\n```ek9\n    Ratio as Float constrain as\n      >= 0.0 and <= 1.0\n\n    Email as String constrain as\n      matches /^[a-z]+@[a-z]+$/\n```\n\nThe rule always goes on its own line, indented under `constrain as`; writing it on the same line is\na syntax error.\n\n`Integer`, `Float` and `String` can be constrained this way, and so can `Money`, `Date`, `Time`,\n`Dimension` and `Colour`. The underlying type brings its behaviour; you bring the boundary. You cannot\nconstrain a type that is *already* constrained — build on `Integer`, not on an age type you made\nearlier. Layering one constraint on another is an error (`E04010`): one flat rule is easier to read,\nand to trust, than a stack of them.\n\n## Building one, the direct way\n\nYou make a `DrivingAge` with its constructor:\n\n```ek9\n#!ek9\ndefines module book.constrain\n\n  defines type\n    DrivingAge as Integer constrain as\n      >= 16 and <= 100\n\n  defines function\n    verdict()\n      -> age as DrivingAge\n      <- rtn as String: `${age} is a valid driving age`\n\n  defines program\n    Show()\n      stdout <- Stdout()\n\n      // Direct construction, in range — behaves like the Integer underneath\n      age <- DrivingAge(17)\n      stdout.println(`age = ${age}   (set? ${age?})`)\n      stdout.println(`next year: ${age + 1}`)\n      stdout.println(verdict(age))\n\n      // Safe construction from an untrusted value with the .of factory\n      for raw in [20, 9, 133]\n        candidate <- DrivingAge().of(raw)\n        if candidate?\n          stdout.println(`${raw}: accepted -> ${candidate}`)\n        else\n          stdout.println(`${raw}: rejected (out of range)`)\n```\n\nIt prints:\n\n```text\nage = 17   (set? true)\nnext year: 18\n17 is a valid driving age\n20: accepted -> 20\n9: rejected (out of range)\n133: rejected (out of range)\n```\n\nThe first three lines come from `DrivingAge(17)`, and show `Integer`'s operators at work: `age + 1`\ngives `18`, `${age}` prints `17`, `age?` is `true`. The last three come from `DrivingAge().of(raw)`, a\nsecond way to build one that gives an *unset* value instead of stopping the program; *Building one, the\nsafe way*, below, explains it.\n\nNow look at `verdict`, a function that *takes a `DrivingAge`*. Its parameter is not \"an `Integer` I\nhope is a sensible age\"; it is a `DrivingAge`, and the type system guarantees that any value reaching\nit is already in range. The check happened once, when the value was built. Inside `verdict`, and\nanywhere else a `DrivingAge` goes, there is nothing left to validate: **a function that takes a\n`DrivingAge` can never be handed `-5`.**\n\n## It is not an Integer with a label\n\nIf a `DrivingAge` has all of `Integer`'s operators, can you use one *as* an `Integer` — assign it to an\n`Integer` variable, or pass it to a function that wants one? It is a natural thing to try:\n\n```ek9\n      age <- DrivingAge(17)\n      years as Integer: age          // assign to an Integer\n      r <- takesInteger(age)         // pass where an Integer is wanted\n```\n\nNeither compiles (the whole program is `notAnInteger.ek9`, in the `error-examples` folder):\n\n```text\nEK9     : Error   : E50030: 'years' on line 16 position 6: 'years as Integer' on line 16 in 'notAnInteger.ek9' and 'age as DrivingAge': types are not compatible with each other\n             See: ek9 -h E50030\nEK9     : Error   : E06270: 'takesInteger' on line 17 position 11: found function 'Integer <- takesInteger(n as Integer)' but used with supplied arguments '(DrivingAge)' not appropriate: parameter mismatch\n             See: ek9 -h E06270\n           forAI: methodResolution\n```\n\nA `DrivingAge` is **not** an `Integer`. It is a distinct type, built on `Integer` and sharing its\noperators, but not interchangeable with it. If a `DrivingAge` could stand in for any `Integer`\nunnoticed, the guarantee would be lost the first time one passed through general-purpose number code.\n\nWhen you do want the plain number, you ask for it with the promotion operator `#^`:\n\n```ek9\n#!ek9\ndefines module book.promote\n\n  defines type\n    DrivingAge as Integer constrain as\n      >= 16 and <= 100\n\n  defines function\n    takesInteger()\n      -> n as Integer\n      <- rtn as Integer: n + 1\n\n  defines program\n    Show()\n      stdout <- Stdout()\n      age <- DrivingAge(17)\n\n      // Deliberately take the plain Integer value with #^ — a fresh, independent copy\n      plain as Integer: #^age\n      plain += 5\n      stdout.println(`age stays ${age}, plain is now ${plain}`)\n\n      // Hand the promotion to code that wants a plain Integer\n      stdout.println(`takesInteger(#^ age) = ${takesInteger(#^age)}`)\n```\n\n```text\nage stays 17, plain is now 22\ntakesInteger(#^ age) = 18\n```\n\n`#^ age` **promotes** the `DrivingAge` to a plain `Integer`, and it does so by returning a *new,\nindependent* `Integer` holding a copy of the value. The first line of output shows it: adding `5` to\n`plain` leaves `age` at `17`. Promotion produces a separate value and leaves the constraint behind,\nwhich is why EK9 makes you write it rather than doing it unseen.\n\nThe other direction you already know: to turn an `Integer` *into* a `DrivingAge` you build one —\n`DrivingAge(x)` or `DrivingAge().of(x)` — and the constraint is checked as you do. So the only way\n*in* is to build (and be checked), and the only way *out* is to promote with `#^` (and get a separate\ncopy). Nothing crosses unnoticed.\n\n> **Note.** Arithmetic depends on *what* you combine. Combine a `DrivingAge` with a plain number —\n> `age + 1` — and the result is an ordinary `Integer` (`18`), not a `DrivingAge`, so the rule is *not*\n> checked; build a `DrivingAge` from the result if you need one. Combine *two* `DrivingAge` values —\n> `age1 + age2` — and the result is a `DrivingAge`, so the rule *is* checked:\n> `DrivingAge(60) + DrivingAge(60)` reaches `120` and **panics** with `Constraint violation`. The\n> operators that change a value in place — `++`, `--`, `+=`, `-=` and the rest — keep it a\n> `DrivingAge`: `age++` on `17` gives `18`, but `age--` on `16`, or `age += 5` on `100`, panics. Once a\n> value is a `DrivingAge`, none of them can take it out of range.\n\n## When the value is wrong\n\nWhat happens when a value breaks the rule depends on whether the compiler can see the problem.\n\nIf the compiler can work out the value — a plain number that is out of range — it will not build the\nprogram:\n\n```ek9\n      bad <- DrivingAge(5)\n```\n\n```text\nEK9     : Error   : E08260: '5' on line 11 position 24: '5' violates the constraint of 'DrivingAge' compile-time constant value violates the type's constraint — this would Panic at runtime\n             See: ek9 -h E08260\n```\n\n(That is `constraintCompile.ek9`, in the `error-examples` folder.)\n\nThe message says what *would* have happened: a panic when the program ran. Because the compiler could\nprove the value wrong, it stops you first.\n\nOften, though, the value is not known until the program runs — it comes from a person, a file or a\nform. The next program stands in for that by parsing the text `\"5\"` into an `Integer`, which to the\ncompiler looks exactly like input from a keyboard or a file: a number it cannot see in advance. The\ncheck then happens while the program runs (`constraintRuntime.ek9`, in the `error-examples` folder):\n\n```ek9\n#!ek9\ndefines module book.panicdemo2\n\n  defines type\n    DrivingAge as Integer constrain as\n      >= 16 and <= 100\n\n  defines program\n    Show()\n      stdout <- Stdout()\n      stdout.println(\"about to build a bad age...\")\n      raw <- Integer(\"5\")\n      bad <- DrivingAge(raw)\n      stdout.println(`built: ${bad}`)\n```\n\nRunning it prints:\n\n```text\nabout to build a bad age...\nException in thread \"main\" Panic: Constraint violation for book.panicdemo2::DrivingAge: Exit Code: 1\n```\n\nThe program printed its first line, then *panicked* — stopped at once — when it tried to build a\n`DrivingAge` from `5`. The line that would have printed the value never ran. Rather than let an\ninvalid `DrivingAge` into the program, where it could cause a wrong answer somewhere far away, EK9\nrefuses to create it. A loud stop at the source is easier to fix than a quiet error later.\n\n## Building one, the safe way\n\nA panic is the right response to a *bug*: a value that should never have been out of range. At the\nedge of a program, though, bad input is expected. People mistype; files contain bad rows. For that\ncase a constrained type has a second way to build one, the **`.of` factory**:\n\n```ek9\n      candidate <- DrivingAge().of(raw)\n      if candidate?\n        stdout.println(`${raw}: accepted -> ${candidate}`)\n      else\n        stdout.println(`${raw}: rejected (out of range)`)\n```\n\n`DrivingAge().of(raw)` never panics. If `raw` is in range you get a set `DrivingAge`; if not, you get\nan *unset* one, and `?` tells the two apart. That is why the loop over `[20, 9, 133]` in the first\nprogram runs to the end: `20` is accepted, `9` and `133` are rejected, and nothing stops. It is the\nsame check-before-use habit as `Optional` and `Result` in *Optional and Result*, applied to building\nyour own type.\n\nSo there are two ways to build, for two situations:\n\n- Use **`DrivingAge(x)`** when the value *should* already be valid. If it is not, that is a bug, and a\n  panic stops the program where the bug is.\n- Use **`DrivingAge().of(x)`** at the edge of the program, where bad input is normal. You get a\n  set-or-unset value to test with `?`, and the program stays in control.\n\nThe constructor states a fact you are sure of; the factory asks a question you do not yet know the\nanswer to.\n\n> **Note.** The `.of` factory has the same shape for every constrained type: `Email().of(text)`,\n> `Ratio().of(n)`, `Budget().of(amount)`. Build a blank one with `Type()`, then call `.of(value)` to\n> try a value safely. An unset input gives an unset result.\n\n## Try it yourself\n\n1. Add a `Percentage` type, written on two lines like `DrivingAge`:\n\n   ```ek9\n       Percentage as Integer constrain as\n         >= 0 and <= 100\n   ```\n\n   Build a valid one directly and print it, then pass `-10` and `250` through `.of` and check each\n   with `?`.\n2. Write a `Username`, again on two lines:\n\n   ```ek9\n       Username as String constrain as\n         matches /^[a-z][a-z0-9]+$/\n   ```\n\n   Try `.of(\"alice\")`, `.of(\"2cool\")` and `.of(\"Bob\")`, and see which are accepted.\n3. Write `DrivingAge(5)` directly and read the compile error. Then take the number from a program\n   argument instead, so the compiler cannot see it, and see where the check happens now.\n\n## Recap\n\nA **constrained type** is a named type built on a familiar one — `DrivingAge as Integer constrain as`\n`>= 16 and <= 100` — that keeps the underlying type's operations and adds a rule about which values\nare allowed. Build one **directly** with `DrivingAge(x)` when the value should already be valid: a\nprovably bad literal is a **compile error** (`E08260`), and a bad value found while running\n**panics**. Build one **safely** at the edges with `DrivingAge().of(x)`, which returns a set-or-unset\nvalue you check with `?`. A constrained type is a **distinct type**, not a relabelled `Integer`: it\nwill not stand in for one, and you get the plain value out by **promoting** it with `#^`, which gives\na separate copy. With enumerations, constrained types let you make **illegal states unrepresentable**:\nnot \"please pass a sensible age\" in a comment, but a type that cannot hold a wrong one. Next,\n*Classes*: data protected not by a range but by the behaviour you attach to it.\n","examples":["books/getting-started-with-ek9/ch15-constrained-types/DrivingAge.ek9","books/getting-started-with-ek9/ch15-constrained-types/Increment.ek9","books/getting-started-with-ek9/ch15-constrained-types/Promotion.ek9","books/getting-started-with-ek9/ch15-constrained-types/Rules.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 16","title":"Classes","url":"https://ek9.io/books/getting-started-with-ek9/classes.html","markdown":"# Classes\n\nRecords hold plain data, and constrained types narrow it. The other half of the choice in *Two Ways to\nBuild: Data, Functions and Objects* is **objects**. In EK9 an object is made from a **class**, and the\nshortest useful definition is this: *a class is a record whose fields are hidden, with functions\nattached*. Those attached functions are called **methods**. A method is a function that belongs to the\naggregate and can see its hidden fields, which ordinary functions cannot.\n\n## The smallest class\n\nHere is a counter, about the smallest class worth writing:\n\n```ek9\n#!ek9\ndefines module book.counter\n\n  defines class\n    Counter\n      count as Integer: 0\n\n      tick()\n        count += 1\n\n      total() as pure\n        <- rtn <- Integer(count)\n\n      default operator ?\n\n  defines program\n    Show()\n      stdout <- Stdout()\n      clicks <- Counter()\n      clicks.tick()\n      clicks.tick()\n      clicks.tick()\n      stdout.println(`clicks so far: ${clicks.total()}`)\n```\n\n```text\nclicks so far: 3\n```\n\n`defines class` opens it; `Counter` names it. So far it looks like a record: one field, `count`,\nstarting at `0`. The difference is what other code *cannot* do. A record's fields are open to any code\nwith a dot. A class's fields are **always private**: there is no way to make one reachable from\noutside. Outside the class, `clicks.count` is not allowed; the only way to change the count is\n`tick()`, and the only way to read it is `total()`. The methods are the object's public surface, and\nthe field behind them is out of reach.[^noprotected]\n\n`total()` is written in the shorter inferred-return form, `<- rtn <- Integer(count)`,[^inferrtn] and it\nreturns `Integer(count)` — a *copy* of the field, not the field itself. Why that matters is the\nsubject of \"The leak nobody mentions\", below.\n\nBecause no outside code can touch `count`, it can never be set to `-5` or `1000`, or reset. It changes\nonly through `tick()`, by exactly one. The object **looks after its own state**.\n\n## Why hide anything?\n\n*Records and Enumerations* argued for keeping data open. Open and hidden suit different jobs.\n\nA record is public data, right when the data is just *values to carry around*, with no rules about\nwhat is allowed. A class is right when the data has **rules to enforce**: a count that may only go up,\na balance that may not go negative, a list that must stay sorted. Hide the data, and those rules live\nin one place — the methods — with no way around them. The point is not secrecy; it is that every\nchange goes through code you control.\n\nSo the choice becomes a simple test: *is this just data, or data with rules?* Just data: use a\nrecord. Data with rules to protect: use a class.\n\n## Guarding real state\n\nHere is a class doing a real job: a scoreboard that keeps a list of scores and always knows the best\none.\n\n```ek9\n#!ek9\ndefines module book.scoreboard\n\n  defines record\n    Summary\n      count as Integer: Integer()\n      best as Integer: Integer()\n\n      Summary() as pure\n        ->\n          c as Integer\n          b as Integer\n\n        count :=? Integer(c)\n        best :=? Integer(b)\n\n      operator $ as pure\n        <- rtn as String: `${count} scores, best ${best}`\n\n      default operator ?\n\n  defines class\n    ScoreBoard\n      scores as List of Integer: List() of Integer\n      topScore as Integer: Integer()\n\n      add()\n        -> points as Integer\n        scores += Integer(points)\n        if not topScore? or points > topScore\n          topScore := Integer(points)\n\n      summary() as pure\n        <- rtn <- Summary(length scores, topScore)\n\n      default operator ?\n\n  defines program\n    Show()\n      stdout <- Stdout()\n      board <- ScoreBoard()\n      board.add(30)\n      board.add(70)\n\n      snap <- board.summary()\n      stdout.println(`snapshot after two: ${snap}`)\n\n      board.add(90)\n      stdout.println(`snapshot is unchanged: ${snap}`)\n      stdout.println(`live summary now:     ${board.summary()}`)\n```\n\n```text\nsnapshot after two: 2 scores, best 70\nsnapshot is unchanged: 2 scores, best 70\nlive summary now:     3 scores, best 90\n```\n\n`ScoreBoard` hides two fields: the `scores` list and the running `topScore`. The only way to add a\nscore is `add()`, which does two things together: it appends the score *and* keeps `topScore`\ncorrect. The two can never drift apart, because they are updated together, every time, in the one\nmethod allowed to change them. Keeping two facts in step is exactly the kind of rule a class exists to\nprotect. (The list field starts as `List() of Integer`, an empty list — which, as *Collections*\nnoted, is *set*, with nothing in it yet.)\n\n## Sealing the empty back door\n\nBoth classes so far gave every field a starting value. Some fields have no sensible starting value.\nAn account without an owner is not an account with a *blank* owner; it is meaningless. So you declare\nthe field in the *absent* form, `owner as String?` — a name with no object yet — and give the class a\nconstructor that requires an owner:\n\n```ek9\n#!ek9\ndefines module book.account\n\n  defines class\n    Account\n      //No sensible starting value exists: an account without an owner is nonsense.\n      owner as String?\n      balance as Integer: 0\n\n      //Seals off the no-argument constructor, so no ownerless Account can be built.\n      default private Account() as pure\n\n      Account() as pure\n        -> who as String\n        owner :=? String(who)\n\n      deposit()\n        -> amount as Integer\n        require amount > 0\n        balance += amount\n\n      statement() as pure\n        <- rtn as String: `${owner} has ${balance}`\n\n      default operator ?\n\n  defines program\n    Show()\n      stdout <- Stdout()\n\n      acc <- Account(\"Sam\")\n      acc.deposit(30)\n      acc.deposit(70)\n      stdout.println(acc.statement())\n      stdout.println(`account set? ${acc?}`)\n```\n\n```text\nSam has 100\naccount set? true\n```\n\nThe line to look at is this one:\n\n```ek9\n      default private Account() as pure\n```\n\nEvery class has a no-argument constructor, `Account()`. Usually that is harmless, because the fields\nhave starting values. Here it would be a back door: an `Account()` built with no arguments would have\nno `owner`, and nothing would stop that half-built object being passed around as if it were real. So\nEK9 refuses. Delete that line and the compiler stops you (`openConstructor.ek9`, in the\n`error-examples` folder, is `Account.ek9` without it):\n\n```text\nEK9     : Error   : E07175: 'Account' on line 5 position 4: default constructor must be 'private' when uninitialised properties exist\n             See: ek9 -h E07175\n```\n\n`default private Account() as pure` is the fix: `default` means the standard no-argument constructor,\nand `private` means no outside code can call it. The only way left to make an `Account` is\n`Account(\"Sam\")`, which demands an owner. `owner` starts *absent*, and every constructor must give it\nan object (here `String(who)`) before the object can exist. A half-built `Account` cannot reach the\nrest of your program, because it cannot be created.\n\n> **Note — the object itself, `this`.** The constructor calls its parameter `who`, not `owner`, so\n> there is no doubt which is which. If you want a parameter to share a field's name, `this` settles it:\n> `this.owner` is the field and plain `owner` the parameter, so `this.owner :=? owner` is unambiguous.\n> `this` is the object a method is working on. Use it to name a field explicitly, or to pass the whole\n> object to something else.\n\nMany languages leave this problem — objects that exist but are not fully formed — to your discipline:\n*remember* to make the constructor private, *remember* not to call it. EK9 removes the remembering. If\na field has no honest starting value, the empty constructor is sealed, or the code does not build.\n\n## The anaemic class: a record in disguise\n\nA common wrong turn is a class with a private field, a `getScore()` and a `setScore()` for it, then\nanother field and another pair, until the class is nothing but fields and the methods that expose\nthem.\n\nThat class hides nothing. A `setScore()` that writes any value straight to the field is an open field\nwith extra typing: the rules you hid the data to protect are never applied. If you want open data, use\na **record**. Use a class when it does something a record cannot — *guard* its state, *enforce* a\nrule, *keep two fields in step*. A class of plain getters and setters is a record in disguise, and the\ndisguise costs clarity for nothing.\n\n## The leak nobody mentions\n\nNow the reason for `Integer(count)`. This trap catches experienced programmers too.\n\n**In EK9 there are no primitives.** An `Integer` is not a bare machine number; it is a full object,\nand — like every value in EK9 — you hold it by *reference*. When you pass or return an object, you\nhand over the very same object, not a duplicate. That is fast, but it means sharing is the default.\nEK9's rule is the same for every type: **everything is a reference, and nothing is copied unless you\nask.** It applies to `Integer`, `List`, your own classes — every type. The one exception you have met is\na constant, which is handed over as a copy so that nothing can change it (*Text, Numbers, Time and\nMoney*).[^javabuckets]\n\nSuppose `Counter` returned its field directly:\n\n<!-- listing: fragment -->\n```ek9\n      total() as pure\n        <- rtn as Integer: count      // WRONG: hands back the field itself\n```\n\nWatch it leak:\n\n<!-- listing: fragment -->\n```ek9\n      clicks.tick()                  // three ticks -> count is 3\n      stdout.println(`total via method: ${clicks.total()}`)\n\n      n <- clicks.total()\n      n += 100\n      stdout.println(`after n += 100: n=${n}, counter says ${clicks.total()}`)\n```\n\n```text\ntotal via method: 3\nafter n += 100: n=103, counter says 103\n```\n\nWe added `100` to our *own* variable `n`, and the counter jumped to `103`. `<- rtn as Integer: count`\nreturned a reference to the very object the field holds, so `n` and the field are the same object:\nchange one and you change both. Even an integer getter leaks.\n\n**If you want a separate copy, ask for one.** That is what `Integer(count)` does. It is the *copy\nconstructor*: it makes a new `Integer` and copies the value in, so the caller gets an object of their\nown and the field is untouched. With it, `n += 100` moves `n` to `103` and leaves the counter at `3`.\nA copy costs work — a new object, and the value copied into it — so EK9 does not make one behind your\nback on every read. You pay for a copy when you decide you want one, and it shows in the code. (There\nis also a copy operator, `:=:`, for copying *into* an existing object; for returning a fresh value, the\ncopy constructor is simpler.)\n\nWith a collection the same leak is worse, because a whole list is exposed. Suppose a board\n(`LeakyBoard.ek9`) had a method that returned its list, beside a `count()` of its scores:\n\n<!-- listing: fragment -->\n```ek9\n      rawScores() as pure\n        <- rtn as List of Integer: scores      // WRONG: the actual list\n\n      count() as pure\n        <- rtn as Integer: length scores\n```\n\n```ek9\n      board.add(30)\n      board.add(70)\n      stdout.println(`count via class: ${board.count()}`)\n\n      leaked <- board.rawScores()\n      leaked += 999999\n      stdout.println(`the list we got back has ${length leaked} items`)\n      stdout.println(`but the board's own count is now: ${board.count()}`)\n```\n\n```text\ncount via class: 2\nthe list we got back has 3 items\nbut the board's own count is now: 3\n```\n\nWe never called `add`. We took the list, added a number to it, and the board's count changed —\nbecause `rawScores()` returned the board's own list, and now the caller and the board hold the same\none. The field was private and the method looked read-only, yet the protection was lost anyway. This\nis called **representation exposure**, and it is a common way for a class to lose control of its\ndata.[^repexposure]\n\nThe fix is the one `summary()` already uses. To *show* internal state, do not hand out the real thing;\nbuild a **new record** filled with *copies* of the information. That is why the `Summary` constructor\ncopies each value in (`count :=? Integer(c)`, `best :=? Integer(b)`): the snapshot must share nothing\nwith the board. In the output above, the `snap` taken after two scores still reads \"2 scores, best 70\"\nafter a third went in. It cannot change, because every value inside it is its own copy. The caller\ngets the information and *no* way into your internals.\n\nThis also buys freedom. Callers only ever see a `Summary`, never the list, so you can change how a\n`ScoreBoard` stores its scores — a different collection, a running tally, a database — and no caller\nbreaks, as long as you can still produce a `Summary`. That is the idea underneath encapsulation: hide\nthe decisions most likely to change, so the rest of the program does not depend on them.[^parnas]\n\n> **Aside — other languages.** Every language has this problem; they differ in how consistent their\n> rule is. In C# and Java, numbers are copied but lists are shared, and a \"read-only\" list is often a\n> read-only *view* of the same list.[^csharp] In Go, structs are copied but slices and maps still\n> share their contents.[^go] Rust forbids sharing and changing at the same time, and makes you write\n> `.clone()` for a copy.[^rust] EK9 is closest to Rust in that a copy is always something you ask for\n> by name, and it has no special cases: you make the same decision — share a reference, or hand over a\n> copy — every time, for every type.\n\n> **Note.** When a class holds a cluster of plain data, you do not have to choose \"hidden\" or \"open\"\n> for all of it. Put the plain data in its own **record**, hold that record as a field of the class,\n> and keep the class's behaviour around it.\n\n## Try it yourself\n\n1. Give `Counter` a `reset()` method — but first decide whether it *should* have one. Who is allowed to\n   reset a scoreboard mid-game? Hiding the data makes you answer questions like this on purpose.\n2. Add a `lowest()` to `ScoreBoard`, kept correct in `add()` the same way `topScore` is. Check the two\n   stay in step whatever order scores arrive in.\n3. Add the leaky `rawScores()` to `ScoreBoard`, reproduce the count changing underneath you, then\n   replace it with a method that returns a `Summary` and see the leak close.\n\n## Recap\n\nA **class** is a record with its fields **hidden** and **methods** attached; a method is a function\nthat belongs to the aggregate and can see its fields. Use a class rather than a record when the data\nhas **rules to protect**: the fields are private, so every change goes through a method you control.\nIf a field has no sensible starting value, the no-argument constructor must be **private**. A class of\nnothing but getters and setters is an **anaemic** class — a record in disguise. Because EK9 has **no\nprimitives**, returning a field hands back the real object, so a caller can change your internals:\n**representation exposure**. Ask for a copy explicitly with the **copy constructor**\n(`Integer(count)`), and to *show* internal state, return a **new record** filled with copies. That\nprotects your state and leaves you free to change the implementation behind a stable interface. Next,\n*Abstract Types, Subtypes and Polymorphism*: one name standing for several kinds of thing, each\nbehaving in its own way.\n\n[^noprotected]: Many languages offer a `protected` visibility that lets *subclasses* reach a parent's\nfields. EK9 has nothing like it for state: class fields are always private. (Methods may be public —\nthe default — or `protected` or `private`; only *fields* are private-only.) This is deliberate. Shared,\nsubclass-visible state is how inheritance comes to break encapsulation and produce the \"fragile base\nclass\": a subtype comes to depend on a parent's internals, and a later change to the parent breaks it.\nIn EK9 a subtype can use a parent's *methods*, never its fields. *Traits and Composition* returns to\nthis when it weighs inheritance against composition.\n\n[^inferrtn]: The `<- rtn <- value` form lets the compiler *infer* the return type from the value; it is\na shorter way to write `<- rtn as Integer: value`. It works when the type is obvious from a **simple**\nvalue: a construction like `Integer(count)` or `Summary(...)`, or a literal. A more involved expression,\nor a bare reference to a variable (`<- rtn <- count`), does not qualify (`E04050`); write the explicit\n`<- rtn as Type:` form there instead.\n\n[^javabuckets]: Java, by contrast, has three cases to keep in mind: primitives such as `int` are\ncopied, so returning one is safe; `String` is an object but cannot be changed, so sharing it is also\nsafe; but an `ArrayList` or any ordinary changeable object is shared, so returning one leaks. Whether a\ngetter is safe depends on which case the type falls into. The `Counter` leak above could not happen\nwith a Java `int`; it can with any changeable Java object.\n\n[^repexposure]: The term *representation exposure* — and the remedy of never returning a reference to\na changeable internal part — is from Barbara Liskov and John Guttag, *Program Development in Java:\nAbstraction, Specification, and Object-Oriented Design* (Addison-Wesley, 2000). Joshua Bloch puts the\nworking attitude bluntly in *Effective Java*: \"You must program defensively, with the assumption that\nclients of your class will do their best to destroy its invariants.\"\n\n[^parnas]: David L. Parnas, \"On the Criteria To Be Used in Decomposing Systems into Modules,\"\n*Communications of the ACM* 15, no. 12 (1972): 1053–1058. Parnas's principle of *information hiding* is\nthat each module should hide a design decision likely to change, so that the decision can be revised\nwithout disturbing the rest of the system.\n\n[^csharp]: In C#, `List<T>.AsReadOnly()` and the `IReadOnlyList<T>` interface return a read-only *view*\nover the same underlying list, not an independent copy; the backing collection remains changeable. See\nMicrosoft Learn, \"IReadOnlyList\\<T\\> Interface\" and \"List\\<T\\>.AsReadOnly Method.\"\n\n[^go]: In Go, slices and maps are reference-like: assigning or returning one copies a header that still\npoints at the shared backing array or store, so changes through the copy are visible to the original.\nDefending requires an explicit `copy()` (slices) or a manual clone (maps). See \"Arrays, Slices and\nMaps\" in Go 101.\n\n[^rust]: Rust enforces this at compile time through its borrow checker: data may be shared or changed\nbut not both at once, so an outstanding reference to a field prevents that field being changed. An\nowned, independent value is obtained explicitly with `.clone()`. See *The Rust Programming Language*,\n\"References and Borrowing.\"\n","examples":["books/getting-started-with-ek9/ch16-classes/Account.ek9","books/getting-started-with-ek9/ch16-classes/Counter.ek9","books/getting-started-with-ek9/ch16-classes/LeakyBoard.ek9","books/getting-started-with-ek9/ch16-classes/LeakyCounter.ek9","books/getting-started-with-ek9/ch16-classes/ScoreBoard.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 17","title":"Abstract Types, Subtypes and Polymorphism","url":"https://ek9.io/books/getting-started-with-ek9/polymorphism.html","markdown":"# Abstract Types, Subtypes and Polymorphism\n\nYou can now build data (records), narrow it (constrained types) and guard it (classes). The remaining\npiece of type design is how types *relate* to one another. A circle and a rectangle are both\n**shapes**. A program often wants to ask them the same question — \"what is your area?\" — while each\nanswers in its own way. One question with many answers, chosen by the actual type of the value, is\ncalled **polymorphism**. It rests on two ideas: **abstract types** and **subtypes**.\n\n## A type that cannot stand alone\n\nStart with the shared idea, a shape, written as an **abstract** class:\n\n```ek9\n    Shape as abstract\n      name() as pure abstract\n        <- rtn as String?\n\n      area() as pure abstract\n        <- rtn as Float?\n```\n\n`Shape as abstract` says this type is deliberately *incomplete*. Its two methods are marked `abstract`\nand have no body: `<- rtn as Float?` says what kind of answer `area` gives (a `Float`) but not *how* to\ncompute it, because a shape in general has no area. An abstract type is a contract, not a thing.\n\n> **Note — `?` and the shapes.** Every aggregate that holds fields must answer \"am I set?\" with a `?`.\n> `Circle` and `Rectangle`, which you will meet in a moment, have fields, so each declares\n> `default operator ?`. `Shape` has *no* fields, so it needs nothing: a class with no fields is always\n> set, and the compiler gives it that `?` itself.\n\nEK9 enforces the contract. Try to make a plain `Shape` and it will not build:\n\n```ek9\n      s <- Shape()\n```\n\n```text\nEK9     : Error   : E50080: 'Shape' on line 15 position 11: which is a call to 'Shape' on line 5 in 'abstractShape.ek9': cannot make a call on an abstract function/type directly\n             See: ek9 -h E50080\n```\n\n(`abstractShape.ek9`, in the `error-examples` folder, is the whole program.)\n\nYou cannot create something incomplete. A `Shape` only becomes real when another type *fulfils* the\ncontract.\n\n## Fulfilling the contract: subtypes\n\nA **subtype** takes the abstract type and completes it. Here is one of two, each extending `Shape` and\nproviding a real `name` and `area`:\n\n```ek9\n    Circle extends Shape\n      radius as Float: Float()\n\n      Circle() as pure\n        -> r as Float\n        require r > 0\n        radius :=? Float(r)\n\n      override name() as pure\n        <- rtn as String: \"circle\"\n\n      override area() as pure\n        <- rtn as Float: PI * radius * radius\n```\n\n`extends` (you may also write `is`) declares that a `Circle` is a kind of `Shape`. The `override`\nkeyword on each method is required: it tells the reader, and the compiler, that this method replaces\nthe abstract one the parent declared. A `Rectangle` does the same with `width` and `height`.\n\nThe constructor uses three earlier lessons. `require r > 0` states a **precondition**: a circle with a\nzero or negative radius is meaningless, so the constructor refuses to build one.[^require]\n`radius :=? Float(r)` stores a **copy** of the incoming value rather than sharing the caller's (the\nreference-or-copy decision from *Classes*). And `area` multiplies by `PI`, a named **constant**\n(`PI <- 3.14159`) declared once at the top of the module, rather than a number buried in the\narithmetic.\n\nThe compiler checks subtypes too. Leave out one of the required methods and the subtype is still\nincomplete, so it must either supply the method or declare itself abstract. Here `Circle` leaves out\n`area` (`incompleteCircle.ek9`, in the `error-examples` folder):\n\n```text\nEK9     : Error   : E07130: 'Circle' on line 12 position 4: 'public Float <- area() as abstract' on line 9 in 'incompleteCircle.ek9' not overridden: not declared abstract but still has abstract methods/operators\n             See: ek9 -h E07130\n```\n\nA **concrete** type — one complete enough to build, which is what \"not abstract\" means — cannot\nhalf-fulfil a contract. Either it supplies every method, or it is abstract too\nand cannot be built.\n\n## One question, many answers\n\nBecause a `Circle` and a `Rectangle` are both `Shape`s, you can put them together and treat them the\nsame way:\n\n```ek9\n#!ek9\ndefines module book.shapes\n\n  defines constant\n    PI <- 3.14159\n\n  defines class\n    Shape as abstract\n      name() as pure abstract\n        <- rtn as String?\n\n      area() as pure abstract\n        <- rtn as Float?\n\n    Circle extends Shape\n      radius as Float: Float()\n\n      Circle() as pure\n        -> r as Float\n        require r > 0\n        radius :=? Float(r)\n\n      override name() as pure\n        <- rtn as String: \"circle\"\n\n      override area() as pure\n        <- rtn as Float: PI * radius * radius\n\n      default operator ?\n\n    Rectangle extends Shape\n      width as Float: Float()\n      height as Float: Float()\n\n      Rectangle() as pure\n        ->\n          w as Float\n          h as Float\n\n        require w > 0 and h > 0\n        width :=? Float(w)\n        height :=? Float(h)\n\n      override name() as pure\n        <- rtn as String: \"rectangle\"\n\n      override area() as pure\n        <- rtn as Float: width * height\n\n      default operator ?\n\n  defines program\n    Show()\n      stdout <- Stdout()\n\n      shapes <- List() of Shape\n      shapes += Circle(2.0)\n      shapes += Rectangle(3.0, 4.0)\n\n      for shape in shapes\n        stdout.println(`a ${shape.name()} has area ${shape.area()}`)\n```\n\n```text\na circle has area 12.56636\na rectangle has area 12.0\n```\n\n`shapes` is a `List of Shape`: it holds shapes, whatever their kind. The loop calls `shape.area()`\nknowing only that each value is a `Shape`, yet a circle's area comes from the circle's formula and a\nrectangle's from the rectangle's. There is no `if` to tell them apart: each value carries its own\n`area`, and calling it runs the right one. That is polymorphism: **one name, `area`, resolved to the\ncorrect behaviour by the actual type of the value when it is called.**\n\nNotice what the loop does *not* say: it names no concrete type. Add a `Triangle` next month — a new\nsubtype with its own `area` — put one in the list, and this loop prints its area too, unchanged. Code\nwritten against the abstract type keeps working for kinds of shape that did not exist when it was\nwritten.\n\n## Why it is safe to substitute\n\nAll of this depends on one guarantee: a `Circle` must be usable *anywhere* a `Shape` is expected. It\nhas an `area` and a `name`, and it behaves as a `Shape` should, so the loop can rely on it without\nchecking. The principle — a subtype must be substitutable for its parent, with no surprises — is called\nthe Liskov Substitution Principle, and it is what makes polymorphism dependable.[^liskov]\n\n## No casts — on purpose\n\nNotice also what the loop does not need. There is no cast and no type test: no way to ask a value\n\"are you *really* a `Circle`?\" and then reach inside it. **EK9 has no type casts at all**, by design,\nin the same spirit in which it has no `break`. A cast is a claim the compiler cannot check — \"trust me,\nthis `Shape` is a `Circle`\" — and a wrong cast is a well-known cause of programs crashing while they\nrun.[^cast] Remove the cast and that failure cannot happen.\n\nSometimes you do need behaviour that depends on the concrete type, more than a shared method like `area`\ncan express. For that EK9 has the **dispatcher**: a method that selects its behaviour from the *actual*\ntype of its arguments, with the compiler checking that every case is covered. It is a topic for the\nsecond volume. Most type-specific behaviour is handled as `area` was, by letting each type carry its own\nversion; the dispatcher covers the rest.\n\n> **Note.** `Shape` never said `as open`, yet `Circle` could extend it. An abstract type is\n> *automatically* open — its purpose is to be extended. A *concrete* class is *closed* unless you write\n> `as open`, and extending a closed class is an error (`E05030`, \"not open to be extended\"). So a type\n> can be extended exactly when it is meant to be.\n\n## Not only classes\n\nPolymorphism is not limited to classes. The same `extends`/`is` and `override` work for every\nbuilding block in the book.\n\n**Records** can form families too. A record's behaviour lives in its *operators* rather than in\nmethods, so a record family is polymorphic through those. Here an abstract `Contact` has an abstract\n`$`, and two kinds of contact each give their own text form:\n\n```ek9\n#!ek9\ndefines module book.contacts\n\n  defines record\n    Contact as abstract\n\n      operator $ as pure abstract\n        <- rtn as String?\n      default operator ?\n\n    Email extends Contact\n      address as String: String()\n\n      Email() as pure\n        -> a as String\n        address :=? String(a)\n\n      override operator $ as pure\n        <- rtn as String: `email ${address}`\n      default operator ?\n\n    Phone extends Contact\n      number as String: String()\n\n      Phone() as pure\n        -> n as String\n        number :=? String(n)\n\n      override operator $ as pure\n        <- rtn as String: `phone ${number}`\n      default operator ?\n\n  defines program\n    Show()\n      stdout <- Stdout()\n      contacts <- List() of Contact\n      contacts += Email(\"sam@example.com\")\n      contacts += Phone(\"555-0100\")\n      for c in contacts\n        stdout.println(`${c}`)\n```\n\n```text\nemail sam@example.com\nphone 555-0100\n```\n\nA `List of Contact` holds an `Email` and a `Phone` side by side, and `${c}` prints each in its own\nway: one name, many answers, this time through a record's `$`.\n\n> **Note — how deep a hierarchy may go.** EK9 limits inheritance depth: a class may sit at most four\n> levels below its root, a record at most two; go further and the build stops (`E11019`). For deeper\n> reuse, use **composition** — a field, or `by` delegation (*Traits and Composition*) — rather than a\n> tall tower of `extends`. Shallow hierarchies stay easy to follow; deep ones are where \"which version\n> runs here?\" becomes hard to answer.\n\n**Functions** have their own polymorphism, and you have already used it. The stream pipelines in\n*Streams and Pipelines* used `Predicate`, `Function` and `Consumer`. Those are function *types*: a\n`Predicate of T` is the shape \"takes a `T`, gives back a `Boolean`\", and *any* function of that shape\ncan stand in for it — `isEven`, `isPositive`, whichever you pass to `filter`. One function type,\nanswered by many concrete functions, each passed around like any other value. The full story is in\nthe second volume.\n\nSo \"one contract, many implementations\" runs through the whole language: classes, records, functions,\nand the component in *Components*. It is not a feature of objects alone.\n\n## Try it yourself\n\n1. Add a `Triangle extends Shape` with its own `area`, put one in the list, and confirm the loop prints\n   it with no change to the loop.\n2. Delete `override area()` from `Circle` and read the error.\n3. Try `bad <- Shape()` and read that error.\n4. Build a `Circle(-1.0)` and run it. The `require r > 0` precondition refuses the radius, so the\n   circle is never created.\n\n## Recap\n\nAn **abstract type** (`as abstract`) is an incomplete contract that cannot be created directly\n(`E50080`). A **subtype** completes it with `extends` or `is` and `override`, and the compiler\ninsists it supplies every required method or is abstract too (`E07130`). The result is\n**polymorphism**: a `List of Shape` holding many kinds, and one call to `area()` running the right\nbehaviour for each — code written once against the abstract type that works for every subtype, now\nand later. It is dependable because a subtype is always substitutable for its parent, so no value ever\nneeds to be tested or cast. Next, *Traits and Composition*: EK9's preferred way to share a contract,\nwithout carrying state along, and the composition EK9 favours over deep inheritance.\n\n[^require]: `require` insists its condition is *definitely* true. A value can be unset, and a\ncomparison involving an unset value — `r > 0` when `r` is unset — is itself an unset `Boolean`: neither\ntrue nor false. `require` treats that the same as `false`, and fails. So `require r > 0` rejects a zero\nor negative radius *and* an unset one; it passes only when the answer is a set, true `Boolean`. A\nfailed requirement stops the program and reports the exact condition that was not met, and where.\n\n[^cast]: In Java, for example, a wrong cast raises a `ClassCastException` when the program runs.\n\n[^liskov]: Barbara Liskov set out the principle in her 1987 keynote \"Data Abstraction and Hierarchy,\"\nlater formalised with Jeannette Wing as \"A Behavioral Notion of Subtyping\" (*ACM TOPLAS* 16, no. 6,\n1994). Informally: if `S` is a subtype of `T`, then objects of type `T` may be replaced with objects of\ntype `S` without breaking the program. A subtype that cannot stand in for its parent is behind the\nsurprised `UnsupportedOperationException` in code that assumed it could.\n","examples":["books/getting-started-with-ek9/ch17-polymorphism/Contacts.ek9","books/getting-started-with-ek9/ch17-polymorphism/Shapes.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 18","title":"Traits and Composition","url":"https://ek9.io/books/getting-started-with-ek9/traits.html","markdown":"# Traits and Composition\n\n*Abstract Types, Subtypes and Polymorphism* gave one way for many types to share a contract: an\nabstract class with subtypes. This chapter gives EK9's *preferred* way, the **trait**, and the style of\nbuilding it encourages: **composition** rather than deep inheritance.\n\nA trait is a named set of methods — with or without bodies — and no state of its own, which any\nclass can take on. The name comes from research on traits as *composable units of behaviour*:\nreusable behaviour, with no fields, that can be mixed into classes and combined without the\ncomplications of inheriting from several parents.[^traitname]\n\n> **Aside — why not \"interface\" or \"protocol\"?** Other languages use those words for similar ideas. An\n> *interface*, in its original Java sense, lists method signatures and nothing else; an EK9 trait can\n> also carry method bodies, so the word would undersell it. *Protocol*, the Swift word, already means\n> network protocols in computing, and EK9 has networking types, so the word would collide.\n\n## Behaviour that cuts across a hierarchy\n\nTraits are easiest to see where ordinary class inheritance struggles. Think about animals. A sensible\nclass hierarchy might put `Bird` and `Reptile` under a common `Animal`. Now ask: which animals can\n*swim*? A penguin can, and so can a crocodile — but a penguin is a bird and a crocodile is a reptile,\nso \"can swim\" does not belong on any one branch. Swimming, flying and walking are **behaviours** that\ncut *across* the hierarchy, and a single line of inheritance cannot express them.\n\nTraits can. Here each behaviour is a trait, and each animal takes the ones it has:\n\n```ek9\n#!ek9\ndefines module book.animals\n\n  defines trait\n    Named\n      name() as pure abstract\n        <- rtn as String?\n\n    Swimmer with trait of Named\n      swim() as pure\n        <- rtn as String: \"paddles through the water\"\n\n    Flyer with trait of Named\n      fly() as pure\n        <- rtn as String: \"takes to the air\"\n\n    Walker with trait of Named\n      walk() as pure\n        <- rtn as String: \"walks on land\"\n\n  defines class\n    Animal as abstract\n      name() as pure abstract\n        <- rtn as String?\n\n      category() as pure abstract\n        <- rtn as String?\n      default operator ?\n\n    Bird extends Animal as abstract\n      override category() as pure\n        <- rtn as String: \"bird\"\n      default operator ?\n\n    Reptile extends Animal as abstract\n      override category() as pure\n        <- rtn as String: \"reptile\"\n      default operator ?\n\n    Penguin extends Bird with trait of Swimmer, Walker\n      override name() as pure\n        <- rtn as String: \"penguin\"\n\n      override swim() as pure\n        <- rtn as String: \"flies through the water on stubby wings\"\n\n      default operator ?\n\n    Duck extends Bird with trait of Swimmer, Flyer, Walker\n      override name() as pure\n        <- rtn as String: \"duck\"\n\n      default operator ?\n\n    Crocodile extends Reptile with trait of Swimmer, Walker\n      override name() as pure\n        <- rtn as String: \"crocodile\"\n\n      override swim() as pure\n        <- rtn as String: \"glides silently through the water\"\n\n      default operator ?\n\n  defines program\n    Show()\n      stdout <- Stdout()\n      penguin <- Penguin()\n      penguinIs <- `The ${penguin.name()} (a ${penguin.category()})`\n      stdout.println(`${penguinIs} ${penguin.swim()} and ${penguin.walk()}.`)\n      duck <- Duck()\n      duckIs <- `The ${duck.name()} (a ${duck.category()})`\n      stdout.println(`${duckIs} ${duck.swim()}, ${duck.fly()} and ${duck.walk()}.`)\n      swimmers <- List() of Swimmer\n      swimmers += Penguin()\n      swimmers += Crocodile()\n      for s in swimmers\n        stdout.println(`the ${s.name()} ${s.swim()}`)\n```\n\n```text\nThe penguin (a bird) flies through the water on stubby wings and walks on land.\nThe duck (a bird) paddles through the water, takes to the air and walks on land.\nthe penguin flies through the water on stubby wings\nthe crocodile glides silently through the water\n```\n\nSeveral ideas are at work here; take them one at a time.\n\n**A trait carries behaviour, but no state.** `swim`, `fly` and `walk` each have a real method body.\nWhat a trait does *not* have is fields.\n\n**A trait's method is a default, not a fixture.** In the output, the duck \"paddles through the water\" —\nthe `swim` the `Swimmer` trait supplies — but the penguin \"flies through the water on stubby wings\" and\nthe crocodile \"glides silently\". Each of those is the class *overriding* the trait's method with its\nown version, as a subtype overrode an abstract method in the previous chapter. So a trait provides a\nshared default, and any class that has the trait can keep it or replace it. Because it is a real\noverride, it works with polymorphism: when the loop over `swimmers` calls `swim()`, each animal\nanswers in its own way.\n\n> **Note.** A trait method does not *have* to have a body. Leave the body off and the method is\n> **abstract**, as in an abstract class, and every class that takes the trait *must* supply its own\n> version or it will not compile (`E07130`, the same error a class gets for an unimplemented abstract\n> method). That is how a trait says \"you must provide this; I have no sensible default\". `swim` has an\n> obvious default, but a `name()` or a `price()` might not. You can mix the two — a method with a body,\n> written in terms of an abstract one — so the trait supplies the *shape* of some behaviour and each\n> class fills in the one piece only it knows.\n\n**The class hierarchy is separate and ordinary.** `Animal` is abstract; `Bird` and `Reptile` extend\nit (and are still abstract, because neither says what its `name` is); each concrete animal extends one\nof those. A class may extend only *one* parent class.\n\n**The join is the important part.** A concrete animal extends its one parent **and** takes any number\nof traits with `with trait of`. `Penguin extends Bird with trait of Swimmer, Walker` is a bird that can\nswim and walk; `Duck` adds `Flyer`; `Crocodile` is a reptile that swims and walks. Behaviours are\nmixed in, in whatever combination fits, *regardless* of where the animal sits in the class tree. That\nis what single inheritance cannot do.\n\n**You can group things by what they do.** `swimmers` is a `List of Swimmer`, and it holds a `Penguin`\nand a `Crocodile` — a bird and a reptile — because what they share is not a class but a *behaviour*.\n\n**A trait can build on another trait.** The loop prints `${s.name()}` as well as `${s.swim()}`, yet\n`s` is only known to be a `Swimmer`. `Swimmer with trait of Named` says every `Swimmer` is also\n`Named`, so any concrete swimmer must supply `name()`, and a `List of Swimmer` gives you both. `Named`\nis the small shared contract that `Swimmer`, `Flyer` and `Walker` all build on.\n\nList each trait once. `Penguin` gets `Named` through `Swimmer`, so it does not list `Named` itself;\nwriting `with trait of Swimmer, Walker, Named` is an error (`E02090`: \"'Named' is already a trait of\n'Swimmer'; list it once\").\n\nIn the previous chapter, polymorphism ran along a single line: a `Circle` could stand in for a `Shape`\nbecause it was a kind of shape. Traits add *other* lines. A `Penguin` can be used as an `Animal` (its\nplace in the class tree), **and** as a `Swimmer`, **and** as a `Walker` — three independent contracts\nit satisfies at once. Traits **extend polymorphism** beyond the one hierarchy a class belongs to: an\nobject can be used through every contract it fulfils.\n\nThe reverse is checked too. A `Penguin` never took `Flyer`, so `penguin.fly()` does not compile. The\nbehaviours a type has are checked, not assumed: a `Penguin` can be used as a `Swimmer`, never as a\n`Flyer`.\n\n## Composition without the boilerplate\n\nTraits also support the reuse style EK9 prefers. Suppose you want to *wrap* something that has a trait\nand change one part of its behaviour, leaving the rest as it was. That is the **Decorator** pattern,\none of the classic designs catalogued by the \"Gang of Four\": you place an object inside another that\noffers the *same* methods, so the wrapper can be used anywhere the original could, adding to or\nchanging what passes through. Because the wrapper is the same kind of thing, decorators can be stacked,\neach layer adding a little.[^decorator] Here a `View` has a `title` and a `body`, and `Framed` is\nanother `View` that puts a border around the body of the view it wraps:\n\n```ek9\n    Framed with trait of View by inner\n      inner as View?\n\n      default private Framed() as pure\n\n      Framed() as pure\n        -> viewToWrap as View\n        require viewToWrap?\n        inner :=? viewToWrap\n\n      override body() as pure\n        <- rtn as String: `*** ${inner.body()} ***`\n\n      default operator ?\n```\n\n`by inner` is the important part. It says \"I have the trait `View`, and its methods are **delegated**\nto my `inner` field.\" So `Framed` gets `title` — and every other `View` method — forwarded\nautomatically to whatever `inner` holds. It writes only the method it wants to change, `body`. Given\n`Framed(Home())`, `title()` returns `Home` (from the wrapped view) and `body()` returns\n`*** Welcome ***`.\n\nThis is **composition**: building a thing out of another thing it holds, rather than out of a parent\nit inherits from. It is EK9's preferred way to reuse behaviour. The advice to prefer composition over\ninheritance is long established; the obstacle has been the typing — to wrap an object you normally\nwrite a forwarding method for every one of its operations, and add another each time the wrapped type\ngrows. `by inner` writes them for you.[^composition] `inner` is held by *reference*, not copied, which\nis right here: a wrapper is meant to refer to one particular object and speak for it.\n\n## When two traits collide\n\nA type can hold several traits, so two unrelated traits might each declare a method with the same\nname. Which version should win? This *name clash* is what makes inheriting from several parents\nrisky, and EK9 refuses to guess: the combining type must **resolve it itself**. (Inheriting one and the\nsame method through two routes — where both traits got it from a shared trait — is not a clash: there\nis only one version, so nothing to choose.)\n\n```ek9\n    Widget with trait of Priced, Monitored\n      override lowCost() as pure\n        <- rtn as Boolean: Priced.lowCost()\n```\n\nBoth `Priced` and `Monitored` declare `lowCost`, so `Widget` must write its own `lowCost` and say what\nit means. It can use one trait's version by name — `Priced.lowCost()`, or `Monitored.lowCost()` —\ncombine both, as in `Priced.lowCost() and Monitored.lowCost()`, or write a new implementation of its\nown. What it may **not** do is leave the method out and let EK9 pick. Leave it out and the program does\nnot compile (`traitClash.ek9`, in the `error-examples` folder):\n\n```text\nEK9     : Error   : E06150: 'Widget' on line 10 position 4: method 'public Boolean <- lowCost()' on 'Monitored' and 'Priced' : conflicting methods to be resolved\n             See: ek9 -h E06150\n```\n\nSo a clash is never a surprise while the program runs, and never settled by an arbitrary winner: it\nis a compile error that names the clash for you to settle. There is more to combining traits well —\nScala, which brought traits to a wide audience, has a detailed scheme for stacking them in order — but\nthat is a topic for the second volume. The rule here: EK9 never chooses for you.\n\n## Sealing a family\n\nSometimes the set of types that implement a trait is meant to be *closed*: exactly these, no more. A\ntrait says so with `allow only`:\n\n```ek9\n    Payment allow only Card, Cash\n      amount() as pure\n        <- rtn as Integer?\n```\n\nOnly `Card` and `Cash` may be `Payment`s. A third type that tries — here a `Cheque`\n(`notAllowed.ek9`, in the `error-examples` folder) — is rejected at compile time:\n\n```text\nEK9     : Error   : E05240: 'Cheque' on line 17 position 4: 'Cheque' is not in 'Payment' allow only list: type is not permitted to extend/implement this sealed type\n             See: ek9 -h E05240\n```\n\nThat is useful when code elsewhere depends on handling *every* kind: a closed set the compiler can hold\nyou to, rather than an open one that might grow without your knowing.\n\n## Try it yourself\n\n1. Add a `Bat extends Mammal with trait of Flyer, Walker` (you will need a `Mammal` class too). It flies\n   and walks like a bird, though it is a mammal: the behaviour does not depend on the branch.\n2. Call `penguin.fly()` and read the error.\n3. Build a `List of Flyer`, add a `Duck` and something new, and confirm a `Penguin` is *not* allowed\n   in it.\n\n## Recap\n\nA **trait** is a stateless unit of behaviour that a class takes with `with trait of`. It can carry\nmethod bodies, which a class may keep or override, or abstract methods every class must supply; and a\nclass can take *many* traits, though it extends only one parent class. Traits capture behaviour that\n**cuts across** a class hierarchy — `Swimmer` shared by a bird and a reptile — so you can group and use\nthings by what they *do*, not only by what they *are*. Each trait is listed once (`E02090`). Traits\nare also the basis of EK9's preferred style, **composition**: `by` delegates a trait's methods to a\nfield, so you can wrap and reuse without writing forwarding methods. When traits clash, EK9 makes you\nresolve it (`E06150`); when a family should be closed, `allow only` seals it (`E05240`). Next,\n*Components*: the larger building blocks a program is assembled from.\n\n[^traitname]: The term and the mechanism come from Nathanael Schärli, Stéphane Ducasse, Oscar Nierstrasz\nand Andrew P. Black, \"Traits: Composable Units of Behaviour,\" *ECOOP 2003*, where a trait is a group of\nmethods with no state, a building block for classes that composes cleanly and resolves conflicts\nexplicitly. The ideas were first implemented in the Squeak dialect of Smalltalk, and were brought to a\nwide audience by Scala, whose standard text (Martin Odersky, Lex Spoon and Bill Venners, *Programming in\nScala*) devotes a chapter to exactly the two uses we see here: mixing behaviour into classes, and\nwidening a \"thin\" interface to a \"rich\" one by building default methods on abstract ones.\n\n[^composition]: \"Favour object composition over class inheritance\" is one of the two founding principles\nof the Gang of Four's *Design Patterns* (Gamma, Helm, Johnson & Vlissides, 1994). The case against\nleaning on inheritance is the **fragile base class problem** — a change to a base class can break its\nsubclasses, and you cannot tell it is safe by reading the base alone — and the observation, shown by\nWilliam Cook, Walter Hill and Peter Canning in \"Inheritance Is Not Subtyping\" (*POPL 1990*), that the\nuseful part (substitutability) is separable from the risky part (implementation inheritance). EK9 keeps\nthe first through traits and steers reuse toward composition, which `by` makes cheap.\n\n[^decorator]: The Decorator is one of the twenty-three patterns catalogued in Gamma, Helm, Johnson &\nVlissides, *Design Patterns: Elements of Reusable Object-Oriented Software* (1994). Its intent, in their\nwords, is to \"attach additional responsibilities to an object dynamically\" by wrapping it in another\nobject of the same interface — a flexible alternative to subclassing for extending behaviour. EK9's\n`by` delegation is what makes it cheap: the forwarding methods a decorator would otherwise need are\nwritten for you.\n","examples":["books/getting-started-with-ek9/ch18-traits/AllowOnly.ek9","books/getting-started-with-ek9/ch18-traits/Animals.ek9","books/getting-started-with-ek9/ch18-traits/Delegate.ek9","books/getting-started-with-ek9/ch18-traits/TraitClash.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 19","title":"Components","url":"https://ek9.io/books/getting-started-with-ek9/components.html","markdown":"# Components\n\nYou now have three ways to build an aggregate: a **record** for data, a **class** for data with\nbehaviour, and a **trait** for behaviour shared across types. The fourth is for a bigger job. A\n**component** is what you use when a whole *group* of cooperating types — classes, records, functions,\ntraits — should sit behind one simple element that hides them.\n\n## Hiding types, not just values\n\nA class practises **value hiding**: its fields are private, so callers reach its data only through the\nmethods it offers (*Classes*). A component does the same one level up: **type hiding**. It presents a\nsimple interface, and behind that interface is whatever set of classes, functions and records the work\nneeds. A caller depends on the interface alone, and never learns *which* types do the job, or how many\nthere are.\n\nThat is the purpose of the arrangement. Because every caller depends on the interface and nothing\nbehind it, the developer is free to change the implementation — swap the types, add new ones, rework\nthe whole calculation — without affecting any caller. Hiding the types is what leaves the\nimplementation *free to change*.[^extension]\n\nHere is the smallest example that shows the shape: a component that quotes a price, built on two\nhelpers.\n\n```ek9\n#!ek9\ndefines module book.pricing\n\n  defines class\n    TaxTable\n      surcharge()\n        <- rtn as Money: 2#GBP\n\n  defines function\n    basePrice()\n      <- rtn as Money: 10#GBP\n\n  defines component\n    Pricing as abstract\n      totalPrice() as abstract\n        <- rtn as Money?\n\n    StandardPricing is Pricing\n      override totalPrice()\n        <- rtn as Money?\n        table <- TaxTable()\n        rtn: basePrice() + table.surcharge()\n\n  defines program\n    Show()\n      stdout <- Stdout()\n      pricing as Pricing: StandardPricing()\n      stdout.println(`total price: ${pricing.totalPrice()}`)\n```\n\n```text\ntotal price: 12.00#GBP\n```\n\nA `component` is declared much like an abstract class: `Pricing as abstract` names the interface — one\nmethod, `totalPrice` — and `StandardPricing is Pricing` provides a concrete version. What makes it a\n*component* rather than a class is its role: it is the unit you put a whole subsystem behind.\n\nLook at the program. It holds `pricing` as a `Pricing` — the interface — and calls `totalPrice()`. It\ncreates a `StandardPricing` once, but never mentions `TaxTable` and never calls `basePrice`; those\nbelong to the implementation. The `Pricing` interface is all the rest of the program sees.\n\n## Why hide the types\n\nThat freedom is the reason components exist, so here it is in concrete terms. Today `totalPrice` adds\na base price and a surcharge from a small `TaxTable`. Tomorrow it could read live rates from a\ndatabase, split the work across five new classes, or replace the calculation entirely — and no line of\nthe program that calls `totalPrice()` would change, because none of it depended on how the price was\nworked out. A component separates *what a subsystem does* from *how it does it*, so the two can change\nindependently. It is information hiding, applied to a whole subsystem rather than a single\nobject.[^parnas2]\n\nComponents earn their place in *larger* software, where whole areas of a system — a payment engine, a\nsearch index, a report generator — are best kept behind a simple interface so the rest of the code\ndoes not depend on their internals. In a real project the internal types would live in their own\n**module**, in separate files, out of the caller's sight; this example keeps everything in one module\nso it fits in one file. Splitting a project across modules, and *injecting* a component so one\nimplementation can be swapped for another, are topics for the second volume.\n\n## Coupling, cohesion, and a compiler that keeps score\n\nTwo terms describe designs like this. **Coupling** is how much one part of a program depends on others\n— how many other things it reaches out to. **Cohesion** is how well the pieces *inside* one thing\nbelong together, all serving a single purpose. Good design wants coupling *low*, so a change in one\nplace does not spread everywhere, and cohesion *high*, so each thing has one clear job. Both terms date\nfrom 1974.[^couplingcohesion] A component is a tool for low coupling: by hiding a subsystem's types, it\nkeeps down the number of things the rest of the program depends on.\n\nEK9 does not leave coupling and cohesion as advice. The compiler **measures them** — how many other\nconstructs each class, record, trait, component and module depends on, and how well each one's parts\nbelong together — and enforces **generous but fixed limits**. Go past them and the code does not\ncompile: a class that depends on too many others, a module too tangled to be one module, a component\nwhose parts have drifted into unrelated jobs. The limits are deliberately loose, so ordinary code does\nnot meet them; they exist to catch a badly over-connected or unfocused design before it sets. When you\ncross one, the error gives your figure and the limit. (The EK9 IDE also shows each construct's coupling\nand cohesion as you write.)\n\nThis is the language's usual approach, applied to *structure*: a quality usually left to reviewers is\nsomething the compiler measures and enforces.\n\n> **Note.** Even this small example has to pass the compiler's quality rules. A helper with an unused\n> parameter is refused (`E08091`: \"parameter is declared but never used\"), and so is a literal repeated\n> three times (`E11065`: \"extract to a named constant\"). Small examples are checked exactly as large\n> programs are; there is no relaxed mode for sketches.\n\n## Try it yourself\n\n1. Add a second implementation, `SalePricing is Pricing`, whose `totalPrice()` takes `1#GBP` off the\n   standard price. Switch the program to it by changing only the line that makes `pricing`. Nothing\n   that uses `pricing` changes.\n2. Try to make a `Pricing()` directly, and read the compiler's error. Why can an abstract component\n   not be built?\n3. Give `TaxTable` a second method, and call it only from `StandardPricing`. Which parts of the program\n   would notice if you changed it later?\n\n## Recap\n\nA **component** is the fourth aggregate, alongside record, class and trait. A class hides its\n**values**; a component hides its **types** — a set of cooperating classes, functions and records behind\none simple interface — so callers depend on *what* a subsystem does, never on *how*. It is declared like\nan abstract class (`defines component`, an abstract interface, a concrete `is` implementation), and its\nrole is to draw a boundary around a subsystem. It comes into its own in larger programs, with its\ninternals in their own module; packaging and dependency injection are in the second volume. The compiler\nalso measures **coupling** and **cohesion** and enforces limits on both. Next, *Using Generics*: types\nwritten to work with *any* type.\n\n[^couplingcohesion]: The terms were coined by Wayne P. Stevens, Glenford J. Myers and Larry L.\nConstantine in \"Structured Design,\" *IBM Systems Journal* 13, no. 2 (1974): 115–139 — the paper that gave\nthe field the vocabulary of coupling and cohesion. The specific measures EK9 enforces are *efferent\ncoupling* (Ce — how many other constructs a construct reaches out to) and *LCOM4* (a lack-of-cohesion\nmeasure that counts how many disconnected clusters a type's methods and fields fall into; M. Hitz and\nB. Montazeri, \"Measurement of Coupling and Cohesion in Object Oriented Systems,\" 1995). Cohesion is\nchecked on classes, services and components — records and traits are exempt by design. EK9's thresholds\nare deliberately generous, set to leave its functional style unhindered while still catching\nover-connected or unfocused designs.\n\n[^extension]: This is the subject of David L. Parnas, \"Designing Software for Ease of Extension and\nContraction,\" *IEEE Transactions on Software Engineering* 5, no. 2 (1979): 128–138, which treats\nextensibility as \"a special case of design for change\": structure a system so that a module's\nimplementation can be extended or replaced without disturbing the code that uses it. Hidden internals\nbehind a stable interface are what buy that freedom.\n\n[^parnas2]: The principle is David Parnas's, from \"On the Criteria To Be Used in Decomposing Systems into\nModules\" (*Communications of the ACM* 15, no. 12, 1972), first met in *Classes*: each module should\nhide a design decision likely to change, so the decision can be revised without disturbing the rest of\nthe system. A class applies it to a data structure; a component applies it to a whole subsystem.\n","examples":["books/getting-started-with-ek9/ch19-components/Pricing.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 20","title":"Using Generics","url":"https://ek9.io/books/getting-started-with-ek9/generics.html","markdown":"# Using Generics\n\nYou have been using generics since *Collections*, without the name. A `List of String`, a `Dict of\n(String, Integer)`, and the `Optional` and `Result` from *Optional and Result* are all **generic**\ntypes. This chapter names the idea and shows how to read it. *Writing* your own generic types is a\ntopic for the second volume; here you learn to use the ones EK9 provides.\n\n## One definition, every type\n\nA list of strings, a list of integers and a list of whatever you invent next week all need the same\ncode. You do not want a separate `StringList`, `IntegerList` and `ShapeList`, the same code written out\nagain for each element type. A **generic** type avoids that by being a *template with a gap in it*.\nAsk EK9 for help on `List` (`ek9 -h List`) and the definition begins:\n\n```text\n    List of type T\n```\n\n`T` is a **type parameter**: a placeholder for the element type, filled in when you use the list. Fill\nit with `String` and you have a `List of String`; fill it with `Integer` and you have a\n`List of Integer`. Both are the one `List`, used two ways:\n\n```ek9\n#!ek9\ndefines module book.generics\n\n  defines program\n    Show()\n      stdout <- Stdout()\n\n      names <- List() of String\n      names += \"Ada\"\n      names += \"Alan\"\n\n      primes <- List() of Integer\n      primes += 2\n      primes += 3\n\n      stdout.println(`names  (List of String):  ${names}`)\n      stdout.println(`primes (List of Integer): ${primes}`)\n\n      scores <- {\"Ada\": 90, \"Alan\": 85}\n      stdout.println(`Ada scored ${scores.getOrDefault(\"Ada\", Integer())}`)\n```\n\n```text\nnames  (List of String):  [\"Ada\", \"Alan\"]\nprimes (List of Integer): [2, 3]\nAda scored 90\n```\n\n`List() of String` makes a new list and fills the gap: the type after `of` takes the place of `T`. Some\ngenerics have more than one gap. A `Dict` needs a type for its keys *and* a type for its values, so it\nis written `Dict of (K, V)`. `scores` above, built from `{\"Ada\": 90, ...}`, is a\n`Dict of (String, Integer)`: string keys, integer values. Read a generic type left to right and it\ntells you exactly what it holds.\n\n## The parameter is a promise\n\nThe type in the gap is a rule the compiler enforces. A `List of String` holds strings and *only*\nstrings. Try to add an integer:\n\n```ek9\n      names <- List() of String\n      names += 42\n```\n\nand it will not build (`wrongElement.ek9`, in the `error-examples` folder):\n\n```text\nEK9     : Error   : E50060: '+=' on line 8 position 12: In relation to type 'List of String', and '+=(Integer)', parameter mismatch. Possible method(s) public Void <- +=(item as String),public Void <- +=(other as List of String): method/function not resolved\n             See: ek9 -h E50060\n           forAI: methodResolution\n```\n\nThis is what makes generics safe as well as convenient. Because you can never *put* an integer into a\n`List of String`, you can never get one *out*. One `List` serves every element type at no cost in\nsafety, because the element type travels with the list and is checked wherever it is used.\n\n## The family you already know\n\nThe generic types EK9 provides are the ones you have been using all along:\n\n- **`List of T`** — an ordered collection of one element type (*Collections*).\n- **`Dict of (K, V)`** — keys of one type, values of another (*Collections*).\n- **`Optional of T`** — either nothing or one `T` (*Optional and Result*).\n- **`Result of (O, E)`** — a success value or an error value (*Optional and Result*).\n- and others, such as **`PriorityQueue of T`**, built the same way.\n\nYou do not always have to write the parameter. A literal `[\"Ada\", \"Alan\"]` is inferred as a\n`List of String`, and `{\"Ada\": 90}` as a `Dict of (String, Integer)`: the compiler reads the parameter\nfrom the contents. When the contents cannot tell it — an empty list, say — you name the type yourself:\n`List() of String`.\n\n## Two ways to \"work for many types\"\n\n*Abstract Types, Subtypes and Polymorphism* gave the first answer to the wish to \"write it once, use it\nfor many types\": one `Shape` variable could hold a `Circle` or a `Rectangle` — many types sharing one\ncontract, the right behaviour chosen when the method is called. That is **subtype** polymorphism.\nGenerics are **parametric** polymorphism: one definition — `List` — that works for *any* type you fill\nit with, with that type carried along and checked. One says \"many types, one contract\"; the other says\n\"one definition, any type\". You will use both constantly.\n\n## Try it yourself\n\n1. Make a `List of Boolean`, add a couple of values, and print it.\n2. Build a `Dict of (String, List of Integer)` — a dictionary whose values are themselves lists — and\n   read one entry. Generics nest.\n3. Add a value of the wrong type to a typed list and read the `E50060` error. It lists the parameter\n   types it *would* have accepted.\n\n## Recap\n\nA **generic** type is a template with a **type parameter**: `List of type T` becomes a `List of String`\nor a `List of Integer` when you fill the gap; `Dict of (K, V)` has two. The parameter is enforced — a\n`List of String` rejects anything that is not a string (`E50060`) — which is what makes the reuse safe.\nYou already know the built-in family — `List`, `Dict`, `Optional`, `Result` and others — and the\ninference that often fills the parameter for you. Generics are **parametric** polymorphism, the\ncompanion to the **subtype** polymorphism of the previous chapters. Defining your own generic types\nwaits for the second volume. Next, *Using Operators*: giving your own types the same operators the\nbuilt-in ones have.\n","examples":["books/getting-started-with-ek9/ch20-generics/Generics.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 21","title":"Using Operators","url":"https://ek9.io/books/getting-started-with-ek9/operators.html","markdown":"# Using Operators\n\nYou have used operators since the first chapter. `+` added numbers, `==` compared them, `$` turned a\nvalue into text, `?` asked whether it was set, `<=>` sorted. Since *Records and Enumerations* you have\ngiven a few to your own types, such as `default operator ?`. This chapter looks at the whole set at\nonce, because the way EK9 handles operators says a good deal about the language.\n\n## A fixed, named set\n\nEK9 has a **fixed catalogue** of operators, each with a name and a settled meaning. You may give most\nof them to your *own* types (the comparisons are the exception: the compiler generates them, as you\nwill see), but you cannot invent a new symbol.\n\nThe closed set is deliberate. Because `+` always means add and `<` always means \"comes before\" —\neverywhere, in everyone's code — any operator you meet is one you already understand. There is no\nprivate set of invented symbols to learn for each library; a newcomer can read every operator aloud and\nreason about it. That keeps code readable, including the code you write today and read again next\nyear.[^inventops] Here is the catalogue, grouped by job (*The Operator Reference* appendix lists every\none):\n\n- **Comparing:** the comparator `<=>` (which returns \"less, equal or greater\" as one number), and\n  `<~>` (a fuzzy, how-similar comparison). From a type's `<=>` the compiler *generates* `<`  `<=`  `>`\n  `>=`  `==`  `<>`; a type that can say \"the same\" but not \"comes before\" gives `==` instead, and gets\n  `<>` from it. You never write the generated ones yourself.\n- **Arithmetic:** `+`  `-`  `*`  `/`  `^` (power)  `mod`  `rem`  `++`  `--`  and `abs`, `sqrt`, and\n  a `-` in front of a value to negate it (`-n`).\n- **Turning into something:** `$` (to text), `$$` (to JSON), `#^` (promote, from\n  *Collections*), `#?` (a **hash code**: a whole number worked out from the value, which collections\n  such as `Dict` use to find values quickly; equal values must give equal hash codes).\n- **Asking about state:** `?` (is it set?), `empty`, `length`, `contains`, `matches`.\n- **Copying and merging:** `:=:` (copy), `:~:` (merge), `:^:` (replace).\n- **Logic and the rest:** `and`, `or`, `xor`, `not` (which can also be written `~`), the stream pipe\n  `|`, and a few more.\n\nYou have met most of these already. Gathered together, they make the point: a small vocabulary, each\nsymbol chosen because it already means something to most programmers, and closed so that it stays that\nway.\n\n## Giving your own type operators\n\nYou add an operator to your type with the word `operator`, as you have seen for `?`. Some you ask the\ncompiler to generate — `default operator <=>` — and some you write yourself. Here a small\ntwo-dimensional vector gets its own `+` (add two vectors) and `$` (how it prints), and `default`\noperators for comparison and the set check:\n\n```ek9\n#!ek9\ndefines module book.vectors\n\n  defines record\n    Vec2\n      x as Integer: Integer()\n      y as Integer: Integer()\n\n      Vec2() as pure\n        ->\n          initialX as Integer\n          initialY as Integer\n\n        x :=? Integer(initialX)\n        y :=? Integer(initialY)\n\n      operator + as pure\n        -> other as Vec2\n        <- rtn as Vec2?\n        require other?\n        rtn: Vec2(x + other.x, y + other.y)\n\n      operator $ as pure\n        <- rtn as String: `(${x}, ${y})`\n\n      default operator <=>\n      default operator ?\n\n  defines program\n    Show()\n      stdout <- Stdout()\n      a <- Vec2(1, 2)\n      b <- Vec2(3, 4)\n      twin <- Vec2(1, 2)\n      stdout.println(`${a} + ${b} = ${a + b}`)\n      stdout.println(`a == twin?  ${a == twin}`)\n      stdout.println(`a == b?     ${a == b}`)\n```\n\n```text\n(1, 2) + (3, 4) = (4, 6)\na == twin?  true\na == b?     false\n```\n\n`operator +` reads like a small method: it takes another `Vec2` and returns a new one with the\ncomponents added, so `a + b` works on your type as `+` works on an `Integer`. The `default` operators\nare the compiler writing the obvious version: `<=>` compares the fields, `?` reports whether the record\nis set. `a == twin` works although you never mentioned `==`: `<=>` is how `Vec2` says what \"the same\"\nmeans, and the compiler *generates* `==`, `<>`, `<`, `<=`, `>` and `>=` from it. You never write or\nrequest those yourself (`E07181` if you try), so they cannot drift out of step with `<=>`.\n\nThe `require other?` line states a precondition inside the operator: adding a vector only makes sense\nif there *is* a vector to add, so `other` must be set. A record built from unset parts is itself unset\n— `Vec2(Integer(), Integer())`, with no real numbers in it, answers `?` with `false` — so\n`require other?` catches it. Pass a set vector and the operator proceeds; pass an unset one and the\nprogram stops at once, naming the failed requirement (it prints ``Requirement failed: `other?` ``,\nwith the file, line and column) rather than computing a meaningless result. The precondition comes\nfirst in the body, so it runs before any adding.\n\n## Write what is special, default the rest\n\nNaming each operator — `default operator <=>`, `default operator ?`, and so on — works, but listing half\na dozen is tedious, and it is not what EK9 programmers write. Write **`default operator`** with no\nsymbol after it, and the compiler generates *every* operator it can work out for itself, and never\nreplaces an operator you wrote by hand. So a well-made type follows one rule: **write the one or two\noperators that carry your own judgement, and let `default operator` fill in the rest.**\n\nHere a `Release` record does exactly that. Only `$` is written by hand, because \"1.5\" is our own choice\nof how a version should read:\n\n```ek9\n#!ek9\ndefines module book.versions\n\n  defines record\n    Release\n      major as Integer: Integer()\n      minor as Integer: Integer()\n\n      Release() as pure\n        ->\n          initialMajor as Integer\n          initialMinor as Integer\n\n        major :=? Integer(initialMajor)\n        minor :=? Integer(initialMinor)\n\n      //Written by hand, because \"1.5\" is our own idea of how a Release reads\n      operator $ as pure\n        <- rtn as String: `${major}.${minor}`\n\n      //And the compiler fills in every other operator it can work out for itself\n      default operator\n\n  defines program\n    Show()\n      stdout <- Stdout()\n\n      versions <- List() of Release\n      versions += Release(2, 0)\n      versions += Release(1, 5)\n      versions += Release(2, 3)\n\n      sorted <- cat versions | sort | collect as List of Release\n      for v in sorted\n        stdout.println(`sorted: ${v}`)\n\n      a <- Release(1, 5)\n      b <- Release(2, 0)\n      stdout.println(`a < b?   ${a < b}`)\n      stdout.println(`a > b?   ${a > b}`)\n      stdout.println(`as text: ${a}`)\n      stdout.println(`as JSON: ${$$a}`)\n```\n\n```text\nsorted: 1.5\nsorted: 2.0\nsorted: 2.3\na < b?   true\na > b?   false\nas text: 1.5\nas JSON: {\"major\":1,\"minor\":5}\n```\n\n`default operator` gave `Release` the comparator `<=>`, which answers *how* two values relate as one\nnumber (negative, zero or positive), and the comparisons generated from it, `<`, `>`, `==` and the\nrest. `<=>` is what lets `sort` put a `List of Release` in order — `1.5`, `2.0`, `2.3` — with no\nsorting code from you. It also gave the set check `?`, a hash, and the JSON form `$$`. The one\noperator the compiler did *not* touch is the `$` you wrote, which is why the text form is `1.5`.\n\nThat is the division of work `default` is for. The compiler is good at the mechanical operators —\ncompare the fields, hash the fields, turn the fields into JSON — and does them for you. It cannot\nguess the ones that carry a judgement, such as how a version number should *look*. You write those.\n\n## When you write the sameness yourself\n\n`default operator` hashes every field, because the sameness it generates compares every field. Sometimes\nsameness is narrower. Two tickets are for the same seat when the row and the number match, whoever holds\nthem. Write that `==` by hand, and EK9 requires a hand-written `#?` as well (`E07184`): equal values must\ngive equal hash codes, or a `Dict` keyed by seat would look for the resold ticket under the wrong hash code\nand not find it.\n\nYou build that hash code with a **`Hasher`**, a built-in type that takes values one at a time, in order,\nand works out one hash code from all of them. `Hasher()` starts with nothing added, `+` gives a new\n`Hasher` with one more value, and `#?` gives the hash code:\n\n```ek9\n#!ek9\ndefines module book.seats\n\n  defines record\n    Seat\n      row as Character: Character()\n      number as Integer: Integer()\n      holder as String: String()\n\n      Seat() as pure\n        ->\n          initialRow as Character\n          initialNumber as Integer\n          initialHolder as String\n\n        row :=? Character(initialRow)\n        number :=? Integer(initialNumber)\n        holder :=? String(initialHolder)\n\n      //Two tickets are for the same seat when the row and number match - whoever holds them\n      operator == as pure\n        -> other as Seat\n        <- rtn as Boolean: row == other.row and number == other.number\n\n      //So the hash code is worked out from the same two fields, and nothing else\n      operator #? as pure\n        <- rtn as Integer: #?(Hasher() + row + number)\n\n      default operator\n\n  defines program\n    Tickets()\n      stdout <- Stdout()\n\n      first <- Seat('F', 12, \"Ada\")\n      resold <- Seat('F', 12, \"Grace\")\n      nextDoor <- Seat('F', 13, \"Ada\")\n\n      stdout.println(`resold ticket, same seat: ${first == resold}`)\n      stdout.println(`resold ticket, same hash: ${#?first == #?resold}`)\n      stdout.println(`next seat, same seat:     ${first == nextDoor}`)\n      stdout.println(`next seat, same hash:     ${#?first == #?nextDoor}`)\n```\n\n```text\nresold ticket, same seat: true\nresold ticket, same hash: true\nnext seat, same seat:     false\nnext seat, same hash:     false\n```\n\nThe `#?` adds exactly the fields the `==` compares, `row` and `number` and not `holder`, so the resold\nticket has the same hash code as the first. The next seat differs in its number, so it is a different seat\nwith a different hash code. (Equal values always give equal hash codes; different values almost always\ngive different ones.) Order counts: `row` then `number` gives a different hash code from `number` then\n`row`. And if any value added is unset, the `Hasher` is unset, and so is the hash code, which agrees with\nthe record's own `?`.\n\n## Turning a value into text, and into JSON\n\nTwo conversions come up constantly, so each has its own operator. `$` produces a **text** form — what\nyou want when you print a value or put it in a `` `...` `` string. `$$` produces a **JSON** form — what\nyou want when a value leaves the program, for a file or a network. On `Release`, `$` was written by\nhand (`1.5`, the \"major.minor\" a person expects), while `$$` came from `default operator`, built from\nthe fields:\n\n```text\n{\"major\":1,\"minor\":5}\n```\n\nA value's *human* form is a presentation choice — `1.5`, or `£1.50`, or a date in the local style — so\n`$` is usually yours to write. Its *machine* form follows from its structure, so the default `$$` is\nnormally right. Two conversions, two operators, so there is never any doubt about which form you get.\n\n## Promotion: one more look at `#^`\n\nIn *Collections* an `Integer` became a `Float` wherever a `Float` was wanted — `5` became `5.0` —\nthrough an operator, `#^` (promote). Your own types can define it too. When EK9 finds a value of one type\nwhere another is wanted, it looks for a single `#^` that converts it, and calls it. Here a `Celsius`\npromotes itself to a Fahrenheit `Float`:\n\n```ek9\n#!ek9\ndefines module book.temperature\n\n  defines record\n    Celsius\n      degrees as Float: Float()\n\n      Celsius() as pure\n        -> initialDegrees as Float\n        degrees :=? Float(initialDegrees)\n\n      operator $ as pure\n        <- rtn as String: `${degrees}C`\n\n      operator #^ as pure\n        <- rtn as Float: (degrees * 9.0 / 5.0) + 32.0\n\n      default operator ?\n\n  defines program\n    Show()\n      stdout <- Stdout()\n\n      boiling <- Celsius(100.0)\n      fahrenheit as Float: boiling\n      stdout.println(`${boiling} is ${fahrenheit}F`)\n\n      count <- 7\n      asFloat as Float: count\n      stdout.println(`${count} promoted to ${asFloat}`)\n```\n\n```text\n100.0C is 212.0F\n7 promoted to 7.0\n```\n\n`fahrenheit as Float: boiling` needs a `Float`, but `boiling` is a `Celsius`. EK9 finds `Celsius`'s\n`#^`, calls it, and gets `212.0` — the same mechanism that turns `7` into `7.0` a few lines later.\nPromotion goes **one step only**: EK9 uses a single `#^` to convert between two types, and never chains\npromotions together looking for a route, so conversions stay short and predictable.[^promote] Like the\nfixed operator set, it is open to your own types but bounded.\n\n## Keep the meaning\n\nThe fixed set solves half the readability problem. The other half is yours: **an operator you define\nmust keep the meaning of its symbol.** `+` should combine, not send an email; `<` should order; `$`\nshould produce a faithful text form. It is tempting to give an operator a clever, surprising meaning,\nbut once `+` means something a reader would not guess, your code has become a puzzle.[^operatorsem]\nKeeping the meaning pays off: because `Vec2` adds with `+` and compares with `<`, it works with\neverything built on those operators — sorting, arithmetic, the collection type inference from\n*Collections* — with no special cases.\n\nThe compiler helps. `a == a` — comparing a value with itself — does not compile (`E08081`): the answer\nis known in advance, so it is almost certainly a slip. That is one case of a wider check: EK9 detects\n**tautologies** — tests that are *always* true — and **contradictions** — tests that are *always*\nfalse — from the obvious, like `x or not x`, to ones it works out by following how your data reached\nthe test. No compiler can catch *every* always-true expression; that is impossible in general. EK9\nreports the ones it can *prove*, turning a family of quiet logic bugs (\"this `if` can never run\",\n\"this check always passes\") into compile errors while they are cheap to fix.\n\nOne more check belongs here. A **computational** operator — `+`, `<`, `$`, `contains` — exists to\n*produce a value*, so throwing the value away is dead code: call one as a statement and ignore what it\nreturns (`a.+(b)` on its own line, say) and EK9 stops you (`E11050`). It is the same \"nothing unchecked,\nnothing discarded\" rule you met for `Result` and `Optional`. **Mutating** operators are the exception:\n`+=`, `++` and `:~:` exist for the *change* they make, return nothing, and stand on their own.\n\n## The deeper half is in the second volume\n\nThere is more to operators than using them. An operator can be *mutating* (like `++`, which changes its\nvalue in place) or *non-mutating* (like `+`, which computes a new value and leaves its inputs alone),\nand EK9 has an exact, enforced model of which is which and how that interacts with `pure`. That is the\nsubject of the operators chapter of the second volume. For everyday types, what you have here is enough:\nuse `default` where the obvious version will do, write your own where it will not, and keep every\nsymbol's meaning.\n\n## Recap\n\nEK9 has a **fixed, named catalogue** of operators and does not let you invent new ones, so the\nvocabulary stays small, shared and readable. You give your own type an operator with **`operator`**:\n`operator +` with a body to write your own, or `default operator <=>` to have the compiler generate the\nobvious version. The bare **`default operator`** generates *every* operator it can work out and leaves\nyour hand-written ones alone — **write what carries your judgement, and default the rest**. That gives\ncomparison and sorting (through `<=>`), a text form (`$`) and a JSON form (`$$`), the set check `?` and\na hash; and `#^` lets your type promote itself as `Integer` promotes to `Float`, one step and no casts.\nKeep **each symbol's established meaning**, so a type with `+` and `<` works with everything built on\nthem. The compiler enforces the clear-cut cases: `==`, `<` and the rest are always generated from the\ntype's one sameness operator, `<=>` or `==`, and never written; a value cannot be compared with itself;\na computed result cannot be thrown away. A hand-written sameness needs a hand-written `#?` over the same\nfields, built with a **`Hasher`**: `#?(Hasher() + row + number)`. The mutating and non-mutating model, and how operators work\nwith purity, wait for the second volume. Next, *Programs, Input and Output*: where a program meets the\noutside world.\n\n[^inventops]: Languages differ in how far they open this door. C++ lets you overload its own fixed set\nof operators but not invent new ones; others — Haskell and Scala among them — let you define entirely\nnew operator symbols (`>>=`, `|@|`, and the like). That is a powerful facility, and in careful hands it\nreads well; its cost is that the same symbol can mean different things in different libraries, which\nasks more of a reader. Some later languages — Java and Go — left operator overloading out altogether.\nEK9 takes a middle path: the operators are yours to define on your own types, but the *set* is fixed\nand each symbol's meaning is settled.\n\n[^operatorsem]: The EK9 language documentation puts the guidance directly: \"It is very easy to become\nseduced by operators, to override and twist them into contrived meanings. When overriding an operator it\nis really worth taking the time to ensure it retains its semantics and consistency.\"\n\n[^promote]: The one-step rule is a deliberate contrast with languages where several unwritten\nconversions can combine in one place. In C++, for instance, an implicit conversion sequence may combine\na standard conversion with a user-defined one — which is powerful but can make it hard to see why a\ngiven expression type-checks. EK9 allows exactly one `#^` step and no more, so a promotion is always a\nsingle, findable step. It is also why there is no cast syntax at all: every conversion is an operator,\neither written out or a single automatic `#^`, and so stays visible in the code.\n","examples":["books/getting-started-with-ek9/ch21-operators/Celsius.ek9","books/getting-started-with-ek9/ch21-operators/Seats.ek9","books/getting-started-with-ek9/ch21-operators/Vectors.ek9","books/getting-started-with-ek9/ch21-operators/Versions.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 22","title":"Programs, Input and Output","url":"https://ek9.io/books/getting-started-with-ek9/programs.html","markdown":"# Programs, Input and Output\n\nMost programs in this book have taken a value or two, worked something out and printed the answer.\nA real program also deals with the outside world: it reads what you type on the command line, keeps\nthings in files that last beyond a single run, and writes back to your screen. This chapter is about\nthat boundary, between your typed code and a world that is not.\n\nEverything that arrives from outside starts as plain text: a word you typed, a line in a file, an\noption you may or may not have given. It might be missing, or the wrong shape. The boundary is where\nyou check, and EK9 makes sure you do.\n\nWe will build a small **notes-keeper**: a program called `Notes` that keeps lines of text in a file.\nAdd a note today, and it is still there tomorrow.\n\n## Giving a program its instructions\n\nIn *Making Decisions and Repeating Work* a program took a single typed value:\n\n```ek9\n    Weather()\n      -> temperature as Integer\n```\n\nand you ran it with `ek9 Weather.ek9 12`. That is the simplest way in: one value, named and typed,\nhanded over as the program starts.\n\nReal tools usually want more, and want it to be *optional*. Should the program report what it is\ndoing? Which file should it use? Is there a note to add this time, or are we just looking? These are\n**options** — short flags like `-v`, `-f`, `-a` — and they may appear in any order, or not at all. For\nthat, a program takes the whole command line as a list:\n\n```ek9\n    Notes()\n      -> argv as List of String\n```\n\n`argv` is every word after the program name, in order, as `String`s. The name is short for *argument\nvector*: \"argument\" for each value you give the program as it starts, and \"vector\", an old word for a\nlist. It comes from the C language and Unix and has been passed down ever since.[^argv] You could call\nthe parameter `arguments` or `commandLine`, but `argv` is the name most programmers recognise, so we\nuse it too.\n\nYou *could* pick through that list yourself, but options are fiddly — some are on/off, some carry a\nvalue, they come in any order — so EK9 provides a tool for it.\n\n## Reading options with `GetOpt`\n\n`GetOpt` takes a short description of the options you accept and returns what was given. Here is how\n`Notes` sets it up:\n\n```ek9\n      usage <- \"Usage: Notes [-v] [-f file] [-a note]\"\n      supported <- {\n        \"-v\": String(),\n        \"-f\": \":\",\n        \"-a\": \":\"\n      }\n      options <- GetOpt(\":\", supported, usage).options(argv)\n```\n\nThe `supported` dictionary says which options exist and what each expects. `\"-v\": String()` is an\non/off flag: it carries no value. `\"-f\": \":\"` and `\"-a\": \":\"` are options that *take* a value; the\n`\":\"` marks them. The `usage` line is the message shown if someone passes something wrong.\n`options(argv)` reads the actual command line against that description and returns a `Dict` mapping\neach option that appeared to its value.\n\nYou read the answer with the `Dict` methods from *Collections*:\n\n```ek9\n      verbose <- options contains \"-v\"\n      filename <- options.getOrDefault(\"-f\", \"notes.txt\")\n```\n\n`contains` asks whether a flag was present — right for an on/off option like `-v`. `getOrDefault`\nreads a value, with a fallback for when the option was left out: no `-f`, and we use `notes.txt`.\n\nThe choice of fallback matters, and it is the three states at work. When we come to the note itself:\n\n```ek9\n      newNote <- options.getOrDefault(\"-a\", String())\n      if newNote?\n        notes += newNote\n        writeNotes(file, notes)\n```\n\nthe fallback is `String()` — an **unset** String — not `\"\"`. An empty string `\"\"` is *set*: it would\npass the `if newNote?` check, and we would add a blank note. `String()` is unset — it means \"no `-a`\nwas given\" — so the check is false and nothing is added. The right fallback is what lets the program\ntell \"an empty note\" apart from \"no note at all\". Choose the wrong one and the bug is silent.\n\n## Two ways out: `Stdout` and `Stderr`\n\nA program has more than one output channel; use each for its purpose:\n\n```ek9\n      stdout <- Stdout()\n      stderr <- Stderr()\n```\n\n`Stdout` — *standard output* — is for the program's result: here, the list of notes. `Stderr` —\n*standard error* — is for everything else: progress messages, warnings, and things that went wrong.\nKeeping them apart is an old and useful convention.[^streams] It means someone can capture just the\n*notes* — save them to another file, or feed them to another program — without the message\n\"using notes.txt\" mixed in. So `Notes` sends the notes to `stdout` and its other messages to `stderr`:\n\n```ek9\n      if verbose\n        stderr.println(`using ${filename}`)\n```\n\n(Reading input as you type it, from *standard input*, is what the game in the next chapter does. Here,\neverything the program needs arrives on the command line and in the file.)\n\n## A path is just a path\n\nNow the file. A `FileSystemPath` is *only a path*: a name for a place on disk. It does not open or\nread anything, or decide what *kind* of file is there. It is an address.\n\n```ek9\n      path <- FileSystemPath().inCurrentWorkingDirectory(filename)\n```\n\n`inCurrentWorkingDirectory` attaches our `filename` to the directory the program is running in, so\n`notes.txt` becomes a full path in the right place. (Give it a name that is *already* a full path and\nit comes back unchanged.)\n\n## Making the file — and being made to check\n\nCreating a file can fail. The disk might be full, or the directory might not be writable. So the\nmethod that creates a file does not return a plain yes or no that you could ignore; it returns a\n**`Result`** — the type from *Optional and Result* that holds either success or an error message — and\nthe compiler will not let you ignore it:\n\n```ek9\n      //Create the file only if it is not there yet; an existing one is left alone.\n      //createFileIfAbsent() hands back a Result the compiler will not let us ignore.\n      outcome <- path.createFileIfAbsent()\n      if outcome.isError()\n        stderr.println(`cannot create ${filename}: ${outcome.error()}`)\n```\n\nThis is the safe-access rule from *Optional and Result*. We may read `outcome.error()` only *inside* a\nblock that has checked `outcome.isError()`, and if we never checked at all, the program would not\ncompile. A step that can fail, at the edge of the program, is where that rule matters most.\n\n`FileSystemPath` has two ways to create a file, and the choice matters. `createFileIfAbsent()` means\n\"make it, or keep the one that is there\": a new file and an existing one are both success, and only a\nreal failure is an error. That is what `Notes` wants — on the second run, yesterday's notes must be\nread, not replaced. `createFile()` is the strict one: it means **create a new file**, and if one is\nalready there, even an empty one, it reports an error. Use it when an existing file would mean\nsomething has gone wrong — when a program that believes it is making a fresh file must not quietly\nuse, or later overwrite, one that was there before.\n\nAfter the attempt, the program carries on only if the file really exists now:\n\n```ek9\n      if path.exists()\n        if verbose\n          stderr.println(`using ${filename}`)\n```\n\nIf creating it failed, the file is not there, so the work is skipped: no crash, no half-written file,\njust a message on `stderr` and a quiet stop.\n\n## Reading and writing the notes\n\nOnly now, with a path to a file that exists, do we *open* it, and that is `TextFile`'s job, not the\npath's. A `TextFile` is made *from* a path:\n\n```ek9\n        file <- TextFile(path)\n```\n\nReading and writing both happen inside a `try`. Here is the read:\n\n```ek9\n    readNotes()\n      -> file as TextFile\n      <- rtn as List of String: List() of String\n      try\n        -> input <- file.input()\n        while input.hasNext()\n          line <- input.next()\n          if line?\n            rtn += line\n```\n\nThe first line inside the `try` is `-> input <- file.input()`. The `->` is the same \"this comes in\"\narrow as on every function: the `try` is *given* a resource — the reader that `file.input()` opens —\nand names it `input` for the length of the block. `hasNext()` and `next()` then walk through it line\nby line, like the iterators you have used before. Each line is checked with `if line?` before it joins\nthe list. For an ordinary file every line is set, so every line goes in; but reading text can also\ngive an *unset* line (one rejected by the reader's **sanitisation**, its check on incoming text for\ncontent that could be harmful), and the check skips it rather than putting a gap in the list.\n\nWhy give the reader to the `try`, rather than open it into an ordinary variable? Because of what\nhappens at the *end*. An open file uses a resource: the operating system gives your program a **file\ndescriptor** — a small numbered handle on the open file — and it has only so many to give. Open files\nand never close them, and the handles run out. That is a **resource leak**: invisible in a quick test,\nand fatal in a long-running program that eventually cannot open anything more. In many languages the\ncure is to call `close()` on every file when you are done — easy to forget, especially on the path\nwhere something has already gone wrong.\n\nEK9 takes the close out of your hands. Because `input` was given to the `try`, the `try` *owns* it,\nand closes it when the block ends — whether it ended normally or because something failed partway\nthrough. You do not write the close, and you cannot: writing `input.close()` is a compile error\n(`E81060`), because EK9 generates every close itself. There is nothing to forget, so the leak cannot\nhappen.[^resources]\n\nWriting is the mirror image, with one more thing to know:\n\n```ek9\n    writeNotes()\n      ->\n        file as TextFile\n        notes as List of String\n\n      try\n        -> output <- file.output()\n        for note in notes\n          output.println(note)\n```\n\nOpening a file for **output starts it afresh**; it does not add to the end. So \"adding a note\" is not\n\"write one more line\": it is read the whole list, add to it in memory, and write the whole list back.\nThat is why `Notes` reads first and writes the complete list every time. It is a good example of\nchecking what an operation at the boundary actually does, rather than assuming.\n\n## Running it\n\nPut together, the program adds notes, and they stay. Each command below is a separate run in the same\ndirectory.\n\n```console\n$ ek9 Notes.ek9 -a milk\nnotes (1):\n  milk\n\n$ ek9 Notes.ek9 -a bread\nnotes (2):\n  milk\n  bread\n\n$ ek9 Notes.ek9\nnotes (2):\n  milk\n  bread\n```\n\nThe first run creates `notes.txt` and adds `milk`. The second finds the file already there — which\n`createFileIfAbsent()` treats as success — reads `milk` back, adds `bread`, and writes both. The third\nadds nothing (`-a` was left out, so the note was unset) and lists what is stored. With `-v`, the\nprogress message goes to standard error, separate from the notes:\n\n```console\n$ ek9 Notes.ek9 -v -a eggs\nnotes (3):\n  milk\n  bread\n  eggs\n```\n\nwith `using notes.txt` printed separately, on `stderr`.\n\n## Running it as its own command\n\nOne more thing explains a line at the top of every example in this book:\n\n```text\n#!ek9\n```\n\nThat first line is a **shebang**. On macOS and Linux it tells the system \"to run this file, hand it to\n`ek9`.\" So far we have run programs by naming the tool first, `ek9 Notes.ek9`. You can also run the\nfile on its own. Mark it executable, once:\n\n```console\nchmod u+x Notes.ek9\n```\n\n`chmod` changes a file's permissions; `u+x` reads as \"user: add execute\", so you may now *run* this\nfile, not only read it. From then on you run it directly, like any other command:\n\n```console\n./Notes.ek9 -a bread\n```\n\nThere is no `ek9` in front: the shebang points the system at `ek9` for you. The leading `./` means\n\"the file here, in this directory\". A note with spaces in it works too; put it in quotes so the shell\nkeeps it as one piece:\n\n```console\n./Notes.ek9 -a \"buy fresh milk\"\n```\n\nThe result is the same as running it the other way; only the typing is shorter. The shebang is a Unix\nconvention, so macOS and Linux honour it and Windows does not — there you keep typing\n`ek9 Notes.ek9`. Either way, `Notes` is now a command you made.\n\n## A setting from the environment: a web address\n\nSome values belong to the place a program runs, not to the program itself. The address of a server is\nthe usual example. Suppose the notes later live on a web server as well: its address is different on\nyour own computer, on a test machine and on the real service, and it changes years after the code was\nwritten. A setting like that is kept in an **environment variable**, as the language was in *Speaking\nEvery Language*.\n\nFor a web address EK9 goes further than for a language: you cannot write one into your code at all. A\nweb address, a **URL**, comes from the environment, through `Networking`:\n\n```ek9\n#!ek9\ndefines module book.notelink\n\n  defines program\n    NoteLink()\n      -> noteNumber as Integer\n      stdout <- Stdout()\n\n      server <- Networking().urlFromEnv(\"NOTES_SERVER\")\n      if server?\n        link <- server.withPath(\"/notes\").withPathSegment($noteNumber)\n        stdout.println($link)\n      else\n        stdout.println(\"NOTES_SERVER is not set to a web address\")\n```\n\n`Networking().urlFromEnv(\"NOTES_SERVER\")` reads the variable `NOTES_SERVER` and checks that it holds a\nreal web address, starting `http://` or `https://`. If the variable is missing, or holds something\nthat is not a web address, the result is **unset**, and `if server?` asks the usual question: has\nsomething been put in the box?\n\n`withPath(\"/notes\")` and `withPathSegment($noteNumber)` build a new address from the one that came in.\nThey keep its server, so values in the program can change *where on the server* a link points, never\n*which server*. `withPathSegment` also encodes its text, so a `/` or a space in it cannot change the\nshape of the address. `$noteNumber` turns the number into text, as in *Text, Numbers, Time and Money*.\n\nOn macOS and Linux you set the variable for one run by writing it in front of the command:\n\n```console\n$ NOTES_SERVER=https://notes.example.com ek9 NoteLink.ek9 7\nhttps://notes.example.com/notes/7\n\n$ NOTES_SERVER=HTTPS://Notes.Example.COM:443 ek9 NoteLink.ek9 7\nhttps://notes.example.com/notes/7\n\n$ ek9 NoteLink.ek9 7\nNOTES_SERVER is not set to a web address\n```\n\nThe second spelling, in capitals and with the standard secure port `443` written out, is the same\naddress, so EK9 writes it the same way. In Windows PowerShell, set the variable first with\n`$env:NOTES_SERVER = \"https://notes.example.com\"`, then run `ek9 NoteLink.ek9 7`.\n\nTry writing the address into the program instead:\n\n```ek9\n      server <- Networking().urlOf(\"https://notes.example.com\")\n```\n\n```text\nEK9     : Error   : E08275: 'urlOf' on line 9 position 29: '\"https://notes.example.com\"': the text given to 'Networking().urlOf()' is known when the program is compiled - an endpoint in the source is configuration hard-coded: read it with 'Networking().urlFromEnv(name)', and derive other URLs from it with 'withPath', 'withPathSegment', 'withQueryParam' or 'resolve'; 'urlOf' is for URL text that arrives while the program runs\n             See: ek9 -h E08275\n```\n\n`urlOf` exists for an address that *arrives while the program runs*: one a person types into a form,\nor one inside a message from another program. Text the compiler can see when it compiles is refused,\nwhether it is written in place, kept in a constant or copied into a variable first. There are two\nreasons. The people who run a program need to change its addresses without changing its code. And an\naddress buried in code is hidden from anyone checking what the program connects to; a setting outside\nthe code is in plain view.[^config]\n\n## Try it yourself\n\n1. Add a `-c` option that clears the list: when it is given, replace `notes` with an empty list and\n   write it out before any new note is added. Add `-c` to the usage text as well.\n2. Keep two lists with `-f`: add notes to `shopping.txt` and to `todo.txt`, and check that each run\n   shows only its own file's notes.\n3. With `-v`, also report on `stderr` how many notes were read. Run it with `2> /dev/null` on macOS or\n   Linux and see that the notes still appear while the progress messages do not.\n4. Give `NoteLink` a second argument, a word to search for, and add it to the link with\n   `withQueryParam(\"search\", word)`. Run it with a word containing a space and see how it is written.\n\n## Recap\n\nThis chapter dealt with the edge of a program, where it meets the outside world. A program takes the\ncommand line as **`argv`**, and **`GetOpt`** turns a short description of your options into a `Dict`\nyou read with `contains` (was the flag there?) and `getOrDefault` (what value, or what fallback?). The\nfallback should be the *truthful* one: `String()`, not `\"\"`. There are two output channels:\n**`Stdout`** for results and **`Stderr`** for everything else. A file comes in layers, each doing one\njob: a **`FileSystemPath`** is only an address; **`createFileIfAbsent()`** and **`createFile()`**\nreturn a **`Result`** the compiler makes you check, the strict `createFile()` refusing a file that is\nalready there; and a **`TextFile`**, made from the path, reads and writes — inside a `try` that closes\nit for you, so you never write a close yourself. A web address is a setting, not code: **`Networking().urlFromEnv`** reads a **URL** from\nan environment variable, unset if it is missing or not a web address, and `withPath` and `withPathSegment` build\nnew addresses on the same server; writing an address into the code is a compile error. The thread through all of\nit: at the boundary, input is untrusted and operations can fail, and that is exactly where EK9 makes you look.\n\nNext, all of this — options, output and everything else in this book — goes into a program you would\nwant to run: a game.\n\n[^argv]: In C, a program begins at `int main(int argc, char *argv[])`: `argc` is the *argument count*\nand `argv` the *argument vector* — the list of arguments. The pair has been handed down, names and\nall, through language after language for half a century. A name everyone already recognises is often\nworth more than a cleverer one nobody does.\n\n[^config]: Keeping the settings that differ from one installation to the next in environment variables,\nnot in the code, is the third rule of *The Twelve-Factor App* (Adam Wiggins, 2011), a widely used guide to\nbuilding services. EK9 makes it the only way for a web address.\n\n[^resources]: Tying a resource's lifetime to a block, so it is released when the block ends, is a\nwell-established idea. C++ calls it RAII (*resource acquisition is initialisation*); Java has\n*try-with-resources*; Python has the `with` statement; C# has `using`. Each exists because a\nhand-written `close()` is easily forgotten — most of all on the error paths, which are tested least.\nEK9 builds the same guarantee into its `try`, and goes one step further by not letting you write the\nclose at all.\n\n[^streams]: Splitting a program's output into *standard output* and *standard error* is one of the\noldest conventions in computing, from early Unix. Because results and messages travel on separate\nchannels, you can redirect or pipe the real output somewhere without the running commentary mixed in,\nand still see the commentary on your screen.\n","examples":["books/getting-started-with-ek9/ch22-programs/NoteLink.ek9","books/getting-started-with-ek9/ch22-programs/Notes.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Chapter 23","title":"Build a Game, End to End","url":"https://ek9.io/books/getting-started-with-ek9/game.html","markdown":"# Build a Game, End to End\n\nThis chapter puts the whole of this book into one program you would want to run: a\n**number-guessing game**. The computer picks a number, you try to find it, and after each guess it\ntells you whether to aim higher or lower. When the game ends it prints a high-score table — fewest\nguesses wins.\n\nThe game is not new. Guess-the-number is one of the oldest teaching projects there is, written by\nbeginners in many books and many languages.[^classic] The code is built from what you have already met:\nrecords and classes, collections, functions, operators, `GetOpt`, and a set of tests that ties it\ntogether. The few small additions from the standard library are explained where they appear. The skill\non show is how the pieces fit. Here is a real game, played to the end:\n\n```text\nI am thinking of a number from 1 to 100. You have 7 tries.\n  50: lower\n  25: higher\n  37: higher\n  43: higher\n  46: lower\n  44: correct\nWell done Sam - 6 tries.\nFewest tries wins:\n  Ada (3)\n  Alan (5)\n  Sam (6)\n```\n\nBy the end of the chapter you will have built that, tested the parts that can be tested, and seen\nwhy one part cannot be.\n\n## A plan that fits in your head\n\nYou could write the whole game as one long program: read a guess, compare it, print a hint, loop,\nkeep score, show the table. It would work. But one long program is very hard to test. You cannot ask\n\"is the scoring right?\" without playing a whole game by hand, and you cannot play it by hand a hundred\ntimes to be sure.\n\nSo we do the opposite, and it is one of the most useful habits in this book: **move the decisions out\nof the program and into small, named pieces, each doing one thing you can check on its own.** The\nprogram itself becomes a thin shell — read a line, print a line — and the real decisions live in a\nrecord, a class and a few functions that can be tested thoroughly.\n\nThere is a concrete reason, from *Testing as You Go*: EK9 measures how much of your code the tests\nexercise, and requires a minimum. The more of your logic sits in small testable pieces, the easier\nthat minimum is to reach. Good structure and good testing are the same thing seen from two sides.\n\nThe plan: a `Score` record for one line of the table; a `Game` class for one game in progress; a few\nsmall functions — `hint`, `rank`, and helpers for the board; and a short program that connects them to\nthe keyboard.\n\n## A line on the board: the `Score` record\n\nA score is a name and a number of tries — plain data — so it is a **record**:\n\n```ek9\n    Score\n      who as String: String()\n      attempts as Integer: Integer()\n\n      default Score() as pure\n\n      Score() as pure\n        ->\n          name as String\n          tries as Integer\n\n        who :=? String(name)\n        attempts :=? Integer(tries)\n\n      operator $ as pure\n        <- rtn as String: `${who} (${attempts})`\n\n      operator <=> as pure\n        -> other as Score\n        <- rtn as Integer: attempts <=> other.attempts\n\n      operator #? as pure\n        <- rtn as Integer: #?attempts\n\n      default operator ?\n```\n\nThree operators are written by hand.\n\n- `$` gives a `Score` its text form, `Sam (6)`, so one can go straight into a `` `...` `` string.\n- `<=>` compares on `attempts`, so sorting a list of scores puts the *fewest* tries first. That one\n  operator is what sorts the high-score table later, with no sorting code of our own. Because `<=>` is\n  how a `Score` says what \"the same\" means, two scores with equal tries are *equal*: `Ada (3) ==\n  Bob (3)` is `true`. For a table ordered by tries, that is what \"the same\" should mean.\n- `#?`, the hash code (the number collections use to find a value quickly), goes with `<=>`. A\n  hand-written `<=>` needs a hand-written `#?` that hashes what it compares — here, `attempts` — so the\n  two always agree. The compiler requires the pair (`E07184` if the `#?` is missing).\n\n`default operator ?` supplies the set check every record with fields needs, and `default Score()`\ngives a blank score to fall back on. The constructor copies what it is given — `String(name)`,\n`Integer(tries)` — so a `Score` owns its values.\n\n## One game in progress: the `Game` class\n\nA record holds data; a **class** holds data *and* protects it. A game has state that must stay\nconsistent — the secret number, how many tries are allowed, how many have been used, whether it has\nbeen won — so it is a class, with those fields hidden inside:\n\n```ek9\n    Game\n      secret as Integer: Integer()\n      maxTries as Integer: Integer()\n      tries as Integer: 0\n      solved as Boolean: false\n\n      default private Game() as pure\n\n      Game() as pure\n        ->\n          chosen as Integer\n          allowed as Integer\n\n        secret :=? Integer(chosen)\n        maxTries :=? Integer(allowed)\n\n      //Take one guess. Count it, say which way to go, and note a win.\n      guess()\n        -> number as Integer\n        <- rtn as String: String()\n        tries += 1\n        rtn: hint(secret, number)\n        if number == secret\n          solved := true\n\n      over() as pure\n        <- rtn as Boolean: solved or tries >= maxTries\n\n      triesUsed() as pure\n        <- rtn <- Integer(tries)\n\n      report() as pure\n        -> player as String\n        <- rtn as String: String()\n        rtn: solved <- `Well done ${player} - ${tries} tries.` : `Out of tries - the number was ${secret}.`\n\n      default operator ?\n```\n\nEverything a game *does* is a method. `guess` takes a number, counts the attempt, works out the hint\nand records a win. `over` says whether the game has finished — solved, or out of tries. `triesUsed`\nreports the count, and `report` produces the closing line, using the **ternary** from *Guards and\nSafe Code* (`solved <- winMessage : loseMessage`) to choose one of two sentences.\n\n`default private Game()` is the *blank* constructor — a `Game` with no secret and no limit — and\nmaking it **private** means no code outside the class can build a half-made game.[^seal] A game with\nnothing to guess is not a game, so the only way to make one is `Game(secret, tries)`. `Score` made the\n*opposite* choice and left its blank constructor public, because a blank score is a useful \"nothing\nyet\": the tests use `Score()` as the fallback when they read the top of a ranked board. Same tool,\nopposite choice, each following what the type means.\n\nThe class also copies at both doors. On the way *in*, the constructor stores `Integer(chosen)`, not\n`chosen`. On the way *out*, `triesUsed` returns `Integer(tries)`, not the field. As *Classes*\nexplained, an `Integer` is held by reference, so holding — or handing out — another piece of code's\nobject would let that code change the game's secret or its count from outside. With the copies and the\nprivate blank constructor, the class has full control of its state: you cannot make a game without a\nsecret, and you cannot change one it already has.\n\nAll this is in a class because a class can be *tested*. A real game needs a random secret; to **test**\none, we build a `Game` with a secret we already know, and play it:\n\n```ek9\n    @Test\n    WinningGame()\n      game <- Game(42, 7)\n      assert game.guess(50) == \"lower\"\n      assert not game.over()\n      assert game.guess(42) == \"correct\"\n      assert game.over()\n      assert game.triesUsed() == 2\n      assert game.report(\"Sam\") == \"Well done Sam - 2 tries.\"\n```\n\nThat is a whole game, played in a test, with a secret of `42`. Guess `50` and it says `lower`; the\ngame is not over. Guess `42` and it says `correct`; now it is over, in two tries, and the report reads\nas it should. A losing game is as easy to check — run a `Game` out of tries and confirm it admits\ndefeat and names the number:\n\n```ek9\n    @Test\n    LosingGame()\n      game <- Game(30, 3)\n      assert game.guess(10)?\n      assert game.guess(90)?\n      assert game.guess(25)?\n      assert game.over()\n      assert game.report(\"Sam\") == \"Out of tries - the number was 30.\"\n```\n\nBetween them, these two tests exercise every branch in `Game`: the win, the loss, the counting, and\nboth halves of `report`. That is the benefit of keeping the game's logic in a class rather than in the\nprogram.\n\n> **Note.** Writing the first test exposed a real bug. If `tries` starts *unset* rather than at `0`,\n> then `tries += 1` never produces a number, `over()` can never be `true`, and the game would loop\n> forever. The test failed at the first `over()` check and pointed straight at the fix: declare the\n> field as `tries as Integer: 0`.\n\n## The small helpers\n\nThe rest of the logic is a few plain functions. `hint` is the heart of the game, and it is `pure` —\nthe same guess always gives the same word:\n\n```ek9\n    hint() as pure\n      ->\n        secret as Integer\n        guess as Integer\n      <- rtn as String: String()\n\n      order <- guess <=> secret\n      rtn: order < 0 <- \"higher\" : order > 0 <- \"lower\" : \"correct\"\n```\n\nIt compares the guess with the secret using `<=>`, which gives a negative number, zero or a positive\nnumber. The last line is two ternaries in a row: the value after the first `:` is itself a ternary.\nRead it left to right: if `order < 0` the answer is `higher`; otherwise, if `order > 0` it is `lower`;\notherwise it is `correct`. Because it is a small pure function, one line tests each\ncase:\n\n```ek9\n    @Test\n    HigherTest()\n      assert hint(50, 20) == \"higher\"\n```\n\n`rank` puts a board in order. It is one stream pipeline. Its `sort` stage puts the items in order using\ntheir `<=>` — here the one we gave `Score` — just as *Using Operators* sorted a `List of Release`; then\n`collect` gathers the result back into a list:\n\n```ek9\n    rank() as pure\n      -> board as List of Score\n      <- rtn as List of Score: List() of Score\n      rtn: cat board | sort | collect as List of Score\n```\n\nThree more helpers build and display the table: `startingBoard` (the scores already there),\n`finalBoard` (add this game's result) and `boardLines` (turn the ranked board into text, best first):\n\n```ek9\n    boardLines()\n      -> board as List of Score\n      <- rtn as String: \"\"\n      for entry in rank(board)\n        rtn += `  ${entry}\\n`\n```\n\nEach of these can be called from a test with a known input and its answer checked. None of them needs\na keyboard or a running game.\n\n## The program: a thin shell\n\nNow the part that talks to a person, and very little is left for it to do. It reads the player's name\nfrom the command line, asks the operating system for a random secret, then loops: read a line, pass it\nto the game, print the hint. When the game is over it prints the report and the table.\n\n```ek9\n    Guess()\n      -> argv as List of String\n\n      stdin <- Stdin()\n      stdout <- Stdout()\n\n      player <- playerName(argv)\n      high <- 100\n      maxTries <- 7\n      game <- Game(OS().random(1, high), maxTries)\n\n      stdout.println(`I am thinking of a number from 1 to ${high}. You have ${maxTries} tries.`)\n\n      while not game.over()\n        number <- Integer(stdin.next())\n        stdout.println(`  ${number}: ${game.guess(number)}`)\n\n      stdout.println(game.report(player))\n      stdout.println(\"Fewest tries wins:\")\n      stdout.print(boardLines(finalBoard(player, game.triesUsed())))\n```\n\nA few new names, all small. `OS()` reaches the machine the program is running on; `OS().random(1,\nhigh)` picks the secret. `Stdin()` reads what the player types, a line at a time, with `stdin.next()`.\nAnd `stdout.print` is `println` without the line break at the end; the board text already ends with\none. `playerName` uses `GetOpt` to read an optional `-p name` from the command line, falling back to\n`\"Player\"`, as in *Programs, Input and Output*.\n\nThe loop has no `break` and no `return` to jump out of the middle; EK9 has neither. It runs\n`while not game.over()`, and the game decides when that becomes true. The condition says when the loop\nends; there is no hidden exit.\n\nEvery real decision — what the hint is, whether the game is over, how the report reads, how the board\nsorts — has already been made, and tested, elsewhere. The program only carries text between the\nplayer and the pieces that decide.\n\n## Running the tests\n\nFifteen tests cover the record, the class and the functions. Run them with `ek9 -t` (add `-tC` to\nprint the coverage summary):\n\n```text\nℹ️ Found 15 tests:\n  15 assert (unit tests with assertions)\n\nExecuting 15 tests...\n\n✅ PASS book.guess.tests::BoardLinesListsEveryone [Assert] (6ms)\n✅ PASS book.guess.tests::BoardOpensWithAda [Assert] (6ms)\n✅ PASS book.guess.tests::CorrectTest [Assert] (4ms)\n✅ PASS book.guess.tests::EqualScoresHashAlike [Assert] (4ms)\n✅ PASS book.guess.tests::FewerTriesComeFirst [Assert] (4ms)\n✅ PASS book.guess.tests::GameIsSet [Assert] (4ms)\n✅ PASS book.guess.tests::HigherTest [Assert] (4ms)\n✅ PASS book.guess.tests::LosingGame [Assert] (5ms)\n✅ PASS book.guess.tests::LowerTest [Assert] (4ms)\n✅ PASS book.guess.tests::PlayerNameDefaults [Assert] (1ms)\n✅ PASS book.guess.tests::PlayerNameFromFlag [Assert] (0ms)\n✅ PASS book.guess.tests::RankPutsFewestFirst [Assert] (6ms)\n✅ PASS book.guess.tests::ScoreShowsNameAndTries [Assert] (4ms)\n✅ PASS book.guess.tests::TopScoreJoinsBoard [Assert] (6ms)\n✅ PASS book.guess.tests::WinningGame [Assert] (5ms)\n\nSummary: 15 passed, 0 failed (15 total)\nTypes: 15 assert\nDuration: 69ms\n```\n\nWith `-tC`, the same run ends with the coverage summary:\n\n```text\n📊 Coverage Summary\n  ✅ Methods:  94.4% (17/18)\n  ✅ Lines:    82.6% (71/86)\n  ✅ Branches: 88.9% (8/9)\n\n  ✅ Overall: 83.70% (77/92 probes hit)\n\n📦 By Module:\n  ✅ book.guess: 83.70% (77/92)\n```\n\nAll pass, and coverage is above the minimum. But seventeen of eighteen methods are covered, not all\neighteen. The one never run is `Guess` itself: the program, with its interactive loop.\n\nThat gap is deliberate. **You cannot unit-test a conversation.** The loop's job is to talk to a person\nat a keyboard and to use a random secret from the operating system, and a test has neither.\nEverything that *decides* is tested; the only part left uncovered is the thin part that *talks*. That\nis why we made it thin.\n\nTesting even that shell — giving the program a pretend player who types a fixed script, and a pretend\n\"random\" that always returns the same number — is possible, and the second volume shows how. There you\nlearn to *inject* a program's surroundings, so the loop comes under test too. For now: the more you\nbreak a program into small pieces, the more of it you can show to be correct.\n\n## Playing it\n\nCompiled and run, the game plays as it should. A win, guided by the hints:\n\n```text\nI am thinking of a number from 1 to 100. You have 7 tries.\n  50: lower\n  25: higher\n  37: higher\n  43: higher\n  46: lower\n  44: correct\nWell done Sam - 6 tries.\nFewest tries wins:\n  Ada (3)\n  Alan (5)\n  Sam (6)\n```\n\nAnd a game that runs out of tries: after seven guesses, the program reveals the secret and still\nrecords the score at the bottom of the table:\n\n```text\nI am thinking of a number from 1 to 100. You have 7 tries.\n  10: higher\n  20: higher\n  30: higher\n  40: lower\n  60: lower\n  70: lower\n  80: lower\nOut of tries - the number was 36.\nFewest tries wins:\n  Ada (3)\n  Alan (5)\n  Lee (7)\n```\n\nBoth are real runs. The secret comes from `OS().random`, so it is different every time.\n\n## Where to take it next\n\nThe high-score table lasts only as long as the program runs. The next step is to **save it**: write\nthe board to a file when the game ends, and read it back when the next game starts, so scores carry\nover between games. That is the file work of *Programs, Input and Output*, and `rank` and `boardLines`\nalready exist, so only the reading and writing are new.\n\nBeyond that is the second volume, *EK9 in Depth*, where the things a program talks to — files, the\nclock, randomness, other services — become things you can replace with stand-ins, so that even the parts\nleft untested here come under test.\n\n## Try it yourself\n\n1. Add a `-t tries` option so the player can choose how many guesses they get, as `-p` chooses the\n   name. Which function changes, and which do not?\n2. Give `Score` a different `$`, perhaps `Sam - 6 tries`. Run the tests. Which test do you have to\n   update, and why is it good that one failed?\n3. Save the high-score table to a file at the end of the game and load it at the start, using the file\n   work from *Programs, Input and Output*. Play twice and see a score survive.\n\n## Recap\n\nYou built a complete, playable program from the whole of this book: a `Score` **record** with a\nhand-written `<=>` to sort the table; a `Game` **class** that holds one game's state and hides it behind\nmethods; small **functions** — `hint`, `rank` and the board helpers — that each do one thing; and a\nshort **program** that connects them to `Stdin`, `OS().random` and `GetOpt`. The organising idea, and\none of the most useful habits in the book, was to **keep the program thin and move every decision into a\npiece you can test**. That let fifteen tests cover the record, the class and the functions, and clear\nthe coverage minimum from *Testing as You Go*. The one part left uncovered was the interactive loop,\nbecause you cannot unit-test a conversation — and that gap leads into the second volume, where a\nprogram's surroundings can be tested too.\n\nThat closes this book. You began with a program that printed one line; you can now design types, choose\nbetween a record and a class, write and test functions, work with collections and streams, read the\ncompiler when it stops you, and combine all of it into a program a person can sit down and play. The\nsecond volume turns from *using* the language to *why* it works the way it does, and to building much\nlarger programs.\n\n[^seal]: EK9 has a firm rule behind this. When a class or record has an *uninitialised* field — one\ndeclared `x as Type?` with no starting value — the compiler *requires* the blank, no-argument\nconstructor to be private (error `E07175`), so a half-built object can never get out. `Game`'s fields\nall have starting values, so the compiler does not require it here; we make the constructor private\nourselves, for the same reason. The rule states an intent: a type should never be constructible in a\nstate it cannot honour.\n\n[^classic]: The number-guessing game is one of the best-known examples in programming. It is the\nworked project in Chapter 2 of *The Rust Programming Language* (\"Programming a Guessing Game\"), and\nversions of it go back decades — a \"guess the number\" game appears in David Ahl's *BASIC Computer\nGames* (1973), older than most languages in use today. It lasts because it is a small, complete problem\n— a little input, a loop, a decision, a little state — which makes it a good first project, and a good\nlast chapter.\n","examples":["books/getting-started-with-ek9/ch23-game/Guess.ek9","books/getting-started-with-ek9/ch23-game/dev/tests.ek9"]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Appendix A","title":"The Operator Reference","url":"https://ek9.io/books/getting-started-with-ek9/appendix-operators.html","markdown":"```{=latex}\n\\appendix\n```\n\n# The Operator Reference\n\nThe *Using Operators* chapter grouped EK9's operators by the job they do. This appendix lists the whole\nset in one place, for looking things up.\n\nThe **Default?** column says whether the compiler can write the operator for you. A $\\checkmark$ means\nyou may ask for it by name with `default operator <symbol>`, or get it along with all the others from\nthe blanket `default operator`. Everything else is yours to write, because it carries a decision the\ncompiler cannot guess. The defaultable set is small, and deliberately so: comparing, checking,\nconverting, hashing and copying are mechanical; adding, merging and promoting are not.\n\nComparing is special. A type decides its *sameness* once: `<=>` if it can be ordered, or `==` if it can\nonly be told equal or not. The compiler then **generates** the rest of the family from it — from `<=>`\nit writes `==`, `<>`, `<`, `<=`, `>` and `>=`; from `==` it writes `<>`. Those are marked *generated*\nbelow: you never write them and never ask for them (`E07181`), so they can never disagree with the\n`<=>`. And a defaulted `<=>` needs the *fields* to support it — a record whose fields cannot themselves\nbe ordered gets `==` compared field by field, and no `<`.\n\n## Comparing\n\n| Symbol | Name | What it does | Default? |\n|:--------|:----------------------|:----------------------------------------------------------|:----------:|\n| `<=>` | comparator | Negative, zero or positive: sorts before, same, after. | $\\checkmark$ |\n| `<` | less than | Is the left smaller? | generated |\n| `<=` | less than or equal | Smaller, or the same? | generated |\n| `>` | greater than | Is the left larger? | generated |\n| `>=` | greater than or equal | Larger, or the same? | generated |\n| `==` | equal | Are the two the same? | $\\checkmark$ (or generated) |\n| `<>` | not equal | Are the two different? | generated |\n| `<~>` | fuzzy compare | *How similar* — a closeness score. | |\n\nThe comparator `<=>` — often called the \"spaceship\" — is the root of the family: every other comparison\nis generated from it. `==` is marked both ways: it is generated from a `<=>`, but a type that can only be\ntold equal (a point on a map has no \"smaller\") declares `==` as its sameness instead.\n\n> **Note.** You may write `!=` in an *expression* as a C-style alias for `<>` (`a != b` means `a <> b`).\n> But you never define the not-equal operator at all: `<>` is generated from the type's sameness, and\n> writing `operator !=` is a compile error (`E07640`, \"use `<>` for the not equal operator\"). So: use\n> either symbol in an expression; define neither.\n\n## Arithmetic\n\n| Symbol | Name | What it does | Default? |\n|:--------|:----------------------|:----------------------------------------------------------|:----------:|\n| `+` | add | Add, or join together. | |\n| `-` | subtract | Take away. | |\n| `*` | multiply | Multiply. | |\n| `/` | divide | Divide. | |\n| `^` | power | Raise to a power. | |\n| `mod` | modulus | The modulus (always positive). | |\n| `rem` | remainder | The remainder after division. | |\n| `++` | increment | Move on by one. | |\n| `--` | decrement | Move back by one. | |\n| `!` | factorial | The factorial. | |\n| `abs` | absolute | The size, ignoring sign. | |\n| `sqrt` | square root | The square root. | |\n\n> **Note.** `++` and `--` differ from the rest of this table. They *change the value in place* and\n> return nothing, so each is a statement on its own line, `count++`; `+` and `-` produce a new value\n> instead. Because they change the value in place, on a constrained type `++` and `--` keep the\n> value's own type and check its rule again (*Constrained Types*). To flip a number's sign, write a\n> unary minus: `-count`.\n\n## Arithmetic that assigns\n\nThese do the sum *and* store the answer back, so they change the value they are used on.\n\n| Symbol | Name | What it does | Default? |\n|:--------|:----------------------|:----------------------------------------------------------|:----------:|\n| `+=` | add and assign | Add to, and keep the result. | |\n| `-=` | subtract and assign | Take away from, and keep the result. | |\n| `*=` | multiply and assign | Multiply by, and keep the result. | |\n| `/=` | divide and assign | Divide by, and keep the result. | |\n\n## Converting\n\n| Symbol | Name | What it does | Default? |\n|:--------|:----------------------|:----------------------------------------------------------|:----------:|\n| `$` | to text | The human-readable form. | $\\checkmark$ |\n| `$$` | to JSON | The JSON form, for crossing a boundary. | $\\checkmark$ |\n| `#?` | hashcode | A number standing for the value. | $\\checkmark$ |\n| `#^` | promote | Become another type automatically. One step only. | |\n\n## Asking about state\n\n| Symbol | Name | What it does | Default? |\n|:--------|:----------------------|:----------------------------------------------------------|:----------:|\n| `?` | is set | Does this hold a meaningful value? | $\\checkmark$ |\n| `empty` | is empty | Is there nothing in it? | |\n| `length` | length | How long, or how many. | |\n| `contains` | contains | Is that inside this? | |\n| `matches` | matches | Does it match this pattern? | |\n\nEvery type that holds fields must answer `?` — it is the set/unset check the whole language rests on.\n\n## Copying and merging\n\n| Symbol | Name | What it does | Default? |\n|:--------|:----------------------|:----------------------------------------------------------|:----------:|\n| `:=:` | copy | Copy the other's contents into this one. | $\\checkmark$ |\n| `:^:` | replace | Replace this one's contents with the other's. | |\n| `:~:` | merge | Merge the other into this one, filling gaps. | |\n\nFor your own type the default `:=:` is a *shallow* copy: the copy's fields refer to the same objects\nas the original's.\n\n## Logic and bits\n\n| Symbol | Name | What it does | Default? |\n|:--------|:----------------------|:----------------------------------------------------------|:----------:|\n| `~` | not | Flip a true/false value. The `not` keyword reads the same in an expression. | |\n| `and` | and | True when both are true. | |\n| `or` | or | True when either is true. | |\n| `xor` | exclusive or | True when exactly one is true. | |\n| `<<` | shift left | Shift the bits left. | |\n| `>>` | shift right | Shift the bits right. | |\n\n## The rest\n\n| Symbol | Name | What it does | Default? |\n|:--------|:----------------------|:----------------------------------------------------------|:----------:|\n| `#<` | prefix | The leading part of the value. | |\n| `#>` | suffix | The trailing part of the value. | |\n| `close` | close | Release whatever the value is holding — a file, a connection. | $\\checkmark$ |\n\nYou never call `close` yourself — writing `x.close()` is a compile error (`E81060`). It is called for\nyou: a `try` closes the values it opened when it ends, and a type's `default operator close` closes the\ncloseable fields it holds.\n\nThe stream pipe, `|`, also counts as an operator; it joins the stages of a pipeline together\n(*Streams and Pipelines*).\n\nThat is the complete list of operators you can give to a type of your own. You cannot add to it or\ninvent a new symbol, and each entry has a settled meaning you are expected to keep. In return, an\noperator you meet in anyone's code is one you already understand.\n\n## Operators you use, but never define\n\nA last handful belong to the *language* rather than to any one type. You cannot write your own version of\nthese, because they are built on the set/unset idea that every EK9 value already has. You met them in\n*Guards and Safe Code*.\n\n| Symbol | Name | What it does |\n|:--------|:--------------------------------|:----------------------------------------------------------|\n| `?:` | Coalesce (Elvis) | `a ?: b` — use `a` if it is *set*, else `b`. |\n| `<?` | comparison coalescing (lesser) | The smaller of the two. |\n| `>?` | comparison coalescing (greater) | The larger of the two. |\n| `:=?` | assign-if-unset | Assign *only if* the variable is unset. |\n\n`?:` checks that a value is genuinely **set**, and it is the one to use. (EK9 has no `??` operator, as in\nJavaScript, C# or Swift: EK9 is designed so that a value is never absent, though it may be unset, so there\nwould be nothing for `??` to test. Writing `??` is not allowed - it is a compile error, `E01096` - and `?:` is what you want.)\n\nThe two comparison-coalescing operators (`<?` and `>?`) share one rule: a set value is always\npreferred to an unset one, and only when *both* are set does the comparison actually happen. That is what\nmakes them safe on values which may not have arrived yet — exactly where a plain `<` would hand you a\nmeaningless answer. When the two values are equal, both give back the *left* one; swap the two sides\nif you want the right one.\n","examples":[]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Appendix B","title":"Constructs at a Glance","url":"https://ek9.io/books/getting-started-with-ek9/appendix-constructs.html","markdown":"# Constructs at a Glance\n\nEK9 has a small family of building blocks. You have met all of them in this book. This appendix\nputs their capabilities side by side, so you can look up \"can a record have methods?\" or \"does a\ntrait hold state?\" in one place.\n\nIn the table, $\\checkmark$ means \"yes, has this\"; `--` means \"no\". Read it together with the\nchapter each construct is taught in, which gives the exact rules.\n\n| Construct | Fields | Methods | Operators | Constructors | Can be abstract | Can be extended |\n|---|---|---|---|---|---|---|\n| Function | `--` † | `--` | `--` | `--` | $\\checkmark$ | ‡ |\n| Program | `--` | `--` | `--` | `--` | `--` | `--` |\n| Record | $\\checkmark$ (public) | `--` | $\\checkmark$ | $\\checkmark$ | $\\checkmark$ | $\\checkmark$ |\n| Class | $\\checkmark$ (private) | $\\checkmark$ | $\\checkmark$ | $\\checkmark$ | $\\checkmark$ | $\\checkmark$ |\n| Trait | `--` | $\\checkmark$ | $\\checkmark$ | `--` | always | $\\checkmark$ |\n| Component | $\\checkmark$ (private) | $\\checkmark$ | $\\checkmark$ | $\\checkmark$ | $\\checkmark$ | $\\checkmark$ |\n| Constrained type | (its base) | (its base) | (its base) | $\\checkmark$ | `--` | `--` § |\n| Enumeration | fixed members | `--` | compare, text, first/last | from text | `--` | `--` |\n\n† A plain function holds no state. The one exception is a **dynamic function** with a *capture\nlist*: the captured values become its fields (the second volume).\n\n‡ A function is given an implicit super-type by the compiler so it can be passed around and\nsorted (the second volume). You reuse behaviour by *passing functions*, not by subclassing them.\n\n§ A constrained type *constrains* a base type (*Constrained Types*). It is not a subtype\nof its base and cannot be constrained further.\n\nA few things the table cannot show:\n\n- **Records hold data; classes hide it.** A record's fields are public — it is a transparent\n  carrier of values. A class's fields are private — it hides *how* it stores things behind its\n  methods. That is the difference in one line.\n- **A component hides a *type*.** A class hides values; a component hides a whole implementation\n  behind an interface (*Components*), and an application wires the real one in (the second volume).\n  Its behaviour is reached through its methods.\n- **A trait carries behaviour, not state.** It has no fields of its own; its methods and any\n  operators run on the classes that adopt it (*Traits and Composition*).\n- **Every construct with fields needs `?`.** Any aggregate that holds data must be able to say\n  whether it is set, so it needs the `?` operator — write your own, or ask for `default operator ?`.\n","examples":[]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Appendix C","title":"The Evidence: the research behind the rules","url":"https://ek9.io/books/getting-started-with-ek9/appendix-evidence.html","markdown":"# The Evidence: the research behind the rules\n\nMany of EK9's rules forbid something other languages allow. This appendix gathers the reasons in\none place: each entry names the rule, what it prevents, and the source of the lesson.\n\nNone of these ideas is new. EK9 did not invent unit testing or information hiding; it takes ideas\nthe field has trusted for decades and *builds them into the language*, so they are enforced rather\nthan advised.\n\nEvery source is real. If one interests you, read it, or give it to an AI and ask for a summary at\nthe level you want.\n\n## No `null`; values are absent, unset, or set\n\nEK9 has no `null` keyword. A value is *absent*, *unset*, or *set*. EK9 is designed so that an\nabsent value can never be read, and the compiler checks every read.\n\nThe cost of getting this wrong is famous. Sir Tony Hoare, who introduced the null reference in\n1965, later called it his *\"billion-dollar mistake\"* (QCon London, 2009), for the errors it caused\nover the following decades.\n\n## No `return`; name the result instead\n\nEK9 has no `return` to leave a function part-way through. A function names its result up front,\nand the compiler checks that every path sets it.\n\nApple's *\"goto fail\"* bug (2014, CVE-2014-1266) shows what a jump out of the middle of a block can\ndo: a duplicated `goto fail;` line skipped TLS signature verification on iOS and macOS.\n\n## No `break` or `continue`; use streams and guards\n\nEK9 has no `break` or `continue`. You express \"stop early\" or \"skip this one\" with stream\npipelines and guards instead.\n\nThis traces to Edsger Dijkstra's *\"Go To Statement Considered Harmful\"* (Communications of the\nACM, 1968) — the argument that unrestricted jumps make code hard to reason about. `break` and\n`continue` are small gotos; removing them keeps the shape of a loop honest.\n\n## No fall-through in `switch`\n\nIn EK9 a matching `case` runs and that is all; there is no fall-through into the next case, so\nthere is no `break` to forget.\n\nForgetting that `break` is a recorded weakness: the CERT C coding standard covers it in\nrecommendation MSC17-C, and the Common Weakness Enumeration lists it as CWE-484, \"Omitted Break\nStatement in Switch\".\n\n## Copy at the boundary; no leaking your insides\n\nA type that owns data copies it in and copies it out, so no outsider can reach in and change it.\n\nThis is *information hiding*, named by David Parnas in *\"On the Criteria To Be Used in Decomposing\nSystems into Modules\"* (CACM, 1972). The specific trap — handing back a reference to your own\ninternals — is *representation exposure*, described by Barbara Liskov and John Guttag (2000) and\nby Joshua Bloch's advice on defensive copying. A related modern example: Go shared one loop\nvariable across iterations for over a decade, causing a whole class of bugs, until the language\nwas changed to copy it per iteration in Go 1.22 (2024).\n\n## Traits, not tangled inheritance\n\nEK9 uses *traits* to share behaviour across unrelated types, instead of deep inheritance chains.\n\nTraits come from *\"Traits: Composable Units of Behaviour\"* by Nathanael Schärli and colleagues\n(ECOOP, 2003), which showed how to compose behaviour without the fragility of multiple\ninheritance.\n\n## The compiler measures coupling and cohesion\n\nEK9 measures how tangled your types are (coupling) and how focused they are (cohesion), and it\nenforces generous but fixed limits.\n\nThe terms were coined by Stevens, Myers and Constantine in *\"Structured Design\"* (IBM Systems\nJournal, 1974). The specific measures EK9 enforces are *efferent coupling* (Ce) for coupling and\n*LCOM4* for cohesion — the latter from M. Hitz and B. Montazeri, *\"Measurement of Coupling and\nCohesion in Object Oriented Systems\"* (1995). Cohesion applies to classes, services and components,\nnot to records or traits.\n\n## Named, typed message placeholders\n\nEK9's localised text uses named, typed placeholders like `${name}`, checked at compile time —\nnever untyped positional markers like `%s` or `{0}`.\n\nWeitz and colleagues, *\"A Type System for Format Strings\"* (ISSTA, 2014), built a checker that\nfinds format-string mistakes at compile time — mistakes an ordinary compiler cannot see. EK9 makes\nthe compiler see them.\n\n## More sources cited in the chapters\n\nThese shaped individual chapters rather than a single rule. Each is footnoted where it is used.\n\n- **Preconditions and contracts** (*Functions*): C. A. R. Hoare, *\"An Axiomatic Basis for Computer\n  Programming\"* (1969), and Bertrand Meyer's *Design by Contract*, built into the Eiffel language and\n  described in *Object-Oriented Software Construction* (1988). `require` is EK9's precondition.\n- **Writing the test first** (*Testing as You Go*): Kent Beck, *Test-Driven Development: By Example*\n  (Addison-Wesley, 2002).\n- **Naming a value once** (*Reading the Compiler's Guidance*): Juergens, Deissenboeck, Hummel and\n  Wagner, *\"Do Code Clones Matter?\"* (ICSE, 2009), on changes made to some copies of code but not\n  others.\n- **Small pieces joined by pipes** (*Streams and Pipelines*): Douglas McIlroy, who conceived the Unix\n  pipe, added in 1973.\n- **Many functions over one structure** (*Records and Enumerations*): Alan Perlis, *Epigrams on\n  Programming* (1982), epigram 9.\n- **Composition over inheritance** (*Traits and Composition*): Gamma, Helm, Johnson and Vlissides,\n  *Design Patterns* (1994), and William Cook, Walter Hill and Peter Canning, *\"Inheritance Is Not\n  Subtyping\"* (POPL, 1990).\n\n## The two big payoffs\n\nTwo names sit behind the whole language, and the second volume, *EK9 in Depth*, returns to them:\n\n- **Hoare's null mistake** — which the three-state model above is designed to remove.\n- **The Liskov Substitution Principle** (Barbara Liskov, 1987; Liskov and Wing, 1994) — the rule\n  that a subtype must be usable wherever its parent is. EK9 supports it with its rules — no casts,\n  and an override keeps the purity of the method it replaces — and the second volume looks at how far\n  those rules go.\n","examples":[]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Appendix D","title":"Installing and Running EK9","url":"https://ek9.io/books/getting-started-with-ek9/appendix-install.html","markdown":"# Installing and Running EK9\n\nYou do not need much to run everything in this book. This appendix covers the essentials. The\n*full* tour of the development environment — every panel, every refactoring tool, the AI\nassistant and the automation — lives in the companion book, *The EK9 IDE and Refactoring Toolset*.\n\n## Installing EK9\n\nThese are the steps the EK9 website (`ek9.io`, in its *Downloads* section) gives:\n\n1. Download the compiler for macOS, Linux or Windows from the EK9 repository linked there.\n2. Unpack it (zip, tar.gz or dmg) in a directory of your choice, with no spaces in the path.\n3. Install Java 25 or later, and put Java's `bin` directory on your `PATH`.\n4. Put the directory you unpacked EK9 in on your `PATH`, and set the environment variable\n   `EK9_HOME` to the same directory.\n5. Make a new directory (again, no spaces in the path), put the Hello World program from\n   *Hello, EK9* in a file called `HelloWorld.ek9`, and at a command prompt type\n   `ek9 HelloWorld.ek9`.\n\nIf everything is in place you will see `Hello, World`.\n\nOn a Mac with Apple Silicon, the download may be a disk image named like\n`ek9-<version>-macos-arm64.dmg`. That one carries its own Java runtime, so you can skip step 3 and\n`EK9_HOME`: open the image, drag the `EK9` folder onto `Applications`, add\n`export PATH=\"/Applications/EK9:$PATH\"` to the file `~/.zshrc`, open a new terminal and type\n`ek9 -V`. The `README.txt` inside the folder says the same.\n\n## The EK9 IDE\n\nOnce `ek9` is installed, `ek9 -ide` starts the EK9 IDE (it needs the IDE distribution installed\nbeside the compiler; if it is missing, `ek9 -ide` says so). For a beginner it is the smoothest way to\nwork. It bundles three things you would otherwise install and wire together yourself:\n\n- the **editor**, which understands EK9 as you type,\n- the **compiler**, so a keystroke builds your program, and\n- **built-in help**, so when the compiler points at a problem you can read what it means and how\n  to fix it right there.\n\nThat last part is what makes \"the compiler as your guide\" work for a true beginner. A bare text\neditor and a command line can do the same job, but you have to carry more in your head. The full\ntour of the IDE is in the companion book (`ek9.io/ide/`).\n\n## Under the hood: Java 25\n\nEK9 compiles your code to run on a modern Java runtime (Java 25), which is why step 3 above\ninstalls it. Both the command line and the IDE use it.\n\n## Running from the command line\n\nThis book uses the `ek9` command, typed in a terminal, from *Hello, EK9* on: it compiles a file, runs\nit and runs its tests, and the exact commands appear beside the examples in each chapter. Every\nexample was built and run this way before printing. The same command serves for scripts and, later,\nfor building and sharing packages. The complete list of command-line options is printed by `ek9 -h`,\nand documented in the IDE companion book.\n\nEK9 also has an interactive **REPL**, where you can try a line of EK9 and see the result\nimmediately — handy for experimenting with a value type or an operator. Start it with\n`ek9 -repl`. The IDE companion book covers what it can do.\n\n## Getting the examples\n\nEvery worked example in this book is available as a single download, `examples.zip`. Unpack it,\nopen a chapter's folder in the IDE, and press run. Changing an example and watching what the\ncompiler says is one of the fastest ways to learn EK9.\n","examples":[]}
{"book":"getting-started-with-ek9","bookTitle":"Getting Started with EK9","chapter":"Appendix E","title":"Glossary","url":"https://ek9.io/books/getting-started-with-ek9/appendix-glossary.html","markdown":"# Glossary\n\nPlain definitions of the terms used in this book. Where a term has a chapter of its own, that is\nwhere to go for the full story.\n\n**Absent / unset / set** — the *three states* every EK9 value can be in. *Set* means it holds a\nmeaningful value; *unset* means the object is there but has no meaningful value yet; *absent* means\nthere is no object at all. EK9 code is designed never to see an absent value: the compiler checks\nthat every variable has been given an object before it is read. An empty `Optional` is not absent —\nit is a real `Optional` object that is unset. EK9 has no `null` keyword.\n\n**Abstract** — a type or method with no body, meant to be completed by another type. You cannot\ncreate an abstract type directly. The opposite is *concrete*.\n\n**Aggregate** — a construct that defines a type with members of its own (fields, methods,\noperators): a record, class, trait or component, and, in the second volume, a service. A function is\nnot an aggregate.\n\n**Capture list** — the values a *dynamic* function or class holds on to when it is created, so it\ncan use them later. It holds them by reference, not as copies (the second volume).\n\n**Class** — a construct that hides its data (private fields) behind public methods.\n\n**Component** — a construct that hides a whole *implementation* behind an interface, so the\napplication can wire in the real one. Dependency injection uses components.\n\n**Concrete** — a type complete enough to build: it supplies a body for every method it has. The\nopposite of *abstract*.\n\n**Constant** — a named literal of a built-in type, declared in `defines constant`. Its value can never\nchange: a function given a constant receives a copy.\n\n**Constrained type** — a type built by narrowing another, for example an `Integer` that must be\nbetween 16 and 100. It reuses the base type's abilities but is not a subtype of it.\n\n**Constructor** — the special method that builds a value of a type.\n\n**Coupling / cohesion** — how tangled a type is with others (coupling) and how focused it is on one\njob (cohesion). EK9 measures both and enforces limits.\n\n**Coverage** — how much of your code your tests actually exercise. EK9 measures it and requires a\nminimum.\n\n**Default operator** — an operator the compiler can write for you, such as `<=>` or `?`, because it\nis mechanical. Ask for one by name, or get the whole set with `default operator`.\n\n**Dependency injection (DI)** — supplying a component the real implementation to use, rather than\nhard-wiring it. Lets you swap a real part for a test part (the second volume).\n\n**Dispatcher** — EK9's safe way to run different code for different actual types, without casts\n(the second volume).\n\n**Enumeration** — a type that is a fixed set of named values, declared in `defines type`, such as\nthe days of the week. A value of it can only ever be one of those names, or unset.\n\n**Function** — a named piece of behaviour that takes inputs and may return a result. It holds no\nstate of its own.\n\n**Generic** — a type written once and parameterised by another type, such as `List of String`.\n\n**Guard** — a check attached to a statement that only lets it run when a value is set and passes a\ntest.\n\n**Hash code (`#?`)** — a whole number worked out from a value, which collections such as `Dict` use to\nfind values quickly. Two values that are equal must have the same hash code.\n\n**Hasher** — a built-in type that works out one hash code from several values, added in order:\n`#?(Hasher() + row + number)`. If any value added is unset, the `Hasher` and its hash code are unset.\n\n**Hexadecimal** — counting in base 16, with the digits `0`-`9` then `A`-`F`. Character codes such as\n`é` are written in it.\n\n**Interpolation** — building a string with values inside it, using backticks and `${...}`.\n\n**Iterator** — an object that hands out the items of a collection one at a time: `hasNext()` asks\nwhether there is another, and `next()` takes it.\n\n**Literal** — a value written directly in the code: `42`, `\"Ada\"`, `12#GBP`, `true`.\n\n**Module** — the named box a piece of EK9 code lives in (`defines module ...`).\n\n**Operator** — a symbol such as `+`, `==` or `<=>` that a type can give meaning to. EK9 has a fixed\nset; you cannot invent new symbols, and each must keep its usual meaning.\n\n**Optional / Result** — safe containers for \"maybe a value\" (`Optional`) and \"a value or an error\"\n(`Result`). The compiler makes you check them before use.\n\n**Panic** — how an EK9 program stops at once when something that must be true is not, for example a\nfailed `require`. It prints `Panic:` and the reason.\n\n**Parameter** — a named input to a function or method, declared after `->`.\n\n**Polymorphism** — one name standing for several kinds of thing. Code written for a shared parent\ntype, such as `Shape`, works with every subtype, and each value runs its own version of a method.\n\n**Program** — an entry point you can run, the place your code meets the outside world.\n\n**Promotion (`#^`)** — turning a value into a related type, producing a fresh independent copy.\n\n**Pure / purity** — a promise about *change*: a pure function does not reassign its variables (apart\nfrom setting its result) and does not alter what it was handed. It may still print. The compiler\nchecks it.\n\n**Record** — a construct that carries data openly (public fields), with operators.\n\n**Representation exposure** — the bug where a type hands out a reference to its own internals, so an\noutsider can change them. EK9's copy-at-the-boundary habit prevents it.\n\n**`require` (precondition)** — a condition that must be true before a piece of code runs, such as\n`require n?`. If it is false, the program panics.\n\n**Sanitisation** — checking text that comes in from outside, such as a line read from a file, and\nrefusing content that could be harmful.\n\n**Stream / pipeline** — processing a sequence of values through stages (`cat | filter | map |\ncollect`), EK9's replacement for loops with `break`.\n\n**Subtype** — a type that `extends` another (its parent), and can be used wherever the parent is\nexpected.\n\n**Ternary** — the one-line either/or, `condition <- valueIfTrue : valueIfFalse`.\n\n**Trait** — a bundle of behaviour a class can adopt, letting behaviour cut across unrelated types.\nA trait holds no state of its own.\n\n**Type inference** — the compiler working out a variable's type from the value it is given, as in\n`age <- 36`.\n\n**Unit test** — a small test of one piece of behaviour. In EK9 testing is a first-class part of the\nlanguage, not an add-on.\n\n**Variable** — a name that refers to a value, declared with `<-` (or with `as` and a type).\n\n**`<=>` (the comparator)** — the operator that says whether one value is less than, equal to, or\ngreater than another. Most other comparisons are built from it.\n\n**`?` (the set check)** — asks whether a value is set.\n","examples":[]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Copyright","url":"https://ek9.io/books/ek9-in-depth/copyright.html","markdown":"# Copyright {.unnumbered .unlisted}\n\n*EK9 in Depth*\n*A Guide for Experienced Developers*\n\nThe second volume of *Getting Started with EK9*.\n\nWritten 2020–2026 by Stephen John Limb.\n\nThis book is dedicated to the public domain under CC0 1.0\n(https://creativecommons.org/publicdomain/zero/1.0/): its text, every code example in it, and\nevery file in its download, `examples.zip`. Anyone, AI companies included, may copy, change,\npublish and use any of it, for any purpose, without asking. `examples.zip` carries the same\nstatement in its `LICENSE.txt`. The whole book is also on the web, at\nhttps://ek9.io/books/ek9-in-depth/.\n\nThe appendices that close this book (the operator reference, *Constructs at a Glance*, *The Evidence*,\nthe installation appendix and the glossary) are those of *Getting Started with EK9*, printed here\nunchanged under the same CC0 1.0 dedication.\n\nThe EK9 compiler and tools it describes (the \"Software\") are the proprietary property of\nS&R Limb, and the CC0 dedication above does not extend to them. The Software is provided\nfor authorised use only. No license, express or implied, by estoppel or otherwise, to any\nintellectual property rights in the Software is granted by this document. The EK9 runtime, which\nthe compiler places in every program it builds, is licensed under the Apache License 2.0; see\nhttps://ek9.io/LICENSE.txt.\n\nWritten by Stephen John Limb, with Claude (Anthropic).\n\nEvery code example in this book was compiled and run with the EK9 compiler before publication.\n\nFor licensing inquiries, contact: ek9lang@gmail.com\n","examples":[]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Preface","url":"https://ek9.io/books/ek9-in-depth/preface.html","markdown":"# Preface {.unnumbered}\n\nThis is the second volume of *Getting Started with EK9*. The first taught the language by building small programs. This\none is for people who already think in code: readers who finished the first volume and want the mechanisms behind what\nthey used, and developers fluent in Java, C#, Kotlin, Rust, Go or Python who skipped it and want to know whether EK9 is\nworth their time. If you are in the second group, *Where Volume 1 Left You*, which follows, is a short compiled primer;\nread it first.\n\nThe book does three things, in order. It explains **why the safety you used holds**: the compiler reads your control\nflow, and each rule is a decision about what to forbid. It shows how to **build real systems** with the constructs the\nfirst volume only named: dependency injection, concurrency, a web service, packaging. And it ends on **what the rules add\nup to**: the quality the compiler enforces, and the two famous problems the design answers. Every chapter owns its costs.\nA rule that forbids something takes something away, and the chapter says what, and what it buys.\n\nThe rest of this preface is an essay. It is the argument for the whole design, and the one place the book steps back.\n\n## The decade that still runs your code {.unnumbered}\n\nOpen almost any popular language and you are looking at decisions made between roughly 1969 and 1995. C arrived in 1972,\nC++ in 1985, Java and JavaScript in 1995. Python (1991) and the rest borrowed liberally from the same well. Those designs\nwere shaped by constraints that have since evaporated: a few kilobytes of memory, single processors, no practical type\ntheory in compilers, and a hard requirement that the compiler itself stay small enough to run on the hardware of the day.\n\nUnder those constraints, the choices were sensible. A null pointer was a cheap way to say \"nothing here.\" Letting a\nprogrammer `break` out of a loop or `goto` a cleanup label saved instructions. Leaving quality to convention kept the\ncompiler simple. None of this was foolish. It was *appropriate for 1975*.\n\nThe trouble is that those choices hardened into instincts, and the instincts outlived the constraints. We now have\ngigabytes of memory, many cores, mature type theory, and compilers that can afford to think hard. Yet we still write code\nas though a value might secretly be nothing, as though jumping out of the middle of a block were normal, as though catching\nquality problems were someone else's optional tooling. We inherited the workarounds and forgot they were workarounds.\n\nEK9 is a bet that we can do better by taking the last fifty years of evidence seriously. Not because its designer is\ncleverer than the people who built C - they were giants - but because EK9 is *later*. It has the post-mortems they could\nnot have read.\n\n## What the post-mortems say {.unnumbered}\n\nNearly every constraint EK9 imposes has a recorded failure behind it, not just a taste. The appendix *The Evidence*\ngathers the sources; four are enough here.\n\n- The **null reference** was introduced, by Tony Hoare's own account, in 1965. In 2009 he called it his \"billion-dollar\n  mistake\". Java programmers know its cost as `NullPointerException`.\n- Jumping out of the middle of a block is the oldest complaint of all. Edsger Dijkstra's *\"Go To Statement Considered\n  Harmful\"* (1968) argued that unrestricted jumps make a program hard to reason about. `break` and `continue` are small\n  `goto`s.\n- The **`goto fail`** bug (Apple, 2014, CVE-2014-1266) skipped TLS signature verification on iOS and macOS because of one\n  duplicated jump. It compiled cleanly.\n- **`switch` fall-through** is a recorded weakness: CERT's coding standard covers it in recommendation MSC17-C, and the\n  Common Weakness Enumeration lists it as CWE-484, \"Omitted Break Statement in Switch\".\n\nA language designed in 1975 could not have weighed this evidence, because it did not exist yet. A language designed now has\nno excuse to ignore it. The same holds for **`instanceof` plus a cast**: it quietly breaks Liskov substitution, the\nproperty that makes polymorphism trustworthy.\n\n## The mapping {.unnumbered}\n\nHere, then, is the bridge: each inherited assumption, what we have since learned, and the answer EK9 gives. The chapters\nthat follow teach the right-hand column; this table is the map.\n\n| 1970s assumption (C lineage) | What we learned | EK9's answer |\n|---|---|---|\n| `null` / `nil` is an ordinary value | Hoare's \"billion-dollar mistake\" | No `null` keyword; the tri-state (absent/unset/set) with `?` |\n| Data is mutable by default; *protect the data* with `const` / `final` / `val` | Immutability-as-data is rigid; aliasing still bites | Data is always mutable; the **process** (`pure`) governs *when* mutation may happen |\n| `break` / `continue` / `return` / `goto` to leave a block early | Jumps make a program hard to reason about (Dijkstra, 1968; `goto fail`, 2014) | Removed; **stream pipelines** and **guards** express the intent directly |\n| `switch` fallthrough | Forget one keyword, run the wrong cases (CWE-484) | No fallthrough; one `case` lists several values |\n| Runtime type checks: `instanceof` + casting | Breaks Liskov substitution; brittle | The **dispatcher** routes on argument types - no casts |\n| Inheritance first; classes open by default | The fragile base-class problem | Closed by default; **composition** and trait delegation preferred |\n| Quality is bolt-on: linters, SAST, coverage, style - all optional | Optional checks are skipped under deadline pressure | The **compiler is the single gate**: complexity, purity, coverage, security |\n| Operators have loose or ad-hoc meaning | Surprising operator behaviour breaks substitution | **Finite, strict operator contracts** every type must honour |\n| Internationalisation via external libraries and config files | Bolted on; drifts out of sync | Localisation (`text`) is **in the grammar** |\n| Functions are second-class citizens beside objects (or objects beside functions) | A false dichotomy that distorts designs | Functions and classes are **equal partners**; functions are safely polymorphic |\n| Dependency injection via reflection and frameworks | Wiring errors surface at runtime | DI is a language construct, validated at compile time |\n\n## Two ideas do most of the work {.unnumbered}\n\nIf you remember only two things from this essay, make them these, because every row above ultimately rests on them.\n\n**Tri-state, not null.** In EK9 a value is absent, unset, or set, and the `?` operator asks whether it is set. There is\nno `null` keyword and no way to write one. A value that exists but has nothing meaningful in it is *unset*, an ordinary\nstate you can test and handle; a variable declared but not yet assigned is a *null slot*, and the compiler's job is to\nprove it is never read. That is the claim, stated as carefully as the language's governing document allows: **EK9 is\ndesigned so that absence is unobservable; the compiler checks every read; the proof is in progress.** Every read position\nin the grammar is classified and checked today. The layers that would turn \"no counterexample found\" into a theorem are\nstill being built, and this book says *designed so that*, not *guaranteed*, until they are.[^absence]\n\n**Purity is a property of the process, not the data.** This is the one that most surprises experienced developers,\nbecause it inverts the `const`/`final`/`val` reflex. EK9 has *no* immutable data structures; every record, class and\ncollection is mutable. Safety does not come from freezing the data - it comes from the `function`, `method` or\n`operator` deciding when mutation is permitted. A `pure` process may build values and set its own return, but it may not\nreach out and change what already exists, and it may call only other `pure` processes. Mutation becomes something you\n*grant*, not something you *fight*.\n\nPut those together - values the compiler checks before every read, and operator and override rules a subtype cannot\nquietly betray - and **Liskov substitution has far fewer ways to break**. The compiler keeps those rules, rather than a\nteam promising to; the last chapter looks at how far they go, and where they stop.\n\n## Why this is hard to teach, and worth it {.unnumbered}\n\nA book about a language in the 1970s lineage can reuse the examples its predecessors used and simply change the syntax. A\nloop is a loop; a null check is a null check. This book cannot do that, because the whole point of EK9 is the places where\nit *refuses* to be the same. Its job is harder: to take a concept you already hold, show honestly where EK9 constrains it\nor extends it, prove the constraint with evidence rather than assertion, and then show the EK9 idea that does the job.\n\nThat is the bridge. On the near bank, fifty years of accumulated workarounds we mistook for the nature of programming. On\nthe far bank, a language that asks a simple question of each one - *does this eliminate a category of failure, or merely\ndiscourage it?* - and keeps only the answers that eliminate.\n\n## A word about maturity {.unnumbered}\n\nEK9 is **pre-beta**: a beta is planned for mid-2027, and no production system runs on it yet. Where this book shows a gap - a\nrule the compiler does not yet enforce, a feature that is planned rather than built - it is a real gap, and it is named\nwhere it bites, not softened. What you can check is narrower and firmer: every example in these pages was compiled and run\nwith the EK9 compiler, and every block of output is what that run printed.\n\n[^absence]: EK9's design document on absence lists every route by which an absent value could be read, closes each,\nand says which layers of the proof are built and which are not. Hoare's own account is in *The Evidence*, the appendix.\n","examples":[]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Where Volume 1 Left You","url":"https://ek9.io/books/ek9-in-depth/where-volume-1-left-you.html","markdown":"# Where Volume 1 Left You {.unnumbered}\n\n*Getting Started with EK9* taught the language to a reader who had never programmed. This volume does not repeat it. If you\nread that book, this chapter is the ledger of what it promised and where each promise is kept, and you can skim to the map\nat the end. If you did not, because you already write Java, Kotlin, C#, Rust, Go or Python, this chapter is the primer: ten\nminutes, one program, and the places a fluent programmer trips first. Every listing here was compiled and run.\n\n## The syntax in one table {.unnumbered}\n\nEK9 is not C, Java, C# or Python, and the differences are mostly subtractions. This is the compiler's own summary of them\n(`ek9 -h -E4`), reworded:\n\n| You would write | In EK9 |\n|---|---|\n| `{ }` and `;` | Indentation (two spaces) is structure; a newline ends a statement; `if x > 5`, `switch x`, `case y` are bare |\n| `return` | You name the result in the signature, `<- rtn as Type`, and assign it: `rtn: value`. The compiler proves every path assigns it |\n| `break`, `continue`, `goto`, fall-through | Stream pipelines, guards, and several values in one `case` |\n| `null` | None. A value is absent, unset or set; `?` asks \"set?\" |\n| `new`, `var`, `let`, `final`, `static`, `void`, `public`, `private`, `interface` | `Person()` builds; `<-` declares; fields are always private; `defines constant` at module level; `trait` |\n| `&&`, `\\|\\|`, `!` | `and`, `or`, `not` |\n| `Type[]`, `Type<T>` | `List of Type`, `Type of T` |\n| `int`, `string`, `bool`, `float` | `Integer`, `String`, `Boolean`, `Float`: every type is an object, there are no primitives |\n| `package`, `import` | `defines module x.y` and a `references` block |\n| Safe navigation (Kotlin's `?.`) | A guard: `if x <- maybe()` |\n| `extends X implements Y` | `extends X with trait of Y` |\n\nThree operators do the work of declaration and assignment. `<-` declares a **new** variable. `:=` assigns an **existing**\none. `:=?` assigns only if the target is still unset. Strings with values inside use backticks, `` `Hello ${name}` ``; in\ndouble quotes `${name}` is literal text. Two keyword synonyms exist for readers who prefer them: `given` for `switch` and\n`when` for `if`.\n\n## One program {.unnumbered}\n\nHere is a stock check: a record, a constant, three small `pure` functions, a stream pipeline and a guard. Read it once for\nits shape.\n\n```ek9\n#!ek9\ndefines module book.primer\n\n  defines constant\n    REORDER_LEVEL <- 5\n\n  defines record\n    Item\n      name <- String()\n      stock <- Integer()\n\n      default Item() as pure\n\n      Item() as pure\n        ->\n          itemName as String\n          itemStock as Integer\n\n        name :=? String(itemName)\n        stock :=? Integer(itemStock)\n\n      operator $ as pure\n        <- rtn as String: `${name} (${stock})`\n\n      default operator ?\n\n  defines function\n    needsOrder() as pure\n      -> item as Item\n      <- rtn <- Boolean()\n      rtn: item.stock < REORDER_LEVEL\n\n    describe() as pure\n      -> item as Item\n      <- rtn <- String()\n      rtn: $item\n\n    find() as pure\n      ->\n        wanted as String\n        items as List of Item\n      <- rtn <- Optional() of Item\n\n      for item in items\n        if item.name == wanted\n          rtn: Optional(item)\n\n  defines program\n    Tally()\n      stdout <- Stdout()\n      items <- [Item(\"pen\", 12), Item(\"ink\", 3), Item(\"pad\", 4)]\n\n      low <- cat items | filter by needsOrder | map with describe | collect as List of String\n      stdout.println(`Reorder: ${low}`)\n\n      if ink <- find(\"ink\", items)\n        stdout.println(`Found ${ink.get()}`)\n      else\n        stdout.println(\"No ink\")\n\n      stdout.println(`Found staples? ${find(\"staples\", items)?}`)\n```\n\nIt prints:\n\n```text\nReorder: [\"ink (3)\", \"pad (4)\"]\nFound ink (3)\nFound staples? false\n```\n\nFive things in it are not what you would guess.\n\n**Construct names are the keywords.** `defines record`, `defines function`, `defines program` and `defines constant` each\nopen a block of that construct. A record carries data and operators and holds no methods; a class hides its data behind\nmethods; a trait is a bundle of behaviour; a component hides an implementation behind an interface. A function is a\nfirst-class, single-purpose callable, not a method of something. The same constructs recur in every chapter.\n\n**`default operator ?` is mandatory.** An aggregate with fields must say what \"set\" means for it. `default` asks the\ncompiler to write the obvious one from the fields; without it, the record does not compile (E07235). EK9 has a fixed list\nof operators, each with a fixed meaning, and `default operator` writes the mechanical ones (`<=>`, `$`, `$$`, `#?`, `:=:`,\n`?`) so that you do not.\n\n**`pure` is enforced.** A `pure` function may not reassign anything but its own return, may not mutate what it was handed,\nand may call only other `pure` code. It is not \"no side effects\" - a pure function may print - and there is no escape hatch.\n*Operators and Pragmatic Purity, in Full* is the chapter on what that costs and buys.\n\n**The stream line replaces a loop.**\n\n```ek9\nlow <- cat items | filter by needsOrder | map with describe | collect as List of String\n```\n\n`cat` names the source, each `|` is a stage that takes a function by name, and `collect as` ends it; a pipeline must end in\na terminal. There is no `break` and no `continue`, so \"stop early\" and \"skip this one\" are `filter`, `head` and their kin.\n\n**The guard runs the block only when the value is set.**\n\n```ek9\nif ink <- find(\"ink\", items)\n  stdout.println(`Found ${ink.get()}`)\nelse\n  stdout.println(\"No ink\")\n```\n\n`ink.get()` is legal only because the check sits in the same block; take the `if` away and the compiler refuses the\n`get()`. Guards work identically in `if`, `switch`, `for`, `while` and `try`. That one pattern is the front line of EK9's answer\nto null, and *Optional and Result, in Depth* is the chapter on exactly how far it reaches.\n\n## The first things that trip a fluent programmer {.unnumbered}\n\nThese three cost more first attempts than anything else, because the compiler enforces as errors what other languages leave\nto a style guide.\n\n**A literal in a comparison must be named.** The 5 below is an error, E11064; the same literal repeated three times is\nE11065. Zero, one and minus one are exempt.\n\n```ek9\nif stock < 5\n  rtn: true\n```\n\n```text\nEK9     : Error   : E11064: '5' on line 8 position 17: '5' literal in comparison/range - give it a meaningful name\n             See: ek9 -h E11064\n```\n\nThe fix is a `defines constant`, as `REORDER_LEVEL` above. It costs a line and it puts the intent in a name. The cost is that\nyou cannot write a throwaway threshold inline; what it buys is that every number in a condition has a reason attached.\n\n**Four or more arguments must be named.** `lineTotal(9.99, 2, 0.1, 0.2)` is E11062, and so is a call with two literal\n`true`/`false` arguments. Name them all, in declaration order, with the declared parameter names: `lineTotal(price: 9.99,\nquantity: 2, discount: 0.1, taxRate: 0.2)`.\n\n```text\nEK9     : Error   : E11062: '(' on line 17 position 40: call has 4+ positional arguments - use named arguments for clarity\n             See: ek9 -h E11062\n```\n\n**`operator ?` takes `override` on a plain class or record; the others do not.** `?` is inherited from the root type, so a\nhand-written one replaces it; `$`, `<=>`, `==` and `#?` take `override` only when a parent defines them. Get it wrong and the\ncompiler tells you which way.\n\n```text\nEK9     : Error   : E05120: '?' on line 8 position 15: 'override' required on 'public Boolean <- ?()' in 'Meter' (add it to THIS member only - a member with no parent version must not carry 'override', E05110) as it overrides method of same name/signature in hierarchy\n             See: ek9 -h E05120\n```\n\nBehind all three is the same idea. EK9 does not leave quality to review: the compiler is the single gate, and \"if it\ncompiles, it is good\" is a statement about that gate. Its limits are real and this book states them where they bite.\n\n## A note on field style {.unnumbered}\n\nVolume 1 declared fields with the type spelled out, `count as Integer: Integer()`, because naming the type was part of\nlearning it. This volume uses the terser `count <- Integer()`. Both compile and behave the same:\n\n```ek9\n#!ek9\ndefines module book.habits\n\n  defines constant\n    REORDER_LEVEL <- 5\n\n  defines record\n    Spelled\n      count as Integer: Integer()\n      label as String: String()\n\n      default operator ?\n\n    Terse\n      count <- Integer()\n      label <- String()\n\n      default operator ?\n\n  defines function\n    verdict() as pure\n      -> stock as Integer\n      <- rtn <- String()\n      given stock\n        case 0\n          rtn: \"none left\"\n        default\n          when stock < REORDER_LEVEL\n            rtn: \"reorder\"\n          else\n            rtn: \"fine\"\n\n  defines program\n    Habits()\n      stdout <- Stdout()\n\n      spelled <- Spelled()\n      terse <- Terse()\n      stdout.println(`spelled: ${spelled.count?} ${spelled.label?}`)\n      stdout.println(`terse:   ${terse.count?} ${terse.label?}`)\n\n      stdout.println(verdict(0))\n      stdout.println(verdict(3))\n      stdout.println(verdict(9))\n```\n\n```text\nspelled: false false\nterse:   false false\nnone left\nreorder\nfine\n```\n\nThe two records are the same to the compiler; the example also uses the `given` and `when` synonyms. When you meet the\nlonger form in Volume 1, or in older code, read it as the shorter one.\n\n## The words this volume uses {.unnumbered}\n\nThese words mean one thing each in this book. Each is defined here once; the chapter in the last column is where it is\ntaken apart.\n\n| Word | What it means here | Taken apart in |\n|----|----------------|------|\n| tri-state | every value is absent, present but unset, or present and set; `?` asks \"is it set?\" | *Optional and Result, in Depth* |\n| guard | a `<-` declaration at the head of an `if`, `switch`, `for`, `while` or `try`: the body runs only when the value is set (and, for a `Boolean`, true) | *Optional and Result, in Depth* |\n| pre-flow | the statement ahead of the test in a control structure, `x <- f()` or `x := f()`: the part that runs before the test | *Operators and Pragmatic Purity, in Full* |\n| safe access | a read the compiler has proved legal by a check in the same block, such as `get()` on an `Optional` after `if x?` | *Optional and Result, in Depth* |\n| re-point | making an existing name refer to another object, with `:=` or a `:` assignment; a mutating operator changes the object instead | *Operators and Pragmatic Purity, in Full* |\n| pure | enforced, not advised: no reassignment but the return, no mutation of what was handed in, only pure calls. It does not mean \"no side effects\" | *Operators and Pragmatic Purity, in Full* |\n| aggregate | a construct with members of its own: record, class, trait, component, service. A function is not one, except a dynamic function with a capture list | *Dynamic Functions and Classes* |\n| capture | a value a dynamic function or class takes from the scope around it: a copy of the reference, so a mutation is seen on both sides and a re-point is not | *Dynamic Functions and Classes* |\n| pipeline stage | one verb of a stream (`filter by`, `map with`, `sort by` and the rest); each is a function value | *Stream Pipelines in Depth* |\n| dispatcher | a method marked `as dispatcher`: the compiler routes a call to the overload for the argument's run-time type | *The Dispatcher* |\n| constrained type | a type made by narrowing a base, such as an `Integer` held between 16 and 100; it is not a subtype of its base | *Write-Your-Own Generic Types and Functions* |\n| closeable | a type with `operator close`; the compiler writes the closing, and there is no `close` statement | *Errors and Exceptions* |\n| component, application | a component hides an implementation behind an interface and is one instance per program; an application registers components and aspects and wires them | *Dependency Injection and Applications* |\n| aspect | advice (`before`, `after`) wrapped around a component's methods at its registration line | *Aspects* |\n| HEX | hazard times exposure: an advisory change-risk score, with input variety as its exposure half | *Quality Built In* |\n\n## What Volume 1 promised {.unnumbered}\n\nVolume 1 pointed forward in several places. Each is kept in the second volume, and each chapter opens by quoting the sentence it pays.\n\n| Volume 1 said, in | The promise | Kept in |\n|---|---|---|\n| *Making Decisions and Repeating Work* | Exceptions are for when something goes wrong; the second volume covers them | *Errors and Exceptions* |\n| *Testing as You Go* | The second volume goes into testing, coverage and test-driven development in depth | *Testing the Compiler Trusts* |\n| *Collections* | The second volume covers JSON in full | *A Web Service, Step by Step*, and the JSON sink in *Stream Pipelines in Depth* |\n| *Optional and Result* | Unchecked access, a discarded result and a stale check are compile errors | *Optional and Result, in Depth* |\n| *Streams and Pipelines* | The other pipeline verbs; a one-in, one-out function that is not `pure` is a `Routine` | *Stream Pipelines in Depth*, *Functions as Values: the Type Hierarchy* |\n| *Records and Enumerations* | The second volume moves to the shorter field form | the previous section |\n| *Abstract Types, Subtypes and Polymorphism* | The dispatcher; one function type, answered by many concrete functions | *The Dispatcher*, *Functions as Values: the Type Hierarchy* |\n| *Traits and Composition* | Stacking traits is a topic for the second volume | *Dynamic Functions and Classes* |\n| *Components* | Splitting a project across modules, and injecting a component | *Organising a Growing Codebase*, *Dependency Injection and Applications* |\n| *Using Generics* | Writing your own generic types | *Write-Your-Own Generic Types and Functions* |\n| *Using Operators* | Mutating and non-mutating operators, an exact, enforced model | *Operators and Pragmatic Purity, in Full* |\n| *Build a Game, End to End* | You cannot unit-test a conversation; the second volume shows how to inject a program's surroundings | *Dependency Injection and Applications*, *Testing the Compiler Trusts* |\n| *The Evidence* | The second volume returns to Hoare's null mistake and to Liskov substitution | *The Payoffs: Liskov and Hoare* |\n\n## The map {.unnumbered}\n\nThe volume has three movements. They are not Parts of the printed book; they are how its chapters hang together.\n\n### The first movement: why the safety holds {.unnumbered}\n\n*Optional and Result, in Depth* takes the guard you used and shows what the compiler's flow analysis can see and what it\nrefuses to. *Operators and Pragmatic Purity, in Full* gives the exact operator model and the purity rules. *Functions as\nValues* shows how every function gets a type from its shape. *Dynamic Functions and Classes* adds capture, *Stream Pipelines\nin Depth* uses it, and *The Dispatcher* is the object-oriented cousin of both. *Write-Your-Own Generic Types and Functions*\nis where you author what you used.\n\n### The second movement: building real systems {.unnumbered}\n\n*Organising a Growing Codebase* (with an opinionated section on comments), *Errors and Exceptions*, *Concurrency, Safely*,\n*Dependency Injection and Applications*, *Aspects*, *Networking: TCP and UDP*, *A Web Service, Step by Step* as the capstone,\nand *Packaging and Sharing Your Program*.\n\n### The third movement: what it adds up to {.unnumbered}\n\n*Testing the Compiler Trusts*, *Quality Built In*, and *The Payoffs: Liskov and Hoare*, which names the two problems the whole\ndesign answers.\n","examples":[]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Optional and Result, in Depth","url":"https://ek9.io/books/ek9-in-depth/optional-result-in-depth.html","markdown":"# Optional and Result, in Depth\n\n*Optional and Result* in Volume 1 ended on three compile errors: unchecked access (E08030), a discarded result\n(E11052), and a check made stale by reassignment (E08040). This chapter is the machinery behind those three. If you know\nJava's `Optional` you will have assumed EK9's is the same thing with nicer syntax. It is not. Java's `get()` is legal anywhere\nand throws when you are wrong; EK9's `get()` is legal only inside a block whose check proved the value present, and the\ncompiler, not a runtime check, is what stops you. This chapter is about that flow analysis: what it can see, what it refuses\nto see, and why the refusal is the feature.\n\n## Two ordinary objects\n\n`Optional of T` holds zero or one value. `Result of (O, E)` holds an ok value, an error value, both, or neither; the last two\nare a surprise, and the chapter returns to them. Neither type is special to the type checker. They are\nlibrary types, tri-state like every other EK9 object (set, unset or absent), with `?` meaning \"set\". There is no `unwrap`, no\n`orElseThrow`, no force-access of any kind. The calls that matter are `get`, `getOrDefault` and `whenPresent` on `Optional`,\nand `ok`, `error`, `isOk`, `isError`, `okOrDefault`, `errorOrDefault`, `getOrDefault`, `whenOk` and `whenError` on\n`Result`.[^api] Nothing in those types stops you calling `get()` on an empty `Optional`. What stops you is a pass over your\ncontrol flow.\n\nHere is a start-up routine that reads four settings. One lookup may find nothing; one parse may fail and says why.\n\n```ek9\n#!ek9\ndefines module book.settings\n\n  defines constant\n    LOWEST_PORT <- 1024\n\n    HIGHEST_PORT <- 65535\n\n  defines function\n\n    setting() as pure\n      ->\n        settings as Dict of (String, String)\n        key as String\n      <- rtn <- Optional() of String\n\n      if settings contains key\n        rtn: Optional(settings.getOrDefault(key, String()))\n\n    parsePort() as pure\n      -> text as String\n      <- rtn as Result of (Integer, String)?\n\n      port <- Integer(text)\n      if not port?\n        rtn: Result(Integer(), `'${text}' is not a whole number`)\n      else if port < LOWEST_PORT or port > HIGHEST_PORT\n        rtn: Result(Integer(), `${port} is outside ${LOWEST_PORT} ... ${HIGHEST_PORT}`)\n      else\n        rtn: Result(port, String())\n\n    showPort()\n      -> port as Integer\n      Stdout().println(`listening on ${port}`)\n\n    showProblem()\n      -> problem as String\n      Stdout().println(`cannot listen: ${problem}`)\n\n  defines program\n\n    StartServer()\n      stdout <- Stdout()\n      settings <- {\"host\": \"example.org\", \"port\": \"8o80\", \"retries\": \"3\"}\n\n      if found <- setting(settings, \"host\")\n        stdout.println(`host: ${found.get()}`)\n\n      region <- setting(settings, \"region\").getOrDefault(\"eu-west-1\")\n      stdout.println(`region: ${region}`)\n\n      for key in [\"port\", \"retries\", \"backlog\"]\n        if raw <- setting(settings, key)\n          parsed <- parsePort(raw.get())\n          if parsed.isOk()\n            stdout.println(`${key}: ok ${parsed.ok()}`)\n          if parsed.isError()\n            stdout.println(`${key}: error ${parsed.error()}`)\n        else\n          stdout.println(`${key}: not configured`)\n\n      parsePort(\"8080\").whenOk(showPort)\n      parsePort(\"8080\").whenError(showProblem)\n      parsePort(\"80\").whenOk(showPort)\n      parsePort(\"80\").whenError(showProblem)\n```\n\nIt prints:\n\n```text\nhost: example.org\nregion: eu-west-1\nport: error '8o80' is not a whole number\nretries: error 3 is outside 1024 ... 65535\nbacklog: not configured\nlistening on 8080\ncannot listen: 80 is outside 1024 ... 65535\n```\n\n`setting` returns an `Optional of String`, empty when the key is missing; a `Dict` has no `get()` of its own, so the\n`Optional` is built from `contains` and `getOrDefault`. `parsePort` returns a `Result` carrying either the port or the\nreason it was refused. (The `?` on its return type declares a slot that holds no object until the body assigns one; the\ncompiler proves every path assigns it.) The program then reads these in four different ways, in this order: a **guard**\n(`if found <- setting(...)`) that enters its block only when the `Optional` is set; `getOrDefault`, which never looks inside;\na pair of matched checks, `isOk()` then `ok()` and `isError()` then `error()`; and **callbacks**, where `whenOk` and\n`whenError` are handed a plain function and only the side that is set calls it. A callback that is not `pure` is an\n`Acceptor` and one that is `pure` is a `Consumer`; both overloads exist, and *Functions as Values: the Type Hierarchy* explains why.\n\nMost reads need no check at all. `getOrDefault` and the callbacks are the ways to take a value out without writing one, and\nyou will use them more than you expect.\n\n## The rule\n\nA read is legal where a check in the same block has proved it; this book calls such a read a **safe access**. These are the pairs:\n\n| The check | What it proves |\n|---|---|\n| `x?`, or a guard `if x <- f()`, on an `Optional` | `x.get()` |\n| `r?` on a `Result` (a set `Result` is an ok one) | `r.ok()` |\n| `r.isOk()` | `r.ok()` |\n| `r.isError()` | `r.error()` |\n| `it.hasNext()` on an `Iterator` | `it.next()` |\n\nThe `Iterator` is the third safe container: the compiler treats `Optional`, `Result` and `Iterator` the same way, so\n`next()` without a `hasNext()` check is the same error as a bare `get()`.\n\nTake the check away and the compiler refuses the read:\n\n```ek9\nmaybe <- nickname(\"Stephen\")\nstdout.println(maybe.get())\n```\n\n```text\nEK9     : Error   : E08030: 'get' on line 17 position 27: 'maybe as Optional of String': has not been checked before access\n             See: ek9 -h E08030\n```\n\nMatch the wrong check to the accessor and you get **the same code**. The compiler does not distinguish a missing check from\nthe wrong one; both are \"not checked\":\n\n```ek9\nif parsed.isError()\n  stdout.println(`age ${parsed.ok()}`)\n```\n\n```text\nEK9     : Error   : E08030: 'ok' on line 21 position 37: 'parsed as Result of (Integer, String)': has not been checked before access\n             See: ek9 -h E08030\n```\n\nAnd the same rule holds for the iterator:\n\n```ek9\ncursor <- colours.iterator()\nstdout.println(cursor.next())\n```\n\n```text\nEK9     : Error   : E08030: 'next' on line 10 position 28: 'cursor as Iterator of String': has not been checked before access\n             See: ek9 -h E08030\n```\n\nThe legal forms are a loop and an `if`, each with its `hasNext()` in the head:\n\n```ek9\n#!ek9\ndefines module book.iteration\n\n  defines program\n\n    Iteration()\n      stdout <- Stdout()\n      colours <- [\"red\", \"green\", \"blue\"]\n      cursor <- colours.iterator()\n\n      while cursor.hasNext()\n        stdout.println(cursor.next())\n\n      noColours <- List() of String\n      emptyCursor <- noColours.iterator()\n      if emptyCursor.hasNext()\n        stdout.println(emptyCursor.next())\n      else\n        stdout.println(\"nothing to read\")\n```\n\n```text\nred\ngreen\nblue\nnothing to read\n```\n\n### Where a Rust or Java reader goes wrong first\n\nThe shape every Rust or Java reader writes first is the `else`:\n\n```ek9\nif parsed.isOk()\n  stdout.println(`age ${parsed.ok()}`)\nelse\n  stdout.println(`problem ${parsed.error()}`)\n```\n\n```text\nEK9     : Error   : E08030: 'error' on line 24 position 41: 'parsed as Result of (Integer, String)': has not been checked before access\n             See: ek9 -h E08030\n```\n\nIt does not compile, and the reason is the cost this chapter owns. In Rust, `Result` has two states and `match` has two arms;\n\"not Ok\" is \"Err\". An EK9 `Result` has **four** states, because a `Result` that carries a value *and* an error is a legal,\nset value:\n\n```ek9\n#!ek9\ndefines module book.resultstates\n\n  defines function\n\n    orUnset() as pure\n      -> text as String\n      <- rtn as String: text? <- text else \"(unset String)\"\n\n  defines program\n\n    FourStates()\n      stdout <- Stdout()\n\n      neither <- Result() of (Integer, String)\n      okOnly <- Result(42, String())\n      errorOnly <- Result(Integer(), \"no answer\")\n      both <- Result(42, \"answered, with a caveat\")\n\n      for outcome in [neither, okOnly, errorOnly, both]\n        stdout.println(`set ${outcome?} ok ${outcome.isOk()} error ${outcome.isError()} printed ${orUnset($outcome)}`)\n\n      nothing <- Optional() of String\n      something <- Optional(\"present\")\n      stdout.println(`empty ${orUnset($nothing)} full ${orUnset($something)} set ${nothing?} ${something?}`)\n\n      stdout.println(\"before\")\n      stdout.println($neither)\n      stdout.println(`[${neither}]`)\n      stdout.println(\"after\")\n```\n\n```text\nset false ok false error false printed (unset String)\nset true ok true error false printed {42}\nset false ok false error true printed {no answer}\nset true ok true error true printed {42, answered, with a caveat}\nempty (unset String) full present set false true\nbefore\nafter\n```\n\nThe first four lines are the four states: neither, ok only, error only, both. So \"not ok\" does not tell you there is an\nerror, and the `else` of `isOk()` proves nothing about `error()`. Check each side you intend to read, with its own `if`, as\nthe settings program does. The price is two `if` statements where Rust has one `match`. What it buys is that \"answered, with a\ncaveat\" is a value you can express and cannot silently mishandle.\n\nNotice also what is missing from that output. `$` of an empty `Optional`, or of a `Result` with neither side set, is an unset\n`String`; and printing an unset `String`, or interpolating one into a line, prints **nothing at all**, not even the newline.\nThe program asked for two lines between `before` and `after`, and neither appeared. That is how the tri-state model behaves\ntoday, and it is a genuine cost: a debugging `println` of an empty container tells you nothing. Show emptiness through a\nhelper, as `orUnset` does here, or print the `?` result.\n\n## What keeps the proof\n\nThe proof lives in the block that checked. Within it, quite a lot is allowed:\n\n```ek9\n#!ek9\ndefines module book.safeshapes\n\n  defines constant\n    LIMIT <- 3\n\n  defines function\n\n    attempts() as pure\n      <- rtn as Optional of Integer: Optional(5)\n\n    answer() as pure\n      <- rtn as Result of (Integer, String): Result(7, String())\n\n    flag() as pure\n      <- rtn as Boolean: true\n\n    note()\n      -> text as String\n      Stdout().println(text)\n\n    describe() as pure\n      -> candidate as Integer\n      <- rtn as String: `attempt ${candidate}`\n\n  defines program\n\n    SafeShapes()\n      stdout <- Stdout()\n      tries <- attempts()\n      outcome <- answer()\n      first <- flag()\n      second <- flag()\n\n      if tries? and tries.get() > LIMIT\n        stdout.println(`and: ${tries.get()}`)\n\n      if tries?\n        if tries.get() > LIMIT\n          stdout.println(`nested: ${tries.get()}`)\n\n      if tries?\n        note(\"a call between the check and the read\")\n        stdout.println(`after the call: ${tries.get()}`)\n\n      if (tries? and tries.get() > 1) and describe(tries.get())?\n        stdout.println(describe(tries.get()))\n\n      if (first or second) and tries?\n        stdout.println(`grouped or: ${tries.get()}`)\n\n      if outcome?\n        stdout.println(`a set Result proves ok: ${outcome.ok()}`)\n```\n\n```text\nand: 5\nnested: 5\na call between the check and the read\nafter the call: 5\nattempt 5\ngrouped or: 5\na set Result proves ok: 7\n```\n\nIn order, the proof survives a read in the right-hand conjunct of an `and`; a nested `if`, which is still inside the\nsafe-access block; a call between the check and the read; a parenthesised `and` group, with the read even inside a call argument; and a\nparenthesised `or` ANDed with the check, because the whole group is one conjunct. A set `Result` proves `ok()` too.\n\n## What ends it\n\n`or` proves nothing. If either side can be true without the check, the body can run with the value unset:\n\n```ek9\nif tries? or retry\n  stdout.println(`read: ${tries.get()}`)\n```\n\n```text\nEK9     : Error   : E08030: 'get' on line 20 position 38: 'tries as Optional of Integer': has not been checked before access\n             See: ek9 -h E08030\n```\n\nPrecedence matters here, as it does in C and Python: `and` binds tighter than `or`. `(first or second) and tries?` keeps the\nproof, as the program above showed. Written without the parentheses, `first or second and tries?` means\n`first or (second and tries?)`, and the proof is gone:\n\n```ek9\nif first or second and tries?\n  stdout.println(`ungrouped: ${tries.get()}`)\n```\n\n```text\nEK9     : Error   : E08030: 'get' on line 21 position 43: 'tries as Optional of Integer': has not been checked before access\n             See: ek9 -h E08030\n```\n\nThe other thing that ends the proof is a **store or a mutation** of the checked variable inside the block. Volume 1 showed\nthe plain assignment. The rule is wider than that, because the proof was a fact about the *old* object:\n\n```ek9\nif host?\n  host := fallback()\n  stdout.println(`connecting to ${host.get()}`)\n```\n\nThe assignment is a re-point, and so is the head of a nested `if` that stores before it tests:\n\n```ek9\nif host := fallback() then host?\n  stdout.println(`inner: ${host.get()}`)\nstdout.println(`outer: ${host.get()}`)\n```\n\n```text\nEK9     : Error   : E08040: ':=' on line 16 position 13: 'host as Optional of String': Reassignment/mutation within possible 'safe method access' scope is not allowed\n             See: ek9 -h E08040\nEK9     : Error   : E08040: ':=' on line 23 position 16: 'host as Optional of String': Reassignment/mutation within possible 'safe method access' scope is not allowed\n             See: ek9 -h E08040\n```\n\nMutation counts, not only assignment. `:=:` empties the object in place; the variable still points at it, and the compiler\ntreats that as the same offence:\n\n```ek9\nname <- Optional(\"Steve\")\nif name?\n  name :=: Optional() of String\n  stdout.println(name.get())\n```\n\n```text\nEK9     : Error   : E08040: ':=:' on line 10 position 13: 'name as Optional of String': Reassignment/mutation within possible 'safe method access' scope is not allowed\n             See: ek9 -h E08040\n```\n\nThe proof follows the object, not the text of the block. A call that cannot reach the checked object keeps it - the\n`note(...)` call in the third shape above. A call that may change the object ends it, whether the object is handed over or\nreachable some other way. The compiler does not read the callee to decide; it reads the callee's signature. `forget` is not\npure, so the compiler must assume it can empty what it is given - and it does:\n\n```ek9\nforget()\n  -> target as Optional of String\n  target :=: Optional() of String\n```\n\nSo a read after calling it needs a new check:\n\n```ek9\nname <- Optional(\"Steve\")\nif name?\n  forget(name)\n  stdout.println(name.get())\n```\n\n```text\nEK9     : Error   : E08030: 'get' on line 17 position 28: 'name as Optional of String': has not been checked before access\n             See: ek9 -h E08030\n```\n\nIn Java this compiles and throws `NoSuchElementException` at run time; here it never runs. Declare the callee\n`as pure` and the proof survives the call, because a pure function cannot mutate what it is given - the `:=:` in `forget`\nwould then be E08120. That is the bargain: `pure` is a promise the compiler checks, and the flow analysis spends it. The\ncost falls on a non-pure function that only *reads* the object; the compiler cannot tell it from `forget`, so it ends the\nproof too. *Operators and Pragmatic Purity, in Full* is the rest of that story.\n\n## You may not ignore one either\n\nThe other half of the discipline is that you cannot drop the answer. A function that returns a `Result` or an `Optional` and\nis called as a bare statement is an error:\n\n```ek9\nsave(\"record\")\nlookup(\"missing\")\n```\n\n```text\nEK9     : Error   : E11052: 'save' on line 19 position 6: method returns Result or Optional but result is discarded - must always be checked\n             See: ek9 -h E11052\nEK9     : Error   : E11052: 'lookup' on line 20 position 6: method returns Result or Optional but result is discarded - must always be checked\n             See: ek9 -h E11052\n```\n\nThis is Go's ignorable `err` closed off. The failure the function reported cannot be lost between its return and your next\nline. It is E11052, and it takes precedence over the plainer \"pure return discarded\" rule for these two types.\n\n## The cost\n\nYou cannot stash a `get()` behind an arbitrary Boolean and carry it around. The analysis is scoped and syntactic: it\nrecognises a specific set of checks in specific positions and nothing cleverer. Keep the answer in a variable, or ask a helper\nfunction (`present` returns `candidate?`), and the compiler sees no check at the read:\n\n```ek9\nready <- tries?\n\nif ready\n  stdout.println(`stashed: ${tries.get()}`)\n\nif present(tries)\n  stdout.println(`helper: ${tries.get()}`)\n```\n\n```text\nEK9     : Error   : E08030: 'get' on line 21 position 41: 'tries as Optional of Integer': has not been checked before access\n             See: ek9 -h E08030\nEK9     : Error   : E08030: 'get' on line 24 position 40: 'tries as Optional of Integer': has not been checked before access\n             See: ek9 -h E08030\n```\n\nThere is no `unwrap` to reach for when you are sure, and you are not allowed to be sure. A `Result` takes two `if` statements\nwhere Rust takes one `match`.\n\nThat rigidity is the point, not an accident. Every read of an `Optional` or `Result` has its proof within a screenful of it,\nin the same block; a reviewer never has to ask whether a check three functions away still holds. And the analysis can stay\nthat simple because it is that strict. How the languages compare:\n\n| Language | The form that is legal anywhere | When you are wrong |\n|---|---|---|\n| Java | `Optional.get()` | `NoSuchElementException`, at run time |\n| Rust | `Option::unwrap()`, `Result::unwrap()` | a panic, at run time |\n| Kotlin | `value!!` | `NullPointerException`, at run time |\n| Go | ignoring the returned `err` | nothing, until much later |\n| EK9 | none | E08030, E08040 or E11052, at compile time |\n\nThe rows are not equally bad; Rust's `match` is exhaustive and honest, and Kotlin's `?.` and `?:` are close to EK9's guard\nand `getOrDefault`. The difference is that in each of these languages the unsafe form exists, and a deadline will reach for\nit. In EK9 it does not.\n\n## Where this stops\n\nEK9 has no `null` keyword and no way to write one (E01073). An `Optional` is a real object even when it is empty, so it is\nnever \"null\"; it is unset. A slot declared with a `?` type and not yet assigned is the case that remains, and the compiler's\njob is to prove such a slot is never read. That is what the checks in this chapter are part of. EK9 is **designed so that\nabsence is unobservable; the compiler checks every read; the proof is in progress.** Every read position in the grammar is\nclassified and checked today; the layers that would turn that into a theorem are still being built, and this book says\n*designed so that* until they are.[^evidence] What the chapter has shown you is what the compiler enforces now, with the code\nit prints.\n\n[^api]: The API is `ek9 -h Optional` and `ek9 -h Result`. `whenPresent`, `whenOk` and `whenError` take an `Acceptor` or a\npure `Consumer`.\n\n[^evidence]: Hoare's own account of the null reference, and the sources behind the rules this chapter keeps, are in *The\nEvidence*, the appendix.\n","examples":["books/ek9-in-depth/ch24-optional-result-in-depth/Iteration.ek9","books/ek9-in-depth/ch24-optional-result-in-depth/ResultStates.ek9","books/ek9-in-depth/ch24-optional-result-in-depth/SafeShapes.ek9","books/ek9-in-depth/ch24-optional-result-in-depth/SettingsLookup.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Operators and Pragmatic Purity, in Full","url":"https://ek9.io/books/ek9-in-depth/operators-and-pragmatic-purity.html","markdown":"# Operators and Pragmatic Purity, in Full\n\n*Using Operators* in Volume 1 ended on a promise: an operator is either mutating or non-mutating, EK9 has an exact,\nenforced model of which is which, and that model meets `pure`. If you have written C++ or Python you have overloaded\noperators to mean whatever you liked: `<<` to print, `+` to concatenate, `/` to join paths. EK9 keeps the spelling and\nremoves the freedom. The set of operators is closed, every signature is fixed, and the compiler checks which of them change\ntheir operand. This chapter is that model, the purity rules built on it, and the three operators that copy, merge and\nreplace. It ends on the guard head that Volume 1 left open.\n\n## A closed set with one split\n\nYou cannot invent an operator in EK9, and you cannot give one a signature of your choosing. `?` returns a `Boolean` and takes\nnothing; `$` returns a `String`; `<=>` takes one argument of its own type and returns an `Integer`. The compiler's own list\nof what exists is short enough to hold in your head,[^list] and one line of it does the work of this chapter. Every\noperator either **mutates** its receiver or does not:\n\n| Kind | Operators | `as pure`? |\n|---|---|---|\n| Mutating: changes the object, returns nothing | `:=:` `:~:` `:^:` `+=` `-=` `*=` `/=` `++` `--` | must not be (E07510) |\n| Non-mutating: computes, changes nothing | `+` `-` `*` `/`, the comparisons and `<=>`, `?`, `$`, `$$`, `#?`, `contains`, and the others the list names | must be (E07500) |\n\nThe split is not a convention, because the compiler enforces it in both directions. Here is a `Credit` record that does it\ncorrectly: `+` builds a new value and leaves both operands alone, so it is pure; `+=` changes `deposit` in place, so it is not.\n\n```ek9\n#!ek9\ndefines module book.operatorsplit\n\n  defines record\n\n    Credit\n      pence <- Integer()\n\n      default Credit() as pure\n\n      Credit() as pure\n        -> amount as Integer\n        pence :=? Integer(amount)\n\n      operator + as pure\n        -> other as Credit\n        <- rtn as Credit: Credit(pence + other.pence)\n\n      operator +=\n        -> other as Credit\n        pence += other.pence\n\n      operator $ as pure\n        <- rtn as String: `${pence}p`\n\n      default operator ?\n\n  defines program\n\n    OperatorSplit()\n      stdout <- Stdout()\n\n      deposit <- Credit(150)\n      bonus <- Credit(250)\n\n      sum <- deposit + bonus\n      stdout.println(`sum ${sum}, deposit still ${deposit}`)\n\n      deposit += bonus\n      stdout.println(`after +=, deposit ${deposit}`)\n```\n\n```text\nsum 400p, deposit still 150p\nafter +=, deposit 400p\n```\n\nNow break each half of the rule. A `+` that is not marked `pure`:\n\n```ek9\noperator +\n  -> other as Credit\n  <- rtn as Credit: Credit(pence + other.pence)\n```\n\n```text\nEK9     : Error   : E07500: '+' on line 15 position 15: operator semantics: operator must be declared pure\n             See: ek9 -h E07500\n```\n\nAnd a `+=` that is:\n\n```ek9\noperator += as pure\n  -> other as Credit\n  pence += other.pence\n```\n\n```text\nEK9     : Error   : E07510: '+=' on line 15 position 15: operator semantics: operator must not be declared pure\n             See: ek9 -h E07510\n```\n\nBoth come from the same early pass over the declarations, before any body is read, so a file with both mistakes and a\npurity error in a body shows these two first. The compiler is not inspecting what the operator does; it is holding the\ndeclaration to what the operator's name already says it does. In C++ and Python nothing in the declaration of `+` says it\nmust leave its operands alone. Here a reader who sees `+` knows, from the signature alone, that it returns a new value and\nthat nothing it was given has changed.\n\n## What `pure` enforces\n\n`pure` applies to a function, a method, a constructor or an operator, and it is enforced, transitively, with three rules.\nA pure body may not **reassign** anything but its own return variable (E08100). It may not **mutate** a variable, whether a\nlocal, something it was handed, or the return variable itself (E08120). And it may call only code that is itself pure\n(E08130). Coming from C++ `const` the shape is familiar, except that there is no `const_cast`. Coming from Haskell it is\nweaker: a pure EK9 function may print.\n\nEach rule has a one-line way to break it. The first is the call:\n\n```ek9\nlabel()\n  -> amount as Float\n  <- rtn as String: `GBP ${amount}`\n\nreceipt() as pure\n  -> amount as Float\n  <- rtn as String: `Total ${label(amount)}`\n```\n\n```text\nEK9     : Error   : E08130: 'label' on line 12 position 33: 'label(amount) => String <- label(amount as Float)': is not marked 'pure', but call is made in a scope that is marked as 'pure'\n             See: ek9 -h E08130\n           forAI: purityRules\n```\n\nThe second is a reassignment of a local. Volume 1 showed the plain case; the message also tells you what is allowed, `:=?`, which\nassigns only when the target is still unset:\n\n```ek9\nrunningTotal() as pure\n  -> prices as List of Float\n  <- rtn as Float: 0.0\n\n  running <- 0.0\n  for price in prices\n    running := running + price\n  rtn: running\n```\n\n```text\nEK9     : Error   : E08100: ':=' on line 20 position 16: 'running as Float': reassignment not allowed when scope is marked as 'pure' (':=?' is supported)\n             See: ek9 -h E08100\n           forAI: purityRules\n```\n\nThe third is mutation, and it has two edges worth knowing. The return variable may be *re-assigned* (`rtn: running` is\naccepted above, as is the `rtn:` in every pure function in this chapter) but it may not be *mutated*; and a parameter is\nas protected as anything else:\n\n```ek9\nrunningSum() as pure\n  -> prices as List of Float\n  <- rtn as Float: 0.0\n\n  for price in prices\n    rtn += price\n```\n\n```ek9\naddTo() as pure\n  ->\n    prices as List of Float\n    extra as Float\n\n  prices += extra\n```\n\n```text\nEK9     : Error   : E08120: '+=' on line 28 position 12: mutating variables is not allowed when scope is marked as 'pure'\n             See: ek9 -h E08120\nEK9     : Error   : E08120: '+=' on line 35 position 13: mutating variables is not allowed when scope is marked as 'pure'\n             See: ek9 -h E08120\n```\n\nThe first of those two is the one people do not expect. Accumulating into the return variable is the natural loop in every\nother language, and here it has to be a stream, a `for` that hands back a value, or a local built up with `<-` and returned\nonce. Volume 1's *Guards and Safe Code* shows those shapes; they exist because pure code needs them.\n\nThe fix for the first error is one word. Mark `label` pure and the caller compiles. The program below also shows the two\nthings the rules do not say. A pure function may print (`Stdout().println` is itself declared pure), and a function that is\nnot pure may call a pure one; the restriction runs one way only.\n\n```ek9\n#!ek9\ndefines module book.purity\n\n  defines function\n\n    label() as pure\n      -> amount as Float\n      <- rtn as String: `GBP ${amount}`\n\n    receipt() as pure\n      -> amount as Float\n      <- rtn as String: `Total ${label(amount)}`\n\n    announce() as pure\n      -> text as String\n      Stdout().println(text)\n\n    audit()\n      -> text as String\n      announce(`audit: ${text}`)\n\n  defines program\n\n    PurityRules()\n      stdout <- Stdout()\n      stdout.println(receipt(12.5))\n      announce(\"a pure function may print\")\n      audit(\"a function that is not pure may call a pure one\")\n\n      first <- GUID()\n      second <- GUID()\n      stdout.println(`two calls to a pure constructor, same answer: ${first == second}`)\n```\n\n```text\nTotal GBP 12.5\na pure function may print\naudit: a function that is not pure may call a pure one\ntwo calls to a pure constructor, same answer: false\n```\n\nThe last line is there for the reader who assumes `pure` means referentially transparent. It does not. `GUID()` is a pure\nconstructor and no two calls agree. What `pure` promises is about **change**: nothing is reassigned, nothing handed in is\nmutated, and nothing impure is called. It does not promise that the same input gives the same output, and it does not\npromise silence. If your idea of purity is Haskell's, EK9's is a weaker, more practical property, and the three rules above\nare the whole of what the compiler checks.\n\nConstructors have one more rule, and it explains why every constructor of `Credit` above says `as pure`: if any\nconstructor of a type is pure, all of them must be (E05190).\n\n```ek9\ndefault Credit() as pure\n\nCredit()\n  -> amount as Integer\n  pence :=? Integer(amount)\n```\n\n```text\nEK9     : Error   : E05190: 'Credit' on line 11 position 6: if any constructor is marked pure, all constructors must be pure\n             See: ek9 -h E05190\n           forAI: purityRules\n```\n\n### Purity belongs to the operation\n\nThere is no immutable `List` in EK9, no `final` and no `const`. Every type stays mutable; what `pure` controls is whether *this\npiece of code* may mutate it. A `List` handed to a pure function is the same `List` the caller holds, and the function is\nrefused only when it writes.\n\n> **A design note.** EK9 moves immutability from the data structure to the processing. A `pure` function cannot change\n> what it is given, but what it hands back is an ordinary value the caller may go on changing - reasonable mutation of a\n> returned value is the very nature of many function and method calls. That is deliberately less strict than Haskell and the\n> other functional languages. It also keeps Liskov intact: a Java `List.of(...)` is a `List` whose `add` throws, so every\n> caller of `List` has to wonder which kind it holds, and *The Payoffs: Liskov and Hoare* comes back to that. And there is\n> no converting back and forth between a mutable and an immutable version of the same type. *- Steve*\n\nThat is also why the compiler can use purity without looking inside a callee. *Optional and Result, in Depth* ended on a\n`forget` function that empties an `Optional` it was given, and said that declaring it `as pure` would make the `:=:` inside it\nan E08120. Here is that claim, run:\n\n```ek9\nforget() as pure\n  -> target as Optional of String\n  target :=: Optional() of String\n```\n\n```text\nEK9     : Error   : E08120: ':=:' on line 39 position 13: mutating variables is not allowed when scope is marked as 'pure'\n             See: ek9 -h E08120\n```\n\nSo a pure signature is a promise the compiler has already checked inside the body, and a call to a function the compiler can\nsee is pure does not end the check in *Optional and Result, in Depth*. A callee that is not pure may do anything, so the\nanalysis assumes the worst. *Functions as Values: the Type Hierarchy* shows the same signature reading from the other side: the *type* a function\ngets depends on whether it is pure.\n\n## Copy, merge and replace\n\nThree mutating operators move one object's state into another. In Java you would write `clone()`, a merge helper and a\nsetter loop; in EK9 they are operators, they mutate the left-hand side, and they return nothing.\n\n- `target :=: source` **copies**: the target takes the source's state, set or not.\n- `target :~: source` **merges**: the target takes only what it does not already have. A set value is never overwritten.\n- `target :^: source` **replaces**: the target takes what the source *has set*, overwriting what it holds.\n\nThe built-in types come with their own. For a type of your own, `default operator :=:` generates a copy from the\nfields, and the other two are always yours to write: asking for the merge or the replace to be defaulted is E07220.[^default] A configuration record is\nthe natural home for them, because the three operators are three different answers to \"how do these two settings combine\":\n\n```ek9\n#!ek9\ndefines module book.copymerge\n\n  defines record\n\n    Profile\n      name <- String()\n      email <- String()\n      theme <- String()\n\n      operator :=:\n        -> other as Profile\n        name :=: other.name\n        email :=: other.email\n        theme :=: other.theme\n\n      operator :~:\n        -> other as Profile\n        name :=? String(other.name)\n        email :=? String(other.email)\n        theme :=? String(other.theme)\n\n      operator :^:\n        -> other as Profile\n        if other.name?\n          name :=: other.name\n        if other.email?\n          email :=: other.email\n        if other.theme?\n          theme :=: other.theme\n\n      operator $ as pure\n        <- rtn as String: `${shown(name)} ${shown(email)} ${shown(theme)}`\n\n      override operator ? as pure\n        <- rtn as Boolean: name? and email? and theme?\n\n  defines function\n\n    shown() as pure\n      -> text as String\n      <- rtn as String: text? <- text else \"-\"\n\n  defines program\n\n    CopyMergeReplace()\n      stdout <- Stdout()\n\n      stored <- Profile()\n      stored.name: \"Steve\"\n      stored.email: \"steve@example.org\"\n      stored.theme: \"dark\"\n\n      patch <- Profile()\n      patch.email: \"limb@example.org\"\n      patch.theme: \"light\"\n\n      copied <- Profile()\n      copied :=: stored\n      stdout.println(`copied   [${copied}]`)\n\n      merged <- Profile()\n      merged :=: stored\n      merged :~: patch\n      stdout.println(`merged   [${merged}] the patch could not overwrite`)\n\n      filled <- Profile()\n      filled.name: \"Steve\"\n      filled :~: patch\n      stdout.println(`filled   [${filled}] the gaps were filled`)\n\n      replaced <- Profile()\n      replaced :=: stored\n      replaced :^: patch\n      stdout.println(`replaced [${replaced}] what the patch had set won`)\n```\n\n```text\ncopied   [Steve steve@example.org dark]\nmerged   [Steve steve@example.org dark] the patch could not overwrite\nfilled   [Steve limb@example.org light] the gaps were filled\nreplaced [Steve limb@example.org light] what the patch had set won\n```\n\nNotice that the merge into a full profile changes nothing, and that the merge into a partial one fills only its gaps; the\nbody of `:~:` is `:=?` per field, which is the whole rule. `:^:` on a type of your own means what you write: the operator\nis \"replace\" by name, and for your own type the compiler does not decide what replacing means. On a built-in it overwrites,\nas `:=:` does. All three are mutating operators, so none of them can be declared pure, and none can appear in a pure body\n(E08120).\n\n### References, and what a copy shares\n\nIf you come from Java, your intuition has three cases: primitives copy, `String` and boxed numbers are immutable, and\neverything else is shared by reference. EK9 has one case. Every value is an object, and `<-` from a variable gives the\nnew name to the **same** object:\n\n```ek9\n#!ek9\ndefines module book.aliasing\n\n  defines program\n\n    Aliasing()\n      stdout <- Stdout()\n\n      count <- 10\n      sameObject <- count\n      count++\n      stdout.println(`count ${count} sameObject ${sameObject}`)\n\n      independent <- Integer(count)\n      count++\n      stdout.println(`count ${count} independent ${independent}`)\n\n      names <- [\"Ann\"]\n      sameList <- names\n      names += \"Bo\"\n      stdout.println(`names ${names} sameList ${sameList}`)\n```\n\n```text\ncount 11 sameObject 11\ncount 12 independent 11\nnames [\"Ann\", \"Bo\"] sameList [\"Ann\", \"Bo\"]\n```\n\n`++` is a mutating operator, so it changes the one `Integer` both names point at; there is no boxed immutable `Integer`\nstanding between you and the change. To get an independent value you construct one: `Integer(count)` is a copy.\n\nThe same rule governs `:=:`, and it is the trap in the generated operator. `default operator :=:` copies **each property**\nfrom the source, and a property that holds an object now refers to the *same* object the source's property does. The copy\nis shallow, exactly as `b <- a` and passing a parameter are:\n\n```ek9\n#!ek9\ndefines module book.shallowcopy\n\n  defines record\n\n    Team\n      name <- String()\n      members <- List() of String\n\n      Team()\n        ->\n          name as String\n          members as List of String\n\n        this.name: name\n        this.members: members\n\n      default operator :=:\n      default operator $\n      default operator ?\n\n  defines program\n\n    ShallowCopy()\n      stdout <- Stdout()\n\n      original <- Team(\"core\", [\"Ann\", \"Bo\"])\n      copy <- Team()\n      copy :=: original\n      original.members += \"Cy\"\n      stdout.println(`original ${original}`)\n      stdout.println(`copy     ${copy}`)\n\n      roster <- [\"Di\", \"Ed\"]\n      duplicate <- List() of String\n      duplicate :=: roster\n      roster += \"Flo\"\n      stdout.println(`roster ${roster} duplicate ${duplicate}`)\n```\n\n```text\noriginal Team(name=core, members=[\"Ann\", \"Bo\", \"Cy\"])\ncopy     Team(name=core, members=[\"Ann\", \"Bo\", \"Cy\"])\nroster [\"Di\", \"Ed\", \"Flo\"] duplicate [\"Di\", \"Ed\"]\n```\n\nThe copy of the team sees `Cy`, because both teams hold one `List`. The last line is the contrast: a `List` copied with `:=:` at\nits own level gets its own container, holding the same elements. A shallow copy of a record is the right answer when the\nfields are values and a bug when one of them is a mutable collection you meant to own. There is no default deep copy and no\n`clone()`; a deep or selective copy is an `operator :=:` you write, deciding field by field what is duplicated and what is\nshared. `ek9 -q 2100` answers it with an insurance example in which a renewed policy duplicates its drivers and shares its\nwording.\n\nThis is also where the `E08040` of *Optional and Result, in Depth* comes from. A copy, a merge and a replace are all mutations, so each ends a\nsafe-access proof just as `+=` does, and each is refused inside a pure body for the same reason.\n\n## The re-point head\n\n\"Re-point\" is this book's word for making an existing name refer to another object, and it covers both spellings: the `:=` of\nthis head and the `:` that other chapters use to assign to an existing variable. Neither changes the object the name used to\nrefer to; the name now refers to another.\n\nVolume 1 gave you two assignment forms in a guard head: `<-` declares a new variable and enters only when it is set, and\n`:=?` assigns only when the variable is still unset. The third form handles a variable that already exists and must be\ngiven a new value: **`:=`**, followed by `then` and a check.\n\nThe part of a control-flow head before `then` is the **pre-flow**: the statement that runs once, before the test. In\n`if latest := reading(...) then latest?` the pre-flow is the re-point, and `latest?` is the condition. A pre-flow is blind:\nit assigns and checks nothing, so the head needs its own condition after it.\n\n```ek9\n#!ek9\ndefines module book.thenguard\n\n  defines constant\n    WARM <- 18\n\n  defines function\n\n    reading() as pure\n      ->\n        readings as Dict of (String, Integer)\n        station as String\n      <- rtn as Optional of Integer: Optional() of Integer\n\n      if readings contains station\n        rtn: Optional(readings.getOrDefault(station, Integer()))\n\n  defines program\n\n    ThenGuard()\n      stdout <- Stdout()\n      readings <- {\"roof\": 21, \"cellar\": 9}\n      latest <- Optional() of Integer\n\n      if latest := reading(readings, \"roof\") then latest? and (latest.get() > WARM)\n        stdout.println(`roof is warm: ${latest.get()}`)\n\n      if latest := reading(readings, \"cellar\") then latest? and (latest.get() > WARM)\n        stdout.println(`cellar is warm: ${latest.get()}`)\n      else\n        stdout.println(\"cellar is not warm\")\n\n      if latest := reading(readings, \"attic\") then latest?\n        stdout.println(`attic: ${latest.get()}`)\n      else\n        stdout.println(\"attic: no reading\")\n\n      stdout.println(`after the last check, latest is set: ${latest?}`)\n```\n\n```text\nroof is warm: 21\ncellar is not warm\nattic: no reading\nafter the last check, latest is set: false\n```\n\nThe `get()` is legal in the body and in the right-hand side of the `and` for the reason *Optional and Result, in Depth* gave:\nthe check sits in the same head. Leave the check out and the head has no condition at all:\n\n```ek9\nif latest := reading(\"roof\")\n  stdout.println(`roof: ${latest.get()}`)\n```\n\n```text\nEK9     : Error   : E07340: 'latest' on line 16 position 9: an assignment pre-flow checks nothing, so this 'if' has no condition - use a guard ('<-', ':=?') or add a condition - 'then x?' to enter only when it is set: without a control, failed to find subject of flow\n             See: ek9 -h E07340\n```\n\nThe last line of the program is the cost of `:=`. The head overwrote `latest` on every pass, and when `reading` found nothing it\noverwrote it with an unset `Optional`, so after the attic lookup the old value is gone. If you want to keep what you have\nwhen the new answer is unset, you want `:=?` or a new name. The further condition in the first two heads is parenthesised, as the compiler's own help\nwrites it.\n\n## What it costs\n\nYou cannot write a quick logging call, a cache write or a counter increment into a function you have marked `pure`, and you\ncannot call a helper that nobody marked. The first time it stops you, three levels down a call chain, it is a genuine\nnuisance: the fix is to thread `as pure` up through every helper in between, which is tedious, and where one of them really\ndoes mutate, to split the mutation out into a function that is not pure and call it from the outside. There is no `unsafe`\nand no `const_cast`. Constructors are all-or-nothing, an operator's purity is fixed by its name, and a generated copy is\nshallow whether or not that is what you meant.\n\nWhat that buys is that a signature is a statement the compiler has already checked. The three rules above are checked\ninside every pure body, and a call site needs only the callee's signature to know what it may do to the arguments.\nThat is why a call to a pure function does not end the check in *Optional and Result, in Depth*, and it is why the function\ntypes in *Functions as Values: the Type Hierarchy* fork on purity: the `Predicate` and the `Assessor` have the same shape and differ only in whether the function is\npure.\n\n## Where this stops\n\nThe compiler proves, for every `pure` operation it accepts, that nothing in the body reassigns but the return variable,\nmutates a variable, or calls what is not pure; and for every operator, that its purity matches its kind. It does not try to\nprove that a pure function is deterministic (`GUID()`), that it terminates, or that a hand-written `:=:`, `:~:` or `:^:`\nmeans what its name says; the model fixes the shape of an operator and leaves its meaning to you. A generated `:=:` is\nshallow, and the compiler will not warn you that a field you meant to own is shared.\n\n[^list]: `ek9 -h -E4` prints the paradigm summary, which carries the full list in its OPERATORS block; `ek9 -h operator` is\nthe shorter help.\n\n[^default]: `default operator` writes the mechanical operators (`<=>`, `$`, `$$`, `#?`, `:=:`, `?`) from a type's fields.\n`#^`, `:~:` and `:^:` are always written by hand, and asking for one by default is E07220.\n","examples":["books/ek9-in-depth/ch25-operators-and-purity/Aliasing.ek9","books/ek9-in-depth/ch25-operators-and-purity/CopyMergeReplace.ek9","books/ek9-in-depth/ch25-operators-and-purity/OperatorSplit.ek9","books/ek9-in-depth/ch25-operators-and-purity/PurityRules.ek9","books/ek9-in-depth/ch25-operators-and-purity/ShallowCopy.ek9","books/ek9-in-depth/ch25-operators-and-purity/ThenGuard.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Functions as Values: the Type Hierarchy","url":"https://ek9.io/books/ek9-in-depth/functions-as-values.html","markdown":"# Functions as Values: the Type Hierarchy\n\n*Streams and Pipelines* handed named functions to `filter by` and `map with`, and added in a footnote that \"a one-in,\none-out function that is not `pure`, for example, is a `Routine`\" and that the rest of the family was a matter for this\nvolume. *Abstract Types, Subtypes and Polymorphism* put it as \"One function type, answered by many concrete functions\", with\n\"the full story\" deferred to the same place. Here it is. In Java you reach for `Predicate<Integer>` or declare a\n`@FunctionalInterface`; in C# you write `Func<int, bool>` or a delegate; in Rust a closure satisfies an `Fn` trait. In every\none of them *you* choose or declare the interface a function will be passed as. In EK9 you do neither. You write the\nfunction, and the compiler **synthesises its type from its shape and its purity**. Anywhere that type is expected, the\nfunction goes in by name.\n\n## From shape to type\n\nNothing in the next program says that `isEven` is a `Predicate`, or that `byLength` is a `Comparator`. The functions are\nplain, and each variable in the program names the type the compiler gave them:\n\n```ek9\n#!ek9\ndefines module book.functiontypes\n\n  defines function\n\n    defaultGreeting() as pure\n      <- rtn as String: \"hello\"\n\n    show() as pure\n      -> text as String\n      Stdout().println(`show: ${text}`)\n\n    showPair() as pure\n      ->\n        text as String\n        n as Integer\n\n      Stdout().println(`${text}=${n}`)\n\n    isEven() as pure\n      -> n as Integer\n      <- rtn as Boolean: n mod 2 == 0\n\n    doubled() as pure\n      -> n as Integer\n      <- rtn as Integer: n + n\n\n    describe() as pure\n      -> n as Integer\n      <- rtn as String: `number ${n}`\n\n    byLength() as pure\n      ->\n        first as String\n        second as String\n      <-\n        rtn as Integer: length first <=> length second\n\n    longerThan() as pure\n      ->\n        text as String\n        limit as Integer\n      <-\n        rtn as Boolean: length text > limit\n\n    tagged() as pure\n      ->\n        text as String\n        n as Integer\n      <-\n        rtn as String: `${text}#${n}`\n\n  defines program\n\n    PureShapes()\n      stdout <- Stdout()\n\n      greeting as Supplier of String: defaultGreeting\n      showing as Consumer of String: show\n      pairShowing as BiConsumer of (String, Integer): showPair\n      evenCheck as Predicate of Integer: isEven\n      doubling as UnaryOperator of Integer: doubled\n      describing as Function of (Integer, String): describe\n      ordering as Comparator of String: byLength\n      longerCheck as BiPredicate of (String, Integer): longerThan\n      tagging as BiFunction of (String, Integer, String): tagged\n\n      stdout.println(greeting())\n      showing(\"consumed\")\n      pairShowing(\"width\", 3)\n      stdout.println(`isEven(4) ${evenCheck(4)}`)\n      stdout.println(`doubled(21) ${doubling(21)}`)\n      stdout.println(describing(3))\n      stdout.println(`byLength ${ordering(\"ccc\", \"a\")}`)\n      stdout.println(`longerThan ${longerCheck(\"hello\", 3)}`)\n      stdout.println(tagging(\"item\", 9))\n\n      words <- [\"ccc\", \"a\", \"bb\"]\n      sorted <- cat words | sort by byLength | collect as List of String\n      stdout.println($sorted)\n```\n\n```text\nhello\nshow: consumed\nwidth=3\nisEven(4) true\ndoubled(21) 42\nnumber 3\nbyLength 1\nlongerThan true\nitem#9\n[\"a\", \"bb\", \"ccc\"]\n```\n\nEach variable is declared as the synthesised type and called through it. The last pipeline is the payoff of\nthe whole scheme: `sort by` wants a `Comparator`, and `byLength` is one because it takes two `String`s, returns an `Integer`\nand is `pure`. There is no `implements Comparator<String>`, no adapter and no wrapper object. The same holds for the named functions\nVolume 1 passed to `filter by` and `map with`.\n\nThe library types are themselves functions. `ek9 -h Predicate` shows one:\n\n```text\n    Predicate of type T as pure abstract\n      -> t as T\n      <- r as Boolean?\n```\n\nIt is an **abstract function**: a signature with no body. Your `isEven` conforms to it because the compiler worked out that\nits shape and purity match; it never said `is Predicate`. That relationship is the type hierarchy of the chapter's title.\nThe rules that place a function in it are short enough to hold in a table.\n\n| Shape | If pure | If not pure |\n|---|---|---|\n| no parameters, a return | `Supplier of R` | `Producer of R` |\n| one parameter, no return | `Consumer of T` | `Acceptor of T` |\n| two parameters, no return | `BiConsumer of (T, U)` | `BiAcceptor of (T, U)` |\n| one parameter, `Boolean` back | `Predicate of T` | `Assessor of T` |\n| one parameter, the same type back | `UnaryOperator of T` | `Routine of (T, T)` |\n| one parameter, another type back | `Function of (T, R)` | `Routine of (T, R)` |\n| two parameters of one type, `Integer` back | `Comparator of T` | `BiRoutine of (T, T, Integer)` |\n| two parameters, `Boolean` back | `BiPredicate of (T, U)` | `BiAssessor of (T, U)` |\n| two parameters, another type back | `BiFunction of (T, U, R)` | `BiRoutine of (T, U, R)` |\n| anything else, such as three parameters | `Any` | `Any` |\n\nA shape can fit two rows, and the more specific wins: a pure one-in, same-type-out function is a `UnaryOperator`, not a\n`Function`, and (as the end of this chapter shows) assigning it to a `Function of (T, T)` is refused. The names mirror `java.util.function` on purpose,\nso a Java reader can read the pure column at sight.[^names] The surprise is the right-hand column, which Java does not have.\n\n## Purity forks the hierarchy\n\nHere are the impure twins of those shapes. Every function in the file below is the same as a pure one above, except that\nit is not marked `as pure`:\n\n```ek9\n#!ek9\ndefines module book.impuretwins\n\n  defines function\n\n    nextTicket()\n      <- rtn as Integer: 7\n\n    audit()\n      -> text as String\n      Stdout().println(`audit: ${text}`)\n\n    auditPair()\n      ->\n        text as String\n        n as Integer\n\n      Stdout().println(`audit ${text}=${n}`)\n\n    looksEven()\n      -> n as Integer\n      <- rtn as Boolean: n mod 2 == 0\n\n    bump()\n      -> n as Integer\n      <- rtn as Integer: n + 1\n\n    labelled()\n      -> n as Integer\n      <- rtn as String: `number ${n}`\n\n    longerThan()\n      ->\n        text as String\n        limit as Integer\n      <-\n        rtn as Boolean: length text > limit\n\n    tagged()\n      ->\n        text as String\n        n as Integer\n      <-\n        rtn as String: `${text}#${n}`\n\n    byLength()\n      ->\n        first as String\n        second as String\n      <-\n        rtn as Integer: length first <=> length second\n\n  defines program\n\n    ImpureTwins()\n      stdout <- Stdout()\n\n      ticketing as Producer of Integer: nextTicket\n      auditing as Acceptor of String: audit\n      pairAuditing as BiAcceptor of (String, Integer): auditPair\n      evenGuess as Assessor of Integer: looksEven\n      bumping as Routine of (Integer, Integer): bump\n      labelling as Routine of (Integer, String): labelled\n      longerCheck as BiAssessor of (String, Integer): longerThan\n      tagging as BiRoutine of (String, Integer, String): tagged\n      ordering as BiRoutine of (String, String, Integer): byLength\n\n      stdout.println($ticketing())\n      auditing(\"accepted\")\n      pairAuditing(\"height\", 4)\n      stdout.println(`looksEven(5) ${evenGuess(5)}`)\n      stdout.println(`bump(1) ${bumping(1)}`)\n      stdout.println(labelling(4))\n      stdout.println(`longerThan ${longerCheck(\"hello\", 3)}`)\n      stdout.println(tagging(\"item\", 9))\n      stdout.println(`byLength ${ordering(\"ccc\", \"a\")}`)\n\n      evens <- cat [1, 2, 3, 4] | filter by looksEven | collect as List of Integer\n      stdout.println($evens)\n\n      words <- [\"ccc\", \"a\", \"bb\"]\n      sorted <- cat words | sort by byLength | collect as List of String\n      stdout.println($sorted)\n```\n\n```text\n7\naudit: accepted\naudit height=4\nlooksEven(5) false\nbump(1) 2\nnumber 4\nlongerThan true\nitem#9\nbyLength 1\n[2, 4]\n[\"a\", \"bb\", \"ccc\"]\n```\n\nA function that is not pure is not a `Predicate`, it is an `Assessor`; the same-shape rows split the same way, and the\ncomparator that is not pure is a `BiRoutine`, not a `Comparator`. The pipeline at the end of the program is worth noticing: the\nstream verbs `filter by` and `sort by` accepted the non-pure twins. The fork is in the types.\n\nThe fork matters most to pure code. A pure function may call only pure code, and a function *parameter* is code the\ncompiler has not seen. A parameter's type is the only thing that can say whether the function behind it is pure, and with the\nfork in the type it does:\n\n```ek9\njudge() as pure\n  -> test as Assessor of Integer\n  <- rtn as Boolean: test(6)\n```\n\n```text\nEK9     : Error   : E08130: 'test' on line 39 position 25: 'test(6) => Boolean <- Assessor(t as Integer) as abstract of Integer': is not marked 'pure', but call is made in a scope that is marked as 'pure'\n             See: ek9 -h E08130\n           forAI: purityRules\n```\n\nAn `Assessor` parameter might do anything, so calling it from a pure function is E08130, exactly as calling `label` was in\n*Operators and Pragmatic Purity, in Full*. A `Predicate` parameter is known to be pure, so the same call is legal. The purity\nrules reach through function parameters because purity is part of the function's type.\n\nThe reverse mistake is refused too. A variable of type `Predicate`, or a parameter of one, will not take the impure\n`looksEven`:\n\n```ek9\nevenCheck as Predicate of Integer: looksEven\nstdout.println($acceptsPredicate(looksEven))\n```\n\n```text\nEK9     : Error   : E50030: 'evenCheck' on line 46 position 6: 'evenCheck as Boolean <- Predicate(t as Integer) as abstract of Integer' on line 46 in 'functionTypeMismatches.ek9' and 'Boolean <- looksEven(n as Integer)': types are not compatible with each other\n             See: ek9 -h E50030\nEK9     : Error   : E06270: 'acceptsPredicate' on line 47 position 22: found function 'Boolean <- acceptsPredicate(test as Boolean <- Predicate(t as Integer) as abstract of Integer)' but used with supplied arguments '(Boolean <- looksEven(n as Integer))' not appropriate: parameter mismatch\n             See: ek9 -h E06270\n           forAI: methodResolution\n```\n\nA declaration is E50030, \"types are not compatible\"; an argument is E06270, a parameter mismatch. Both messages print the\ntype the compiler expected as a signature, `Boolean <- Predicate(t as Integer) as abstract of Integer`, which is the clearest\nview of the synthesis you will get. The impure comparator is the same error:\n\n```ek9\nordering as Comparator of String: byLength\n```\n\n```text\nEK9     : Error   : E50030: 'ordering' on line 49 position 6: 'ordering as Integer <- Comparator(t1 as String, t2 as String) as abstract of String' on line 49 in 'functionTypeMismatches.ek9' and 'Integer <- byLength(first as String, second as String)': types are not compatible with each other\n             See: ek9 -h E50030\n```\n\n## When no shape fits\n\nThree parameters match no row, so the function falls back to `Any`. Every function can be held as an `Any`, which is the\nsense in which nothing is left untyped, but an `Any` cannot be called, and a three-parameter function is not a `BiFunction`:\n\n```ek9\nheld as Any: clamp\nstdout.println($held(15, 1, 10))\n\nasBiFunction as BiFunction of (Integer, Integer, Integer): clamp\n```\n\n```text\nEK9     : Error   : E07480: 'held' on line 54 position 22: 'held as Any' used with supplied arguments '(15 as Integer, 1 as Integer, 10 as Integer)': is not a function delegate\n             See: ek9 -h E07480\nEK9     : Error   : E50030: 'asBiFunction' on line 56 position 6: 'asBiFunction as Integer <- BiFunction(t as Integer, u as Integer) as abstract of (Integer, Integer, Integer)' on line 56 in 'functionTypeMismatches.ek9' and 'Integer <- clamp(n as Integer, low as Integer, high as Integer)': types are not compatible with each other\n             See: ek9 -h E50030\n```\n\nThe library catalogue is closed, but you are not limited to it, because an abstract function is a function type you write\nyourself. Declare the signature once, mark the implementations `is` that signature, and take it as a parameter type:\n\n```ek9\n#!ek9\ndefines module book.ownfunctiontype\n\n  defines function\n\n    limit() as pure abstract\n      ->\n        n as Integer\n        low as Integer\n        high as Integer\n      <- rtn as Integer?\n\n    clamp() is limit as pure\n      ->\n        n as Integer\n        low as Integer\n        high as Integer\n      <- rtn as Integer: n\n\n      if n < low\n        rtn: low\n      else if n > high\n        rtn: high\n\n    apply() as pure\n      -> rule as limit\n      <- rtn as Integer: rule(15, 1, 10)\n\n  defines program\n\n    OwnFunctionType()\n      stdout <- Stdout()\n      stdout.println($clamp(15, 1, 10))\n      stdout.println($apply(clamp))\n\n      held as Any: clamp\n      stdout.println(`held as Any is set: ${held?}`)\n```\n\n```text\n10\n10\nheld as Any is set: true\n```\n\n`limit` is now a type with a name, and `apply` takes any function that is declared `is limit`. This is \"one function type,\nanswered by many concrete functions\" in its general form, and the library's `Predicate` is one that someone declared for you.\n\n## An abstract function as a contract\n\nThe same device is how you write a family of interchangeable rules. A till needs a tax rule: take a net price, give back a\ngross. Three rules answer to the one signature, and a pure function chooses among them:\n\n```ek9\n#!ek9\ndefines module book.taxrules\n\n  defines constant\n    STANDARD_RATE <- 0.2\n\n    REDUCED_RATE <- 0.05\n\n  defines function\n\n    taxRule() as pure abstract\n      -> net as Float\n      <- gross as Float?\n\n    standardRate() is taxRule as pure\n      -> net as Float\n      <- gross as Float: net * (1.0 + STANDARD_RATE)\n\n    reducedRate() is taxRule as pure\n      -> net as Float\n      <- gross as Float: net * (1.0 + REDUCED_RATE)\n\n    zeroRate() is taxRule as pure\n      -> net as Float\n      <- gross as Float: net\n\n    ruleFor() as pure\n      -> category as String\n      <- rtn as taxRule?\n\n      switch category\n        case \"food\"\n          rtn: reducedRate\n        case \"book\"\n          rtn: zeroRate\n        default\n          rtn: standardRate\n\n  defines program\n\n    ShopTill()\n      stdout <- Stdout()\n\n      for category in [\"food\", \"book\", \"lamp\"]\n        rule <- ruleFor(category)\n        stdout.println(`${category}: ${rule(100.0)}`)\n\n      asOperator as UnaryOperator of Float: reducedRate\n      stdout.println(`through UnaryOperator: ${asOperator(100.0)}`)\n```\n\n```text\nfood: 105.0\nbook: 100.0\nlamp: 120.0\nthrough UnaryOperator: 105.0\n```\n\n`ruleFor` returns a `taxRule`, and the caller applies whichever it received. This is dynamic selection by a function value\nrather than by a class, and *The Dispatcher* is its object-oriented cousin: one contract, the implementation chosen at run\ntime. The last two lines show that the abstract function sits in the same table. `taxRule` is pure, takes a `Float` and\ngives a `Float` back, so its own super is `UnaryOperator of Float`, and `reducedRate` is accepted as one. A reader who reaches\nfor `Function` first is refused:\n\n```ek9\nasFunction as Function of (Float, Float): reducedRate\n```\n\n```text\nEK9     : Error   : E50030: 'asFunction' on line 51 position 6: 'asFunction as Float <- Function(t as Float) as abstract of (Float, Float)' on line 51 in 'functionTypeMismatches.ek9' and 'Float <- reducedRate(net as Float)': types are not compatible with each other\n             See: ek9 -h E50030\n```\n\n## What it costs\n\nYou have to learn the table, and purity makes one row of it surprising. Add a logging call to a pure `isEven` and the\ncompiler makes you drop `as pure` (a pure function may call only pure code), and the function is now an `Assessor`: every\nplace that held it in a `Predicate` variable or passed it to a `Predicate` parameter stops compiling with E50030 or E06270. The\nchange falls on whoever maintains the shared function, and it spreads to every site that used it. The error text helps less\nthan it might, because it prints the synthesised signature, not your function's, and you have to know the table to see the\ndifference. A function of three or more parameters has no library type, so you declare one. Nor can you tell the compiler that a\nfunction is \"really\" a `Predicate` when its purity says otherwise.\n\nWhat that buys is a type system for functions that nobody declares and nobody can drift out of date: no `@FunctionalInterface`\nto write, no adapter between your `isEven` and a pipeline stage, and one vocabulary that the stream verbs, the callbacks\nof *Optional and Result, in Depth* (`whenOk` takes an `Acceptor` or a pure `Consumer`) and your own code share. Above all,\npurity is in the type. The three rules of *Operators and Pragmatic Purity, in Full* are checked inside each function, and a call through a function value is judged by the purity in its type, not by reading the function behind it.\n\n## Where this stops\n\nThe compiler assigns the type from the signature and purity alone. It does not look at what a function does beyond the\npurity rules, and a function that returns a `Boolean` for any reason at all is a `Predicate`. The table covers up to two\nparameters; past that you write the type. This chapter shows only that `filter by` and `sort by` took the non-pure twins in the\nprogram above; it does not list what every pipeline stage accepts.\n\n[^names]: `Supplier`, `Consumer`, `Predicate`, `Function`, `UnaryOperator`, `BiConsumer`, `BiPredicate` and `BiFunction` are\nthe `java.util.function` names, and `Comparator` is `java.util`'s. `Producer`, `Acceptor`, `Assessor`, `Routine` and the `Bi` forms of them are\nEK9's own, for the functions that are not pure.\n","examples":["books/ek9-in-depth/ch26-functions-as-values/ImpureTwins.ek9","books/ek9-in-depth/ch26-functions-as-values/OwnFunctionType.ek9","books/ek9-in-depth/ch26-functions-as-values/PureShapes.ek9","books/ek9-in-depth/ch26-functions-as-values/TaxRules.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Dynamic Functions and Classes","url":"https://ek9.io/books/ek9-in-depth/dynamic-functions-and-classes.html","markdown":"# Dynamic Functions and Classes\n\n*Streams and Pipelines* in Volume 1 left a footnote: there is a shorter way to write a one-off pipeline function where you\nuse it, without giving it a name, called a *dynamic function*, and the second volume covers it. *Constructs at a Glance*\nleft another: a function holds no state, except a dynamic function with a capture list, whose captured values become its\nfields. This chapter pays both. If you know closures from JavaScript, lambdas from Java or Kotlin, or delegates from C#,\nyou already know what a dynamic function is for. The difference is in what it can see. A JavaScript closure sees every\nvariable in scope, whether you meant it to or not; a Java lambda sees every effectively-final one. An EK9 dynamic function\nsees only what you listed, and the compiler turns that list into the function's fields.\n\n## A function that carries state\n\nA rule that gives a discount above a threshold has two settings, the threshold and the rate. Written as a plain function\nit would need both as parameters on every call, which defeats the point of handing the rule to something else. Written as\na dynamic function, the settings travel inside it:\n\n```ek9\n#!ek9\ndefines module book.vol2.dynamic.discount\n\n  defines function\n\n    discountRule() as pure abstract\n      -> amount as Float\n      <- rtn as Float?\n\n    thresholdRule() as pure\n      ->\n        threshold as Float\n        rate as Float\n      <-\n        rule as discountRule: (threshold, rate) is discountRule as pure function\n          rtn: (amount >= threshold) <- amount * rate : 0.0\n\n  defines program\n\n    Discounts()\n      stdout <- Stdout()\n\n      bulk <- thresholdRule(threshold: 100.0, rate: 0.10)\n      loyalty <- thresholdRule(threshold: 20.0, rate: 0.02)\n\n      amounts <- [15.0, 60.0, 250.0]\n      for amount in amounts\n        stdout.println(`${amount}: bulk ${bulk(amount)} loyalty ${loyalty(amount)}`)\n\n      stdout.println(\"bulk discounts by pipeline:\")\n      cat amounts | map with bulk > stdout\n```\n\nIt prints:\n\n```text\n15.0: bulk 0.0 loyalty 0.0\n60.0: bulk 0.0 loyalty 1.2\n250.0: bulk 25.0 loyalty 5.0\nbulk discounts by pipeline:\n0.0\n0.0\n25.0\n```\n\n`discountRule` is an abstract function: a signature with no body, and a function type of its own. *Functions as Values: the Type Hierarchy*\ncovers how EK9 gives every function a type from its shape; here it is enough that a dynamic function must implement\nsomething abstract (or a function declared `as open`), and that the abstract function supplies the parameters and the\nreturn variable the body works with. The whole dynamic function is one expression:\n\n```text\n(threshold, rate) is discountRule as pure function\n  rtn: (amount >= threshold) <- amount * rate : 0.0\n```\n\nThe parenthesised list is the **capture** list. `threshold` and `rate` are copied in from the enclosing scope (the names are copied, not the objects; *What a capture\nis*, below, has the precise rule), and from then on this function's names for them are its own. Of the enclosing scope's variables the body sees only the captures; beyond those it has the abstract function's\nparameter (`amount`) and its return variable (`rtn`). That last point has one trap. Inside `thresholdRule` the dynamic\nfunction's return variable is the abstract function's `rtn`, so `thresholdRule`'s own return must be called something else.\nHere it is `rule`.\n\nThe two rules built from the one factory behave differently because each carries its own `threshold` and `rate`. Neither\nrule's settings can be reached from outside. A rule is also an ordinary value, so `map with bulk` takes it as a pipeline\nstage exactly as it would take a named function. That is the point of *Streams and Pipelines*: every stage is a function\nvalue, and a function value can carry state.\n\nA dynamic function can also be written at the place it is used, with no name and no variable. This is the shorter way Volume 1\npromised:\n\n```ek9\n#!ek9\ndefines module book.vol2.dynamic.inline\n\n  defines function\n\n    overLimit() as pure abstract\n      -> reading as Integer\n      <- rtn as Boolean?\n\n  defines program\n\n    InlineStage()\n      stdout <- Stdout()\n      readings <- [12, 48, 7, 63, 31]\n      limit <- 30\n\n      alarms <- cat readings\n        | filter by (limit) is overLimit as pure function (rtn: reading > limit)\n        | collect as List of Integer\n      stdout.println(`alarms: ${alarms}`)\n```\n\n```text\nalarms: [48, 63, 31]\n```\n\nThe stage `filter by (limit) is overLimit as pure function (rtn: reading > limit)` captures `limit` and gives the function its\nbody as a single `rtn:` expression in parentheses. Use it when the stage is used once and reads naturally on the line. When the\nline starts to wrap, give the function a name and a declaration of its own.\n\n## What a capture is\n\nThe word \"capture\" means something different in each of the languages you may be thinking of, so it is worth being exact.\nThe experiment is two captures, an `Integer` and a `List`, each changed after the dynamic function was made:\n\n```ek9\n#!ek9\ndefines module book.vol2.dynamic.capturesemantics\n\n  defines function\n\n    counter() as abstract\n      <- rtn as Integer?\n\n    sizer() as abstract\n      <- rtn as Integer?\n\n  defines program\n\n    CaptureSemantics()\n      stdout <- Stdout()\n\n      n <- 1\n      f <- (n) is counter as function\n        rtn: n\n      stdout.println(`f() at capture: ${f()}`)\n\n      n++\n      stdout.println(`after n++ (n is ${n}): f() is ${f()}`)\n\n      n := 5\n      stdout.println(`after n := 5 (n is ${n}): f() is ${f()}`)\n\n      items <- [10, 20]\n      g <- (items) is sizer as function\n        rtn: length items\n      stdout.println(`g() at capture: ${g()}`)\n\n      items += 30\n      stdout.println(`after items += 30 (${items}): g() is ${g()}`)\n\n      items := [7, 8, 9, 11]\n      stdout.println(`after items := [...] (${items}): g() is ${g()}`)\n```\n\n```text\nf() at capture: 1\nafter n++ (n is 2): f() is 2\nafter n := 5 (n is 5): f() is 2\ng() at capture: 2\nafter items += 30 ([10, 20, 30]): g() is 3\nafter items := [...] ([7, 8, 9, 11]): g() is 3\n```\n\nA capture is a copy of the *reference*. `n++` and `items += 30` change the object the variable points at, so the dynamic\nfunction, which points at the same object, sees the change. `n := 5` and `items := [...]` point the outer variable at a\nnew object; the dynamic function keeps the old one and does not see it. So the function is not a live window on the\nvariable, and it is not a snapshot of the value either:\n\n| Language | What the closure holds | Rebinding the outer variable afterwards |\n|---|---|---|\n| JavaScript | the variable itself | seen by the closure |\n| C# | the variable itself | seen by the closure |\n| Java | a copy; the variable must be effectively final | not allowed |\n| EK9 | a copy of the reference, listed by you | legal, and not seen |\n\nIf you reach for \"capture by value\" or \"capture by reference\" to describe EK9's, neither is right. The working rule is one\nsentence: the dynamic function and the enclosing scope share the object, and each keeps its own name for it. This matters\nmost with mutable objects such as collections, which is where a captured `List` can be changed from either side.\n\nInside the body the rule runs one way. The body may read a capture, and it may change the shared object in place with\n`:=:`, `:~:`, `:^:`, `+=` or `++`, which the enclosing scope sees. It may not point its own name at another object,\nbecause nothing outside would ever see that object: `:`, `:=` and `:=?` on a capture are E08280.\n\n```ek9\nnext <- (calls) is counter as function\n  calls: calls + 1\n  rtn: calls\n```\n\n```text\nEK9     : Error   : E08280: ':' on line 16 position 13: 'calls': a dynamic function never re-points a variable it captured - a capture is an initial value (read it, and declare a new variable for a new value) or a way back out (copy into it with ':=:', merge with ':~:' or replace with ':^:', which the caller sees); re-pointing changes only the function's own name\n             See: ek9 -h E08280\n```\n\nSo a capture has two jobs: it is an initial value the body reads, or a way back out that the body changes in place.\nHere `calls++` is the fix. When the body wants a value of its own, it declares a new variable, `total <- calls + 1`,\nand leaves the capture alone. A dynamic class is different: its captures are fields, and its methods assign them as\nordinary object state.\n\n## The list is the whole interface\n\nBecause the capture list is explicit, a body cannot use an outer variable it did not name. Leave `limit` off the list and\nthe body has nothing to read:\n\n```ek9\nlimit <- 10\n\nsupplier <- () is limitSupplier as function\n  rtn: limit\n```\n\n```text\nEK9     : Error   : E50001: 'limit' on line 16 position 13: 'limit': not resolved\n             See: ek9 -h E50001\nEK9     : Error   : E08090: 'limit' on line 13 position 6: 'limit as Integer': is not referenced anywhere, or not referenced after assignment\n             See: ek9 -h E08090\n```\n\nThe compiler does not report a missing capture, because there is no such thing to report: the name is not in scope inside the\nbody, so it is simply not resolved (E50001), and the outer `limit` then reports that nothing read it (E08090). The bug class\nthis closes is the one a JavaScript programmer knows as the loop variable that every callback shares, which `var` made\nfamous and which Go changed its loop-variable scoping in version 1.22 to stop causing. You cannot capture something by\naccident in EK9; you can only fail to capture something you meant to.\n\nThe other side is also checked. A capture the body never reads is E11018:\n\n```ek9\nrule <- (rate, label) is discountRule as pure function\n  rtn: amount * rate\n```\n\n```text\nEK9     : Error   : E11018: 'label' on line 17 position 21: unused captured variable in dynamic function or class\n             See: ek9 -h E11018\n```\n\nThe two checks together make the list exact: everything in it is used, and everything used from outside is in it.\n\n## Dynamic classes\n\nA dynamic function implements one abstract function. A dynamic class implements a trait, and may take several. Its captures\nbecome private fields, and `by` can route a trait's methods to a captured object, the way Kotlin's `by` delegates an\ninterface to a property. Here an auditor timestamps and logs every event, built from two collaborators it does not\ninherit from:\n\n```ek9\n#!ek9\ndefines module book.vol2.dynamic.delegation\n\n  defines trait\n\n    Logger\n      log() as abstract\n        -> message as String\n\n    TimeSource\n      now() as pure abstract\n        <- rtn as String?\n\n    Auditor\n      record() as abstract\n        -> event as String\n\n  defines class\n\n    ConsoleLogger with trait of Logger\n      override log()\n        -> message as String\n        Stdout().println(`LOG ${message}`)\n\n    FixedClock with trait of TimeSource\n      stamp <- String()\n\n      FixedClock() as pure\n        -> stamp as String\n        this.stamp :=? String(stamp)\n\n      override now() as pure\n        <- rtn as String: stamp\n\n      default operator ?\n\n  defines program\n\n    Delegation()\n      stdout <- Stdout()\n      logger <- ConsoleLogger()\n      clock <- FixedClock(\"09:00\")\n      prefix <- \"audit\"\n\n      auditor <- (prefix, logger, clock) with trait of Auditor, Logger by logger, TimeSource by clock as class\n        override record()\n          -> event as String\n          log(`${prefix} ${now()} ${event}`)\n\n        default operator ?\n\n      auditor.record(\"login\")\n      auditor.record(\"logout\")\n      stdout.println(`the auditor is also a TimeSource: ${auditor.now()}`)\n```\n\n```text\nLOG audit 09:00 login\nLOG audit 09:00 logout\nthe auditor is also a TimeSource: 09:00\n```\n\n`(prefix, logger, clock)` makes three private fields. `Logger by logger` and `TimeSource by clock` say that those two traits\nare answered by those two fields. The class writes only `record()`, which calls `log()` and `now()` as though it had always\nhad them, and it ends up usable as a `TimeSource` too, as the last line shows.[^clock]\n\nThe class must say when it is set. A capture is a field, and an aggregate with fields needs `operator ?`; the compiler's own\nmessage is plain about the cause:\n\n```ek9\ntag <- (who) with trait of Named as class\n  override name() as pure\n    <- rtn as String: who\n```\n\n```text\nEK9     : Error   : E07236: '(' on line 16 position 13: dynamic class defined on line 16 has 1 captured variable(s) that become private fields but no 'default operator ?' defined: dynamic class with captured variables requires 'default operator ?' to define set/unset semantics for captured fields\n             See: ek9 -h E07236\n```\n\nThat message is the definition of a capture in the compiler's own words: the captured values become private fields,\nand a dynamic function or class that has them is an aggregate. `default operator ?` is true when every capture is set. Write\n`override operator ? as pure` when only some captures matter.\n\n## Composable by name\n\n*Traits and Composition* ended on a promise: Scala has a detailed scheme for stacking traits in order, and EK9 never chooses\nfor you. This is that rule at work. EK9 has no linearised `super` chain, so there is nothing to stack automatically, and the\nphrase \"stackable traits\" would mislead a Scala reader. What EK9 has is composition by name.\n\nWhen two traits give the same method, a class that takes both must say which one wins, or how they combine:\n\n```ek9\nBoldItalic with trait of Bold, Italic\n```\n\n```text\nEK9     : Error   : E06150: 'BoldItalic' on line 18 position 4: method 'public String <- render(text as String)' on 'Italic' and 'Bold' : conflicting methods to be resolved\n             See: ek9 -h E06150\nEK9     : Error   : E06140: 'render' on line 24 position 34: In relation to type 'BoldItalic', and 'render(String)' resolved: public String <- render(text as String) line 7 , public String <- render(text as String) line 12 ambiguous match\n             See: ek9 -h E06140\n           forAI: methodResolution\n```\n\nE06150 is the clash; E06140 is the same fault met at the call site. The fix is an override that calls each trait by name,\nand the order is whatever the override writes:\n\n```ek9\n#!ek9\ndefines module book.vol2.dynamic.composed\n\n  defines trait\n\n    Bold\n      render() as pure\n        -> text as String\n        <- rtn as String: `*${text}*`\n\n    Italic\n      render() as pure\n        -> text as String\n        <- rtn as String: `_${text}_`\n\n    Underlined with trait of Bold\n      override render() as pure\n        -> text as String\n        <- rtn as String: `__${Bold.render(text)}__`\n\n  defines class\n\n    BoldItalic with trait of Bold, Italic\n      override render() as pure\n        -> text as String\n        <- rtn as String: Italic.render(Bold.render(text))\n\n    ItalicBold with trait of Bold, Italic\n      override render() as pure\n        -> text as String\n        <- rtn as String: Bold.render(Italic.render(text))\n\n    Fancy with trait of Underlined\n\n  defines program\n\n    Composing()\n      stdout <- Stdout()\n      word <- \"ek9\"\n      stdout.println(BoldItalic().render(word))\n      stdout.println(ItalicBold().render(word))\n      stdout.println(Fancy().render(word))\n```\n\n```text\n_*ek9*_\n*_ek9_*\n__*ek9*__\n```\n\nThe first two lines are the same two traits in opposite orders, each written out in a class of its own. The third is a trait\nlaid over a trait: `Underlined with trait of Bold` wraps `Bold.render(text)`, and `Fancy` takes that without an override\nbecause only one implementation reaches it. Delegation does not settle a clash: a trait taken with `by` is one more provider\nof its methods, so two delegated traits with the same method need the same override.\n\n## The cost\n\nExplicit capture is more to write than an implicit closure, and you will feel it. A JavaScript arrow function that uses four\nouter variables costs nothing to write and a capture list costs four names; leave one out and the compiler stops you, leave\none in that you no longer use and it stops you again. Composing by name is the same trade on the other axis: to have bold\nthen italic and italic then bold you write two bodies, where Scala lets the order of the trait list decide and you write\nnothing. With three traits that clash on one method there are as many orders to write as you want to offer, and no default\nto fall back on. What this buys is that every dynamic function and every composed class can be read\nfrom its own text: the names it uses are in its list, the order it applies is in its body, and nothing is decided by a\nrule you have to remember. Capture is also what a stream stage written inline, and a network handler (*Networking: TCP and\nUDP*), are built from.\n\n[^clock]: A trait named `Clock` would fail with E01090: `Clock` is the name of a built-in construct, and a second meaning for\nthat name is not allowed. The example names it `TimeSource`.\n","examples":["books/ek9-in-depth/ch27-dynamic-functions-and-classes/CaptureSemantics.ek9","books/ek9-in-depth/ch27-dynamic-functions-and-classes/ComposedByName.ek9","books/ek9-in-depth/ch27-dynamic-functions-and-classes/DiscountRule.ek9","books/ek9-in-depth/ch27-dynamic-functions-and-classes/DynamicClassDelegation.ek9","books/ek9-in-depth/ch27-dynamic-functions-and-classes/InlineStage.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Stream Pipelines in Depth","url":"https://ek9.io/books/ek9-in-depth/stream-pipelines-in-depth.html","markdown":"# Stream Pipelines in Depth\n\n*Streams and Pipelines* in Volume 1 gave you `cat`, `filter`, `map` and `collect`, and ended with a promise: `sort` returns in\n*Using Operators*; the rest of the vocabulary is for the second volume. This is the rest. If you know Java's `Stream`, Rust's\niterator adaptors or LINQ, the verbs will be familiar; the Unix pipe is the nearer ancestor, since EK9 has `tee`, `uniq`,\n`head` and `tail` under their own names. Two things differ from what you know. Every stage takes a *function value*, by\nname or written where it is used (*Dynamic Functions and Classes*), never a lambda over an implicit scope. And the compiler\nholds the pipeline to rules a library cannot: it refuses a `group` with no `sort` ahead of it, and a stream that appends to\nthe collection it is reading.\n\n## One data set, every verb\n\nEight orders, each a customer, a product and an amount, are enough to use every verb once. The whole program is\none file; each block below is a slice of it and of its single run. Where a verb needs a function, the program\nhas a small `pure` one: `customerOf`, `productOf`, `amountOf`, `isLarge`, two comparators (`byCustomerThenAmount` and\n`byAmountDescending`), and `addAmounts`.\n\n### Sort, branch, group, restructure\n\n```ek9\nstdout.println(\"Top orders per customer:\")\nsorted <- List() of Order\ncat orders\n  | sort by byCustomerThenAmount\n  | tee in sorted\n  | group by customerOf\n  | map with topOfGroup\n  | flatten\n  > stdout\n```\n\n```text\nTop orders per customer:\nada monitor 180.0\nada keyboard 45.0\nbob monitor 220.0\nbob keyboard 60.0\ncy laptop 999.0\ncy mouse 12.0\n```\n\n`sort by` takes a comparator and orders the stream. `tee in sorted` is the Unix `tee`: a copy of everything passing that\npoint lands in the variable `sorted`, and the main flow carries on. `group by customerOf` collects *adjacent* items with\nequal keys into a `List` each, so the stream now carries lists of orders, not orders. That is why the `sort by` ahead of it is\nload-bearing, and the compiler agrees:\n\n```ek9\ncat words | group by initialOf > stdout\n```\n\n```text\nEK9     : Error   : E10040: 'group' on line 16 position 18: 'group' requires a preceding 'sort' with no type-changing operations between them\n             See: ek9 -h E10040\n```\n\nComing from Java, `group by` is not `Collectors.groupingBy`. It yields a stream of lists, not a `Map`, and it works by\nadjacency; the price is the mandatory sort. What the adjacency buys is that grouping stays a stream stage like any other and\ncomposes with the rest.\n\n`map with topOfGroup` then runs a function over each list. That function is itself a small pipeline, which is the usual way\nto keep one readable:\n\n```ek9\ntopOfGroup() as pure\n  -> group as List of Order\n  <- rtn as List of Order: cat group | sort by byAmountDescending | head TOP_PER_CUSTOMER | collect as List of Order\n```\n\n`flatten` turns a stream of lists back into a stream of their elements, and `> stdout` ends it. The order is the order of\nthe groups, and within each group the largest amount first: the two biggest orders for each customer.\n\n### Taking and skipping\n\n```ek9\nstdout.println(\"Three smallest:\")\ncat sorted | sort by byAmountDescending | tail 3 > stdout\nstdout.println(\"All but the first in customer order:\")\ncat sorted | skip 1 | map with productOf > stdout\n```\n\n```text\nThree smallest:\nada mouse 15.5\ncy mouse 12.0\nbob cable 9.0\nAll but the first in customer order:\nkeyboard\nmonitor\ncable\nkeyboard\nmonitor\nmouse\nlaptop\n```\n\n`head N`, `tail N` and `skip N` take from the front, take from the back, and drop from the front. `head` is the answer to the\nloop that used `break` to stop early, and `skip` to the counter that used `continue` for the first few. `tail 3` after a\ndescending sort gives the three smallest, still in descending order. These two pipelines read `sorted`, the copy `tee`\nleft behind.\n\n### Filtering out, de-duplicating, and the two sinks\n\n```ek9\nproducts <- List() of String\ncat orders | reject by isLarge | map with productOf | uniq | sort > products\nstdout.println(`small-order products: ${products}`)\ncat orders | filter by isLarge | map with productOf | uniq | sort >> products\nstdout.println(`after adding large-order products: ${products}`)\n```\n\n```text\nsmall-order products: [\"cable\", \"keyboard\", \"mouse\"]\nafter adding large-order products: [\"cable\", \"keyboard\", \"mouse\", \"laptop\", \"monitor\"]\n```\n\n`reject by` is `filter by` inverted, so there is no need to write a `not` function. `uniq` drops repeats and `sort` with no\n`by` uses the type's own ordering. The two sinks are not the same. `>` **replaces** what the target holds, and `>>`\n**adds to** it. The first pipeline fills `products` from nothing; the second adds the large-order products to what is there.\nThis works the same on a `List`, a `Set`, a `Dict` and a `PriorityQueue`, and on a file, where `>` clobbers and `>>` appends.\n\nA replace is all or nothing. The pipeline fills a fresh collection and swaps it in only when the stream has finished, so a\nfailure part-way leaves the target as it was:\n\n```ek9\n#!ek9\ndefines module book.vol2.streams.sinks\n\n  defines constant\n    BAD_NUMBER <- 3\n\n  defines function\n\n    checked()\n      -> number as Integer\n      <- rtn as String: String()\n      if number == BAD_NUMBER\n        throw Exception(\"bad item\")\n      rtn: $number\n\n  defines program\n\n    ReplaceOrAppend()\n      stdout <- Stdout()\n\n      names <- [\"p\"]\n      cat [\"q\", \"r\"] > names\n      stdout.println(`after >: ${names}`)\n\n      cat [\"s\"] >> names\n      stdout.println(`after >>: ${names}`)\n\n      kept <- [\"old\"]\n      try\n        for i in 1 ... 5 | map with checked > kept\n      catch\n        -> ex as Exception\n        stdout.println(`'>' failed part-way, so kept is still: ${kept}`)\n\n      scores <- [30, 10, 20]\n      cat scores | sort > scores\n      stdout.println(`'>' may replace the List the pipeline reads: ${scores}`)\n```\n\n```text\nafter >: [\"q\", \"r\"]\nafter >>: [\"q\", \"r\", \"s\"]\n'>' failed part-way, so kept is still: [\"old\"]\n'>' may replace the List the pipeline reads: [10, 20, 30]\n```\n\nThe last line is the consequence of the swap. Because `>` builds a new collection and replaces the old one at the end,\n`cat scores | sort > scores` is legal: the pipeline reads the old list and the result takes its place. `>>` has no such\nluxury, since it would be adding to the very list it is reading. In Java, `scores.stream().forEach(scores::add)` compiles and\nfails at run time with `ConcurrentModificationException`; EK9 refuses to compile the equivalent:\n\n```ek9\ncat scores >> scores\n```\n\n```text\nEK9     : Error   : E08277: 'scores' on line 10 position 20: 'scores' is read by 'cat' and appended to by '>>': a variable a stream statement appends to ('>>' or 'tee') also plays another part in that same pipeline - read by its 'cat', or captured by or passed to a function the pipeline runs - so the pipeline uses what it is still writing; use the variable before or after the statement, read a copy instead, use '>' to replace it, or collect into a new variable\n             See: ek9 -h E08277\n```\n\nThe message lists the three ways out: use the variable before or after the statement, read a copy, or replace with `>`. The\ncheck is not only about `cat`. A variable that `>>` or `tee` writes may not also be captured by, or passed to, a function the\npipeline runs.\n\n### Folding, splitting and calling\n\n```ek9\ngrandTotal <- cat orders | map with amountOf | join with addAmounts | collect as Float\n\nmanifest <- [\"# Monday\", \"ada keyboard\", \"bob monitor\", \"# Tuesday\", \"cy laptop\", \"# Wednesday\", \"bob cable\", \"ada mouse\"]\ncat manifest | split with isDayHeader | map with daySummary > stdout\n\ncountLine <- (orders) is summaryLine as pure function\n  rtn: `${length orders} orders in total`\ntotalLine <- (grandTotal) is summaryLine as pure function\n  rtn: `grand total ${grandTotal}`\ncat [countLine, totalLine] | call > stdout\n```\n\n```text\n# Monday (2)\n# Tuesday (1)\n# Wednesday (2)\n8 orders in total\ngrand total 1540.5\n```\n\n`join with addAmounts` folds the stream pairwise into one value, here the total of every amount; it is the fold other\nlanguages call `reduce`. `split with isDayHeader` starts a new list at each item the predicate accepts and emits the lists, which\n`daySummary` then summarises: three headers, three lists. `group` and `split` take a stream down to lists and `flatten`\nbrings it back up.\n\n`call` is the odd one. It takes no function. The *elements* of the stream are the functions, and `call` runs each one in\norder and passes its result on. Here the elements are the two dynamic functions from the lines above, each capturing a\ndifferent value. Give `call` or `async` a function and the compiler says so:\n\n```ek9\ncat numbers | call with doubled > stdout\n\ncat numbers | async by doubled > stdout\n```\n\n```text\nEK9     : Error   : E07880: 'call' on line 16 position 20: a function or function delegate is not required here\n             See: ek9 -h E07880\nEK9     : Error   : E07880: 'async' on line 18 position 20: a function or function delegate is not required here\n             See: ek9 -h E07880\n```\n\nTo apply a function to plain values, `map with` first turns the data into functions to call: `cat numbers | map with toWorker | call`.\n\n## JSON as a sink\n\n*Collections* in Volume 1 said the second volume covers JSON in full; the parsing half is in *A Web Service, Step by Step*.\nThe sink half belongs here, because JSON follows the same two rules as the collections. `>` replaces an array target's items;\n`>>` adds to them; `collect as JSON` makes a fresh array. The records are turned to JSON by `$$`, the serialising operator,\nwhich the record asks for with `default operator $$`:\n\n```ek9\n#!ek9\ndefines module book.vol2.streams.jsonsink\n\n  defines constant\n    LARGE_ORDER <- 100.0\n\n  defines record\n    Order\n      customer <- String()\n      product <- String()\n      amount <- Float()\n\n      Order() as pure\n        ->\n          customer as String\n          product as String\n          amount as Float\n\n        this.customer :=? String(customer)\n        this.product :=? String(product)\n        this.amount :=? Float(amount)\n\n      default operator $$\n      default operator ?\n\n  defines function\n\n    isLarge() as pure\n      -> order as Order\n      <- rtn as Boolean: order.amount >= LARGE_ORDER\n\n    asJson() as pure\n      -> order as Order\n      <- rtn as JSON: $$order\n\n  defines program\n\n    OrdersAsJson()\n      stdout <- Stdout()\n\n      orders <- [Order(\"ada\", \"keyboard\", 45.0), Order(\"bob\", \"monitor\", 220.0), Order(\"cy\", \"laptop\", 999.0)]\n\n      report <- JSON().array()\n      cat orders | filter by isLarge | map with asJson >> report\n      stdout.println(`after >>: ${report}`)\n\n      cat orders | reject by isLarge | map with asJson > report\n      stdout.println(`after >: ${report}`)\n\n      everything <- cat orders | map with asJson | collect as JSON\n      stdout.println(everything.prettyPrint())\n```\n\n```text\nafter >>: [{\"customer\":\"bob\",\"product\":\"monitor\",\"amount\":220.0},{\"customer\":\"cy\",\"product\":\"laptop\",\"amount\":999.0}]\nafter >: [{\"customer\":\"ada\",\"product\":\"keyboard\",\"amount\":45.0}]\n[ {\n  \"customer\" : \"ada\",\n  \"product\" : \"keyboard\",\n  \"amount\" : 45.0\n}, {\n  \"customer\" : \"bob\",\n  \"product\" : \"monitor\",\n  \"amount\" : 220.0\n}, {\n  \"customer\" : \"cy\",\n  \"product\" : \"laptop\",\n  \"amount\" : 999.0\n} ]\n```\n\nThe target's shape decides what pouring means. Into an unset or array target the stream collects; into an object target each\nstreamed object is merged in; a non-object poured into an object, or anything poured into a single JSON value, is invalid,\nleaves the target unset, and later items do not revive it (`ek9 -h JSON`). That last case is the cost: a JSON sink does not\nraise an error when the shapes disagree, it goes unset, so the habit is to check the result with `?` before using it.\n\n## async is a stage, not a thread\n\nPut `async` in a pipeline whose elements are functions and each one is called concurrently. The syntax is all this chapter\nneeds; *Concurrency, Safely* is where the safety rules for what those functions may share live.\n\n```ek9\n#!ek9\ndefines module book.vol2.streams.async\n\n  defines function\n\n    priceLookup() as abstract\n      <- rtn as String?\n\n    lookupKeyboard() is priceLookup\n      <- rtn <- \"keyboard 45.0\"\n\n    lookupMonitor() is priceLookup\n      <- rtn <- \"monitor 220.0\"\n\n    lookupMouse() is priceLookup\n      <- rtn <- \"mouse 15.5\"\n\n    lookupLaptop() is priceLookup\n      <- rtn <- \"laptop 999.0\"\n\n  defines program\n\n    AsyncLookups()\n      stdout <- Stdout()\n      lookups <- [lookupKeyboard, lookupMonitor, lookupMouse, lookupLaptop]\n\n      stdout.println(\"in completion order:\")\n      cat lookups | async > stdout\n\n      stdout.println(\"sorted after async:\")\n      cat lookups | async | sort > stdout\n\n      stdout.println(\"async then head 2, then sorted:\")\n      cat lookups | async | head 2 | sort > stdout\n```\n\n```text\nin completion order:\nmouse 15.5\nlaptop 999.0\nmonitor 220.0\nkeyboard 45.0\nsorted after async:\nkeyboard 45.0\nlaptop 999.0\nmonitor 220.0\nmouse 15.5\nasync then head 2, then sorted:\nkeyboard 45.0\nmonitor 220.0\n```\n\nResults come out in the order the calls *complete*, not the order they arrived, so the first block is not stable. Three more\nruns of the same program printed this as their first block:\n\n```text\nmouse 15.5\nkeyboard 45.0\nlaptop 999.0\nmonitor 220.0\n```\n\n```text\nmouse 15.5\nlaptop 999.0\nkeyboard 45.0\nmonitor 220.0\n```\n\n```text\nkeyboard 45.0\nmonitor 220.0\nlaptop 999.0\nmouse 15.5\n```\n\nIf you need an order, put it back with `sort`, as the second block does; it was the same on every run. The third block\nlooks deterministic and is not a race at all: with only `map`, `call` or `tee` between `async` and `head N`, just N calls are\nstarted (`ek9 -h async`), so you get the first two in list order, not the first two to finish. A `filter` between them keeps a\nwider window.\n\n## What the compiler measures\n\nVolume 1 said pipelines replace the loops that needed `break` and `continue`. The compiler can say what that buys, because\nit scores every function. The same job written both ways, titles by authors with at least three books after a cut-off year:\n\n```ek9\ntitlesByLoop()\n  -> books as List of Book\n  <- rtn <- List() of String\n\n  for candidate in books\n    if candidate.year > ERA_CUTOFF\n      count <- Integer(0)\n      for other in books\n        if other.author == candidate.author\n          if other.year > ERA_CUTOFF\n            count++\n      if count >= MINIMUM_BOOKS\n        if not (rtn contains candidate.title)\n          rtn += candidate.title\n```\n\n```ek9\ntitlesByPipeline() as pure\n  -> books as List of Book\n  <-\n    rtn as List of String: cat books\n      | filter by isModern\n      | sort by byAuthor\n      | group by authorOf\n      | filter by hasEnoughBooks\n      | flatten\n      | map with titleOf\n      | uniq\n      | sort\n      | collect as List of String\n```\n\nBoth are in a test project that asserts they agree. Run with `ek9 -t6`, which writes an HTML report, each function carries\nthe figures the compiler computed. These are copied from that report:\n\n```text\ntitlesByLoop()         cyclomatic 13, cognitive 22, nesting depth 5\ntitlesByPipeline()     cyclomatic 14, cognitive 0, nesting depth 0\nisModern()             cyclomatic 2, cognitive 0, nesting depth 0\nbyAuthor()             cyclomatic 2, cognitive 0, nesting depth 0\nauthorOf()             cyclomatic 1, cognitive 0, nesting depth 0\nhasEnoughBooks()       cyclomatic 2, cognitive 0, nesting depth 0\ntitleOf()              cyclomatic 1, cognitive 0, nesting depth 0\n```\n\nRead the table precisely, because the claim it supports is narrower than \"pipelines are simpler\". **Cognitive complexity and\nnesting fall to zero. Cyclomatic complexity does not fall**: it rose from 13 to 14, since every stage is a path. The loop is\nharder to hold in your head; the pipeline has more things to count. The compiler limits each: cyclomatic 45 for a function\n(E11010), cognitive 35 (E11021) and nesting 6 (E11011) (`ek9 -h complexity`). Written out in full, with a second scan of the books to\ncollect the titles, the loop form stops compiling:\n\n```text\nEK9     : Error   : E11011: 'titlesByLoop' on line 28 position 4: Nesting depth of 7 exceeds maximum of 6: excessive nesting - extract function\n             See: ek9 -h E11011\n           forAI: qualityMetrics.nestingDepth\n```\n\nThe five small functions beside the pipeline each score almost nothing, which is the shape the limits steer you towards:\nmany tiny named functions, one pipeline to say how they combine.\n\n## The cost\n\nA pipeline can be too clever. Nine stages on a line each of which is a function you have to go and find is harder to read\nthan the loop it replaced, and the compiler's scores will not tell you: the pipeline above scores zero cognitive complexity\nand is still at the edge of what a reader takes in at once. A workable limit is the length at which you would have\nnamed an intermediate variable in the loop; past that, split the pipeline and name the halves. You also pay in small functions. Every verb wants a function, so a pipeline of seven stages is seven\ndeclarations, where a lambda-heavy Java stream puts the logic inline; the declarations are where the tests and the names\nlive, but they are more typing. And the safety is partial: `>` is all or nothing, `>>` into what you read is refused, and\n`group` without a `sort` is refused, but `async` ordering is yours to restore and a JSON sink goes quietly unset when the shapes\ndisagree. What the rules buy is that the failures you would find only at run time in another language, a list modified while\nyou read it, groups that are not groups, are compile errors here.\n","examples":["books/ek9-in-depth/ch28-stream-pipelines-in-depth/AsyncLookups.ek9","books/ek9-in-depth/ch28-stream-pipelines-in-depth/JsonSink.ek9","books/ek9-in-depth/ch28-stream-pipelines-in-depth/OrderPipelines.ek9","books/ek9-in-depth/ch28-stream-pipelines-in-depth/SinkReplaceAppend.ek9","books/ek9-in-depth/ch28-stream-pipelines-in-depth/complexity/ProlificAuthors.ek9","books/ek9-in-depth/ch28-stream-pipelines-in-depth/complexity/dev/tests.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"The Dispatcher","url":"https://ek9.io/books/ek9-in-depth/the-dispatcher.html","markdown":"# The Dispatcher\n\n*Abstract Types, Subtypes and Polymorphism* in Volume 1 said that when behaviour has to depend on the concrete type, EK9 has\nthe **dispatcher**: a method that selects its behaviour from the actual type of its arguments, with the compiler checking\nthat every case is covered. It called that a topic for the second volume. The sentence needs one correction before it is\nuseful: the compiler checks every case only where it is told the whole set of cases, and says so when it cannot. This\nchapter is about what a dispatcher checks, what it does not, and why.\n\nIf you know the visitor pattern from Java or C++, the dispatcher is its replacement with the boilerplate removed: no\n`accept` method on every type, no interface with one `visit` per class. If you know Rust or Scala's `match`, or Java's sealed\n`switch`, it is the same idea with the cases written as overloads. Clojure's multimethods route on run-time values too, and find a missing or ambiguous case when the call is made. EK9's\nchecks before the program runs, and the check is the point.\n\n## Routing on what the value is\n\nA dispatcher is a method in a class, marked `dispatcher`, with one or two parameters. Beside it are ordinary methods of the\nsame name, the **handlers**, each taking a narrower type. A call is routed to the handler for the argument's *run-time*\ntype; if no handler fits, the dispatcher's own body runs, as the entry point of last resort.\n\n```ek9\n#!ek9\ndefines module book.vol2.dispatcher.shapes\n\n  defines class\n\n    Shape as abstract\n      name() as pure abstract\n        <- rtn as String?\n\n      default operator ?\n\n    Ellipse is Shape as open\n      override name() as pure\n        <- rtn as String: \"ellipse\"\n\n    Circle is Ellipse\n      override name() as pure\n        <- rtn as String: \"circle\"\n\n    Rectangle is Shape\n      override name() as pure\n        <- rtn as String: \"rectangle\"\n\n    Triangle is Shape\n      override name() as pure\n        <- rtn as String: \"triangle\"\n\n    Renderer\n\n      render() as pure dispatcher\n        -> shape as Shape\n        <- rtn as String: `outline of a ${shape.name()}`\n\n      render() as pure\n        -> ellipse as Ellipse\n        <- rtn as String: `smooth curve: ${ellipse.name()}`\n\n      render() as pure\n        -> rectangle as Rectangle\n        <- rtn as String: `four edges of a ${rectangle.name()}`\n\n    Intersector\n\n      intersect() as pure dispatcher\n        ->\n          first as Shape\n          second as Shape\n        <- rtn as String: `${first.name()} and ${second.name()}: general case`\n\n      intersect() as pure\n        ->\n          first as Circle\n          second as Circle\n        <- rtn as String: \"two circles: compare centres and radii\"\n\n      intersect() as pure\n        ->\n          first as Circle\n          second as Rectangle\n        <- rtn as String: \"circle then rectangle: nearest edge to centre\"\n\n      intersect() as pure\n        ->\n          first as Rectangle\n          second as Rectangle\n        <- rtn as String: \"two rectangles: compare edges\"\n\n  defines program\n\n    Dispatching()\n      stdout <- Stdout()\n\n      renderer <- Renderer()\n      shapes as List of Shape: [Circle(), Ellipse(), Rectangle(), Triangle()]\n      for shape in shapes\n        stdout.println(renderer.render(shape))\n\n      intersector <- Intersector()\n      left as Shape: Circle()\n      right as Shape: Rectangle()\n      stdout.println(intersector.intersect(left, left))\n      stdout.println(intersector.intersect(left, right))\n      stdout.println(intersector.intersect(right, left))\n      stdout.println(intersector.intersect(right, right))\n      stdout.println(intersector.intersect(Triangle(), left))\n```\n\n```text\nsmooth curve: circle\nsmooth curve: ellipse\nfour edges of a rectangle\noutline of a triangle\ntwo circles: compare centres and radii\ncircle then rectangle: nearest edge to centre\nrectangle and circle: general case\ntwo rectangles: compare edges\ntriangle and circle: general case\n```\n\nEvery variable the program dispatches on has the static type `Shape`; the `for` loop's `shape` is one, and `left` and `right`\nare declared as one. Nothing in the call says which handler runs. The first four lines are the single-argument case, and\nthey show the fallback in both directions. A `Circle` has no handler of its own, so it goes to the nearest handler up the\nhierarchy, the one for `Ellipse`. A `Triangle` has none anywhere up its hierarchy but the entry point, so the entry point\nruns. The last five are the two-argument case. `intersect(left, right)` is a `Circle` then a `Rectangle` and has a handler;\n`intersect(right, left)` is the same two shapes the other way round and has none, so it falls to the general case. **Argument\norder is part of the route.**\n\nThere is no cast anywhere in that program. The generated routing compares each argument's run-time class against the\nhandler types and calls the handler with the argument as that type, a conversion the comparison has just justified. That is\nthe correction to the Java habit: where you would write `if (shape instanceof Circle c)`, you declare a handler instead,\nand the type test and the conversion are the compiler's to generate and to get right.\n\n## When two handlers fit equally\n\nThe nearest-type rule has one hole, and the compiler refuses to leave it open. A class that takes two traits is at the same\ndistance from a handler for each of them:\n\n```ek9\nDuck is Animal with trait of Flyable, Swimmable\n  override name() as pure\n    <- rtn as String: \"duck\"\n\n  default operator ?\n```\n\nWith handlers for `Flyable` and `Swimmable` and none for `Duck`, a call with a `Duck` would have two equally good targets.\nThe program does not compile:\n\n```text\nEK9     : Error   : E05230: 'describe' on line 42 position 6: type 'Duck' matches 2 handlers at equal cost in dispatcher 'public String <- describe(animal as Animal)': 'public String <- describe(flyer as Flyable)' (cost 0.10) on line 46 in 'ambiguousDispatch.ek9', 'public String <- describe(swimmer as Swimmable)' (cost 0.10) on line 50 in 'ambiguousDispatch.ek9' dispatcher has ambiguous handler resolution for reachable type\n             See: ek9 -h E05230\n```\n\nThe message names the dispatcher, the type, both handlers and their costs. This is checked at declaration, not at the call:\nthe ambiguity exists in the hierarchy whether or not anyone ever passes a `Duck`. A handler for `Duck` itself costs nothing\nand wins; `ek9 -h E05230` lists that and a bridge trait that combines the two as the fixes. The cost of the rule is that you\ncannot leave the hierarchy ambiguous and hope: if you add a multi-trait class, every dispatcher over its traits stops\ncompiling until you say which handler wins. What it buys is that a call never lands on a handler you did not choose.\n\n## Exhaustiveness belongs to `allow only`\n\nNow the correction to Volume 1. In the shapes program the `Triangle` fell to the entry point silently. That is legitimate\nthere, because `Shape` is an open hierarchy and a handler for every future shape cannot be demanded. Where the set of cases\n*is* closed, EK9 lets you say so, with `allow only` on the base type, and the dispatcher over it becomes exhaustive:\n\n```ek9\nPayment allow only Card, Cash\n  amount() as pure abstract\n    <- rtn as Money?\n```\n\n```ek9\ncharge() as pure dispatcher\n  -> payment as Payment\n  <- rtn as String: `no specific handler: ${payment.amount()}`\n\ncharge() as pure\n  -> card as Card\n  <- rtn as String: `card payment of ${card.amount()}`\n\ncharge() as pure\n  -> cash as Cash\n  <- rtn as String: `cash payment of ${cash.amount()}`\n```\n\nRun as a whole, the program prints what you would expect:\n\n```text\ncard payment of 10.00#GBP\ncash payment of 5.00#GBP\n```\n\nTake the `Cash` handler away and the compiler names the omission:\n\n```text\nEK9     : Error   : E05260: 'charge' on line 38 position 6: on sealed 'Payment' is missing handlers for: Cash: dispatcher on sealed type must have handlers for all permitted types\n             See: ek9 -h E05260\n```\n\nThe compiler's own help for that code makes the comparison this chapter started with: it is exhaustiveness checking \"similar\nto Java's sealed switch or Kotlin's sealed when\". It cuts the other way too. Add a third type to the `allow only` list and\nevery dispatcher over `Payment` fails to compile until it has a handler for it. A type outside the list cannot join the family:\n\n```text\nEK9     : Error   : E05240: 'Voucher' on line 24 position 4: 'Voucher' is not in 'Payment' allow only list: type is not permitted to extend/implement this sealed type\n             See: ek9 -h E05240\n```\n\nSo exhaustiveness here is exactly as strong as the seal and no stronger. **On an unsealed base there is no exhaustiveness\ncheck**: a missing handler falls back to the entry point without a word. And even with every handler present, the entry point\nneeds a body. Declare it with no body and it is refused:\n\n```text\nEK9     : Error   : E07120: 'charge' on line 38 position 6: base level implementation must be provided for dispatcher method\n             See: ek9 -h E07120\n           forAI: dispatcherPattern\n```\n\nThat second rule means a call always has somewhere to land, whatever the run-time type turns out to be: a handler if one fits,\nthe base implementation if none does. There is no cast for you to get wrong and no call that reaches nothing.\n\n## The parent's version, on purpose\n\nThe other mechanic Volume 1 pointed here is calling the parent. An override that replaces its parent's behaviour is common;\none that extends it needs to reach the parent's version, and `super.method()` does:\n\n```ek9\noverride describe() as pure\n  <- rtn as String: `${super.describe()} at ${rate}%`\n\noverride monthlyCharge() as pure\n  <- rtn as Money: super.monthlyCharge() * 0.0\n```\n\nRun as a whole, the program builds an `Account` and a `SavingsAccount` that extends it and calls both, once through\nthe subtype and once through a variable typed as the parent:\n\n```text\nAda holds 120.00#GBP\nBob holds 800.00#GBP at 3.5%\nBob holds 800.00#GBP at 3.5%\ncharges: 2.50#GBP and 0.00#GBP\n```\n\nThe third line is the point: seen through an `Account` variable, the override still runs, and it still reaches the parent's\n`describe()` through `super`. The constructor does the same with `super(holder, balance)`. It is ordinary overriding. It\nbelongs in this chapter because it is the other way of letting the concrete type decide, and the one to try first: if the\nbehaviour belongs on the type, give each type its own version and call `super` where it extends the parent's.\n\n## The cost\n\nYou organise behaviour by dispatch instead of by a chain of type tests, and that is a shift in where you look. The logic\nfor one operation is spread across a handler per type rather than gathered in one `if` ladder; the compiler checks the\nspread, but you read it in pieces. The rules are strict where a visitor would be loose. A dispatcher takes one or two\nparameters, not three (E06320). It lives in a class, not a function or a trait (E07810). Its handlers must match its purity,\nboth ways: a pure entry point needs every handler pure, and a non-pure entry point needs none of them pure (E05170). And\nthere is a run-time price. The compiler's bytecode tests describe the generated routing as a table of `getClass()` comparisons\nfor each reachable type, and for two parameters as the Cartesian product of both parameters' types, so the table grows with\nthe product of the hierarchies. This book gives no timings for it; if a dispatcher is on a hot path, measure it.\n\nWhat those rules buy is that the dispatcher is the one place type-specific behaviour is allowed to live, and the compiler\nchecks the whole of it: no ambiguity the compiler can find (E05230), no gap on a sealed family, no cast anywhere. *The Payoffs: Liskov and Hoare*\nreturns to the substitution rule that makes the fallback to the nearest supertype safe.\n","examples":["books/ek9-in-depth/ch29-the-dispatcher/SealedDispatch.ek9","books/ek9-in-depth/ch29-the-dispatcher/ShapeDispatch.ek9","books/ek9-in-depth/ch29-the-dispatcher/SuperCall.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Write-Your-Own Generic Types and Functions","url":"https://ek9.io/books/ek9-in-depth/write-your-own-generic-types-and-functions.html","markdown":"# Write-Your-Own Generic Types and Functions\n\n*Using Generics* in Volume 1 ended on a promise: \"*Writing* your own generic types is a topic for the second volume.\" This is\nthat chapter. If you write Java you know the shape of the idea and one of its limits, because Java's generics are erased: the\nbody of `List<T>` is compiled once, `T` is `Object` underneath, and a method that wants `a + b` on a `T` simply cannot be\nwritten. If you write C++ you know the other extreme, a template that is checked only when something instantiates it. EK9 sits\nbetween the two. A generic is a template the compiler instantiates for each type you give it, and it checks what it can in the\ntemplate and the rest at the instantiation, where it tells you which operator or constructor the type argument lacks. Generic\n*types* and generic *functions* have equal standing; this chapter writes both, and ends with the constrained types of Volume\n1 built on something other than an `Integer`.\n\n## A generic type\n\nA bounded least-recently-used cache is the smallest realistic generic type: it is written once over a key type and a value\ntype, and it needs to compare, store and evict without knowing either. `LruCache of type (K, V)` keeps a `Dict` of entries and\na `List` that records recency, oldest first.\n\n```ek9\n#!ek9\ndefines module book.generics.lrucache\n\n  defines constant\n    DEFAULT_CAPACITY <- 3\n\n  defines class\n\n    LruCache of type (K, V)\n      capacity as Integer: DEFAULT_CAPACITY\n      entries as Dict of (K, V): Dict()\n      recency as List of K: List()\n\n      default LruCache()\n\n      LruCache()\n        ->\n          key as K\n          item as V\n\n        entries += DictEntry(key, item)\n        recency += key\n\n      limit()\n        -> size as Integer\n        capacity: size\n\n      put()\n        ->\n          key as K\n          item as V\n\n        touch(key)\n        entries -= key\n        entries += DictEntry(key, item)\n        if length recency > capacity\n          oldest as K: recency.getOrDefault(0, K())\n          entries -= oldest\n          recency -= oldest\n\n      get()\n        -> key as K\n        <- rtn as Optional of V: Optional()\n        if entries contains key\n          touch(key)\n          rtn: Optional(entries.getOrDefault(key, V()))\n\n      keys() as pure\n        <- rtn as List of K: recency\n\n      private touch()\n        -> key as K\n        recency -= key\n        recency += key\n\n      default operator ?\n\n  defines program\n\n    CacheDemo()\n      stdout <- Stdout()\n\n      prices <- LruCache(\"apple\", 0.5)\n      prices.limit(2)\n      prices.put(\"pear\", 0.7)\n      if found <- prices.get(\"apple\")\n        stdout.println(`apple: ${found.get()}`)\n      prices.put(\"plum\", 0.9)\n      stdout.println(`keys, oldest first: ${prices.keys()}`)\n      stdout.println(`pear still cached: ${prices.get(\"pear\")?}`)\n\n      squares <- LruCache() of (Integer, Integer)\n      for n in 1 ... 6\n        squares.put(n, n * n)\n      stdout.println(`keys, oldest first: ${squares.keys()}`)\n      if square <- squares.get(5)\n        stdout.println(`5 squared: ${square.get()}`)\n```\n\nIt prints:\n\n```text\napple: 0.5\nkeys, oldest first: [\"apple\", \"plum\"]\npear still cached: false\nkeys, oldest first: [4, 5, 6]\n5 squared: 25\n```\n\nTwo instantiations appear. `LruCache(\"apple\", 0.5)` lets the compiler infer `(String, Float)` from the arguments of the\ninferring constructor, and `LruCache() of (Integer, Integer)` names the types, as `List() of String` does in Volume 1. Each\nis its own concrete type with its own checking; there is no shared erased body. `K()` and `V()` build the no-argument instance of\nwhatever the parameter becomes, which for `String` is the unset `String`; in `get` that never matters, because the lookup is\nprotected by a `contains` check.\n\n### Exactly two constructors\n\nA generic type declares two constructors and no others: the no-argument one, and the *inferring* one, which takes one\nparameter per type parameter, in order. That is why the capacity is set by the method `limit` and not by a constructor\nargument. A type with only the inferring constructor is refused:\n\n```ek9\n      Pair()\n        ->\n          newKey as K\n          newItem as V\n        key: newKey\n        item: newItem\n```\n\n```text\nEK9     : Error   : E06040: 'Pair' on line 5 position 4: a generic type requires 2 constructors, default and inferred type\n             See: ek9 -h E06040\n```\n\nA constructor with the wrong number of parameters, or the right number of the wrong types, is refused too:\n\n```ek9\n      Cache()\n        -> size as Integer\n        entries := Dict()\n```\n\n```text\nEK9     : Error   : E06030: 'Cache' on line 10 position 6: type is generic, but for type inference to work; the number of generic and constructor parameters must be the same\n             See: ek9 -h E06030\n```\n\n```ek9\n      Ring()\n        -> size as Integer\n        slots += T()\n```\n\n```text\nEK9     : Error   : E06050: 'size' on line 11 position 11: wrt: 'size': 'Integer' is not 'T': a generic type requires correct constructor argument to match parametric types (and order)\n             See: ek9 -h E06050\n```\n\nThis is the first of the costs. In Java a generic class has as many constructors as you like, and `new LruCache<>(capacity)` is\nthe natural way to configure one. Here the constructors exist so that the compiler can infer the type arguments from a call,\nand that job needs them to have a fixed shape; anything else you want to say about construction goes in a method.[^constructors]\n\n### Inside a template, every name is typed\n\nVolume 1's chapters, and the primer *Where Volume 1 Left You*, use `<-` to declare a name and let the compiler infer its type. Inside a generic\ntype or function that form is not available, for fields and for local variables alike:\n\n```ek9\n      capacity <- DEFAULT_CAPACITY\n      entries <- List() of T\n```\n\n```text\nEK9     : Error   : E06070: 'capacity' on line 9 position 6: type inference is not supported within generic/template type/functions\n             See: ek9 -h E06070\nEK9     : Error   : E06070: 'entries' on line 10 position 6: type inference is not supported within generic/template type/functions\n             See: ek9 -h E06070\n```\n\nWrite `capacity as Integer: DEFAULT_CAPACITY` and `entries as Dict of (K, V): Dict()`, as `LruCache` does. The ban reaches into\na dynamic function written inside a generic body, which is where it surprises people:\n\n```ek9\n      byTen as scaler: () is scaler as function\n        product <- amount * 10\n        rtn: product\n      rtn: byTen(4)\n```\n\n```text\nEK9     : Error   : E06070: 'product' on line 11 position 6: type inference is not supported within generic/template type/functions\n             See: ek9 -h E06070\nEK9     : Error   : E06070: 'product' on line 22 position 8: type inference is not supported within generic/template type/functions\n             See: ek9 -h E06070\n```\n\n(The first line of that output is the same rule met in a plain function, `product <- item * factor`, on line 11 of the same\nfile.) Java's `var`, Kotlin and Rust all infer locals inside generic code, so this is a real divergence, and the reason is the one\nthat makes the rest of this chapter hang together: the body is stamped out once per instantiation, and an inferred type is\na place where two instantiations could quietly mean different things. EK9 asks you to write the type down, in the template,\nonce.\n\n## Constraining what `T` can do\n\nAn unconstrained `T` is an `Any`: you can hold it and pass it, and little else. To call something on it you constrain it.\n`Ledger of type T constrain by Priced` says every `T` must be a `Priced`, which is a trait, and the body may then call\n`price()` on a `T` and compare two of them with `>`.\n\n```ek9\n#!ek9\ndefines module book.generics.ledger\n\n  defines trait\n\n    Priced\n      price() as pure abstract\n        <- rtn as Money?\n\n      operator <=> as pure\n        -> other as Priced\n        <- rtn as Integer: #> price() <=> #> other.price()\n        if rtn == 0\n          rtn: #< price() <=> #< other.price()\n\n      operator #? as pure\n        <- rtn as Integer: #?price()\n\n  defines class\n\n    Ticket with trait of Priced\n      fare <- Money()\n\n      default Ticket() as pure\n\n      Ticket() as pure\n        -> amount as Money\n        fare :=? amount\n\n      override price() as pure\n        <- rtn as Money: fare\n\n      default operator ?\n\n    Meal with trait of Priced\n      cost <- Money()\n\n      default Meal() as pure\n\n      Meal() as pure\n        -> amount as Money\n        cost :=? amount\n\n      override price() as pure\n        <- rtn as Money: cost\n\n      default operator ?\n\n    Ledger of type T constrain by Priced\n      items as List of T: List()\n\n      default Ledger()\n\n      Ledger()\n        -> first as T\n        items += first\n\n      add()\n        -> item as T\n        items += item\n\n      total()\n        <- rtn as Money: 0#GBP\n        for item in items\n          rtn += item.price()\n\n      dearest()\n        <- rtn as Optional of T: Optional()\n        for item in items\n          keep as Boolean: true\n          if rtn?\n            current as T: rtn.get()\n            keep := item > current\n          if keep\n            rtn: Optional(item)\n\n      default operator ?\n\n  defines program\n\n    PricedLedgers()\n      stdout <- Stdout()\n\n      tickets <- Ledger(Ticket(45#GBP))\n      tickets.add(Ticket(12#GBP))\n      stdout.println(`tickets total: ${tickets.total()}`)\n\n      meals <- Ledger() of Meal\n      meals.add(Meal(9#GBP))\n      meals.add(Meal(31#GBP))\n      meals.add(Meal(18#GBP))\n      stdout.println(`meals total: ${meals.total()}`)\n      if dearest <- meals.dearest()\n        stdout.println(`dearest meal: ${dearest.get().price()}`)\n```\n\nIt prints:\n\n```text\ntickets total: 57.00#GBP\nmeals total: 58.00#GBP\ndearest meal: 31.00#GBP\n```\n\n`Ticket` and `Meal` are unrelated classes that share one trait, and `Ledger` works for either. Look at the ordering the trait\ndeclares, because the compiler held it to a standard. The obvious `price() <=> other.price()` is rejected:\n\n```ek9\n      operator <=> as pure\n        -> other as Priced\n        <- rtn as Integer: price() <=> other.price()\n```\n\n```text\nEK9     : Error   : E07188: '<=>' on line 10 position 15: '<=>' on 'Priced' can answer unset for two set values - 'Money' orders only within one currency or unit, so its '<=>' is unset between them (line 12): an ordering - a '<=>' or a comparator function - must order every two set values of its type: it cannot return an unset Integer, nor build its result on a '<=>' (a field's, a super's, a function's) that answers unset for two set values\n             See: ek9 -h E07188\n```\n\nA `Money` orders only within one currency, so its `<=>` is unset between pounds and dollars; and an ordering that is unset\nfor two set values would make `item > current` mean nothing for some ledgers. The compiler proves the trait's ordering is\ntotal before any `Ledger` is built on it. The version in the listing compares the currency first (`#>`) and the amount\nsecond (`#<`), which answers for every pair.\n\nA constraint also puts demands on the type argument. If a body builds a `T` from another, the type argument must have a\nconstructor of exactly that signature; and when the constraining type declares constructors, a type argument has to offer them.\nA `Weight` that is an `Amount` but lacks the copy constructor `Amount` declares:\n\n```ek9\n    sum() of type T constrain by Amount\n      ->\n        first as T\n        second as T\n      <- rtn as Amount: first + second\n```\n\n```text\nEK9     : Error   : E06130: 'sum' on line 50 position 20: wrt constraining type 'Amount' and parameterizing type 'Weight', constructor 'Weight(Amount)' is required: constraining type constructors must exist on parameterizing type\n             See: ek9 -h E06130\n```\n\nThe report is at the instantiation (`sum() of Weight`, line 50), not in the template: the template is fine, the type you gave it is\nnot. The same holds for a body that copies, `T(item)`, which needs the type argument's copy constructor:\n\n```ek9\n    Shelf of type T\n      items as List of T: List()\n\n      default Shelf()\n\n      Shelf()\n        -> first as T\n        items += T(first)\n\n      add()\n        -> item as T\n        items += T(item)\n\n      size() as pure\n        <- rtn as Integer: length items\n\n      default operator ?\n```\n\n`Book` here declares `Book() -> other as Book`, and the shelf holds copies, so changing the original does not change the shelf.\nIt prints:\n\n```text\non the shelf: 2\nfirst title: Emma\n```\n\nGive the type a constructor that takes a more general parameter instead (`Book() -> other as Named`) and it is not the\nconstructor the generic calls, and the compiler says exactly that:\n\n```ek9\n    Shelf of type T\n      items as List of T: List()\n\n      default Shelf()\n\n      Shelf()\n        -> first as T\n        items += T(first)\n\n      add()\n        -> item as T\n        items += T(item)\n```\n\n```text\nEK9     : Error   : E50001: 'Shelf' on line 45 position 15: 'public T <- T(item as T)' is used in 'Shelf of type T', but 'Book(Book)' is not defined in 'Book' - the generic calls exactly that constructor, and 'public Book <- Book(other as Named)' is not it: not resolved\n             See: ek9 -h E50001\n```\n\n## What a bare `T` demands\n\nLeave `T` unconstrained and use an operator on it, and the template itself compiles. The error arrives when you instantiate\nit for a type that lacks the operator, and it names the operator and the line of the instantiation:\n\n```ek9\n    combine() of type T\n      ->\n        first as T\n        second as T\n      <- rtn as T: first + second\n```\n\n```text\nEK9     : Error   : E07620: 'combine' on line 25 position 23: 'public T <- +(param as T)' is used in 'T <- combine(first as T, second as T) of type T', but '+(Label)' is not defined in 'Label': operator not defined\n             See: ek9 -h E07620\n```\n\n`combine() of Integer` on the line before is accepted; `combine() of Label` is refused because `Label` has no `+`. That is\nC++'s model, and it is the second cost this chapter owns. Rust requires you to state the bound (`T: Add<Output = T>`) and\nreports a missing one at the definition, which finds the mistake earlier and in the author's code; EK9 lets an unconstrained\ntemplate be as permissive as the instantiations turn out to need, and reports at the use. Constraining with `constrain by`\nmoves the check back to the template for everything the constraining type offers.\n\n| Language | Is the bound stated? | A missing operation is reported |\n|---|---|---|\n| Java | Yes, `T extends Bound`; otherwise `T` is an `Object` | in the generic body, at the definition |\n| Rust | Yes, a trait bound is required | in the generic body, at the definition |\n| C++ | No (concepts are optional) | at the instantiation |\n| EK9 | Optional: `constrain by` | at the instantiation, naming the operator and the line |\n\n## Generic functions\n\nA generic function is a named construct of its own, not a method with a type parameter attached. It is declared with `of type`\nand made into a value by naming a type, and the value is then called like any function. `larger() of type T` compares two\nvalues; `transformer() of type T as abstract` has no body, and a dynamic function supplies one where it is instantiated.\n\n```ek9\n#!ek9\ndefines module book.generics.functions\n\n  defines function\n\n    larger() of type T\n      ->\n        a as T\n        b as T\n      <- rtn as T: a > b <- a : b\n\n    transformer() of type T as abstract\n      -> item as T\n      <- rtn as T?\n\n  defines program\n\n    GenericFunctionDemo()\n      stdout <- Stdout()\n\n      largerInteger <- larger() of Integer\n      stdout.println(`larger of 21 and 42: ${largerInteger(21, 42)}`)\n\n      largerString <- larger() of String\n      stdout.println(`larger of pear and apple: ${largerString(\"pear\", \"apple\")}`)\n\n      shout <- () is transformer of String as function\n        rtn: item.upperCase() + \"!\"\n      stdout.println(shout(\"hello\"))\n\n      doubled <- () is transformer of Integer as function\n        rtn: item * 2\n      stdout.println(`doubled: ${doubled(33)}`)\n```\n\nIt prints:\n\n```text\nlarger of 21 and 42: 42\nlarger of pear and apple: pear\nHELLO!\ndoubled: 66\n```\n\n`larger() of Integer` and `larger() of String` are two functions made from one template; `a > b` is checked for each when it is\nmade. The two `() is transformer of ... as function` lines are dynamic functions that implement the abstract template for\n`String` and for `Integer`; *Dynamic Functions and Classes* is the chapter on how they capture. Because a generic function is a\nvalue, it can be passed to a stream stage or stored, which Java's method-level generics cannot be. The family a made function\nbelongs to depends on its shape, and *Functions as Values: the Type Hierarchy* is about that.\n\nA template can also use a `from ... to` range over its `T`. A range needs `<=>`, a copy constructor and `++` on the type, so it\nworks for `Integer`, `Character` and `Date`:\n\n```ek9\n#!ek9\ndefines module book.generics.range\n\n  defines function\n\n    countFromTo() of type T\n      ->\n        from as T\n        to as T\n      <- rtn as Integer: 0\n\n      for step in from ... to\n        rtn++\n\n  defines program\n\n    RangeOverT()\n      stdout <- Stdout()\n      countIntegers <- countFromTo() of Integer\n      stdout.println(`1 to 5: ${countIntegers(1, 5)}`)\n      countCharacters <- countFromTo() of Character\n      stdout.println(`a to e: ${countCharacters('a', 'e')}`)\n      countDates <- countFromTo() of Date\n      stdout.println(`March 2026: ${countDates(2026-03-01, 2026-03-31)}`)\n```\n\nIt prints:\n\n```text\n1 to 5: 5\na to e: 5\nMarch 2026: 31\n```\n\nand is refused for a `String`, which has no `++`:\n\n```ek9\n    countFromTo() of type T\n      ->\n        from as T\n        to as T\n      <- rtn as Integer: 0\n      for step in from ... to\n        rtn++\n```\n\n```text\nEK9     : Error   : E07620: 'countFromTo' on line 18 position 22: 'public T <- ++()' is used in 'Integer <- countFromTo(from as T, to as T) of type T', but '++()' is not defined in 'String': operator not defined\n             See: ek9 -h E07620\n```\n\n### A list of circles is not a list of shapes\n\nOne more thing a generic type does not do is vary. A `List of Circle` is not a `List of Shape`, even though `Circle` is a\n`Shape`, for the reason Java readers will recognise: if it were, a function holding the `List of Shape` could add a `Square` to\nwhat is really a list of circles.\n\n```ek9\n    countShapes() as pure\n      -> shapes as List of Shape\n      <- rtn as Integer: length shapes\n\n  defines program\n\n    NeverCompiles()\n      stdout <- Stdout()\n      circles <- [Circle(), Circle()]\n      stdout.println(`${countShapes(circles)}`)\n```\n\n```text\nEK9     : Error   : E06270: 'countShapes' on line 25 position 24: found function 'Integer <- countShapes(shapes as List of Shape)' but used with supplied arguments '(List of Circle)' not appropriate: parameter mismatch\n             See: ek9 -h E06270\n           forAI: methodResolution\n```\n\nThe message spells out the instantiated signature, `countShapes(shapes as List of Shape)`, and the argument type. The fix is to\nbuild a `List() of Shape` and add the circles to it. Unlike Java there is no wildcard to say \"a list of some kind of shape\";\nyou convert.\n\n## Constrained types over a record\n\n*Constrained Types* in Volume 1 built `DrivingAge as Integer constrain as >= 16 and <= 100` and showed the two ways to make one:\nthe constructor, which Panics on a breach, and `.of`, which answers unset. The same mechanism works over a record you wrote,\nwith three differences worth knowing before you try it.\n\n```ek9\n#!ek9\ndefines module book.generics.constrainedrecord\n\n  defines type\n\n    PositiveQuadrant as Point constrain as\n      > 0\n\n    Coord as Point\n\n  defines record\n\n    Point\n      x as Integer: Integer()\n      y as Integer: Integer()\n\n      default Point()\n\n      Point()\n        -> other as Point\n        x: Integer(other.x)\n        y: Integer(other.y)\n\n      operator > as pure\n        -> limit as Integer\n        <- rtn as Boolean: x > limit and y > limit\n\n      default operator\n\n  defines program\n\n    ConstrainedRecord()\n      stdout <- Stdout()\n\n      inWindow <- Point()\n      inWindow.x := 5\n      inWindow.y := 7\n      accepted <- PositiveQuadrant().of(inWindow)\n      stdout.println(`accepted: ${accepted} set ${accepted?}`)\n\n      direct <- PositiveQuadrant(inWindow)\n      copied <- PositiveQuadrant()\n      copied :=: direct\n      stdout.println(`copied: ${copied} set ${copied?}`)\n\n      outside <- Point()\n      outside.x := -1\n      outside.y := 3\n      rejected <- PositiveQuadrant().of(outside)\n      stdout.println(`rejected set: ${rejected?}`)\n\n      alias <- Coord(outside)\n      stdout.println(`alias: ${alias}`)\n```\n\nIt prints:\n\n```text\naccepted: Point(x=5, y=7) set true\ncopied: Point(x=5, y=7) set true\nrejected set: false\nalias: Point(x=-1, y=3)\n```\n\nFirst, the constraint cannot name `x` or `y`. It reaches the base only through an *operator* the base declares, so the rule\nthat spans both fields is folded into one: `> 0` calls `Point`'s `>`, which holds when both coordinates exceed the limit.\nSecond, the base's fields start unset (`x as Integer: Integer()`), so the constrained type has an unset state to borrow when\n`.of` refuses a value. Third, a constrained value is not a `Point` and does not expose one: `Point(accepted)` and `accepted.x`\nare both errors.\n\n```ek9\n      accepted <- PositiveQuadrant(inWindow)\n      backToPoint <- Point(accepted)\n      stdout.println(`back: ${backToPoint}`)\n      stdout.println(`x: ${accepted.x}`)\n```\n\n```text\nEK9     : Error   : E50060: 'Point' on line 36 position 21: In relation to type 'Point', and 'Point(PositiveQuadrant)', parameter mismatch. Possible method(s) public Point <- Point(),public Point <- Point(other as Point): method/function not resolved\n             See: ek9 -h E50060\n           forAI: methodResolution\nEK9     : Error   : E50001: 'x' on line 38 position 36: 'x' on 'PositiveQuadrant': not resolved\n             See: ek9 -h E50001\n```\n\nThat is the same fact as in Volume 1 (an `Integer` constrained to an age is not an `Integer`), now over fields. `:=:` between\ntwo constrained values copies, as the third line of output shows, and `Coord as Point` is a plain alias that carries no\nconstraint, which is why `Coord(outside)` accepts `x` of minus one. A constrained type declares no constructors of its own;\nit is built through the base's copy constructor, so there is nothing to chain.\n\n## What it costs\n\nYou pay for generics in three places, and none is hidden. You write every field and local type inside a template, which\nremoves the `<-` of the rest of the language. You cannot give a generic type a constructor of your own shape, so configuration\nmoves into methods. And for a `T` you did not constrain, the compiler's complaint arrives at the line that uses the template,\nnot the line that wrote it, which is a longer walk than Rust asks of you.\n\nWhat those three buy is a template whose every instantiation is an ordinary type, resolved and checked like one you wrote by\nhand: no erased body, and an error message that names the exact operator, constructor and line. A generic\nfunction is a value you can pass, and a constraint is a trait whose ordering the compiler has proved total. When the cost does\nbite, the habit it teaches is the useful one: put the constraint on the template, in `constrain by`, so the check is made where\nthe code is.\n\n[^constructors]: The rule is `ek9 -h E06030`: \"any other way of building the object belongs in a method or function, not a\nconstructor.\" The codes seen here are E06040 (the wrong number of constructors), E06030 (the inferring constructor's parameter\ncount) and E06050 (a parameter that is not the matching type parameter).\n","examples":["books/ek9-in-depth/ch30-generic-types-and-functions/ConstrainedRecord.ek9","books/ek9-in-depth/ch30-generic-types-and-functions/GenericFunctions.ek9","books/ek9-in-depth/ch30-generic-types-and-functions/LruCache.ek9","books/ek9-in-depth/ch30-generic-types-and-functions/PricedLedger.ek9","books/ek9-in-depth/ch30-generic-types-and-functions/RangeOverT.ek9","books/ek9-in-depth/ch30-generic-types-and-functions/Shelf.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Organising a Growing Codebase","url":"https://ek9.io/books/ek9-in-depth/organising-a-growing-codebase.html","markdown":"# Organising a Growing Codebase\n\n*Components* in Volume 1 kept everything in one file and said that \"splitting a project across modules\" was a topic for the\nsecond volume. Your programs are now outgrowing one file, and the first question a Java, Go or Rust programmer asks is where the\nbuild file lives. In Java it is a `pom.xml` or a `build.gradle`, a second language with its own plugins; in Go it is `go.mod`\nand the directory tree; in Rust, `Cargo.toml`. In EK9 it is a block inside one of your source files, and the compiler is the\nonly build tool. This chapter covers how files make a module, how one module reaches another, where the tests go, and a view\nabout comments that the compiler enforces as far as a compiler can.\n\n## One build, many files\n\nCompiling a file compiles exactly that file. A second file is invisible to it, even if both declare the same module, until\nthe file you name carries a `defines package` block with `applyStandardIncludes <- true`, which puts every `.ek9` file under\nits directory into the build. Here is a small inventory project, laid out by what each file is about:\n\n```text\ncatalogue/items.ek9\ndev/inventoryTests.ek9\nmain.ek9\npricing/pricing.ek9\n```\n\nFour files, three folders, two modules. `main.ek9` names the module `book.inventory`, holds the package block and the\nprogram; the record `Item` is in `catalogue/items.ek9`, which declares the *same* module; the pricing rules are a different\nmodule, `book.inventory.pricing`, in their own folder. The folder names mean nothing to the compiler; modules are named by\n`defines module`, never by a path. Here are the files, starting with the one you name:\n\n```ek9\ndefines module book.inventory\n\n  references\n    book.inventory.pricing::priceWithTax\n\n  defines function\n\n    stockLine() as pure\n      -> item as Item\n      <- rtn as String: `${item.name}: ${priceWithTax(item.price)}`\n\n    stockLines() as pure\n      -> items as List of Item\n      <- rtn as List of String: cat items | map with stockLine | collect as List of String\n\n  defines program\n\n    Inventory()\n      stdout <- Stdout()\n      stock <- [Item(\"lamp\", 30#GBP), Item(\"desk\", 120#GBP)]\n      stdout.println(stockLines(stock))\n\n  defines package\n    version <- 1.0.0-0\n    description <- \"A small inventory: one module over two files, plus a pricing module\"\n\n    applyStandardIncludes <- true\n```\n\nThe compiler wrote the package block last when it formatted the file; its position is not significant. The other two files\ndeclare their own modules and nothing else:\n\n```ek9\ndefines module book.inventory\n\n  defines record\n\n    Item\n      name <- String()\n      price <- Money()\n\n      default Item() as pure\n\n      Item() as pure\n        ->\n          itemName as String\n          itemPrice as Money\n\n        name :=? itemName\n        price :=? itemPrice\n\n      default operator ?\n```\n\n```ek9\ndefines module book.inventory.pricing\n\n  defines constant\n    VAT_RATE <- 0.2\n\n  defines function\n\n    priceWithTax() as pure\n      -> net as Money\n      <- rtn as Money: net + (net * VAT_RATE)\n```\n\nRun from the project folder, `ek9 main.ek9` builds and runs the program, and prints:\n\n```text\n[\"lamp: 36.00#GBP\", \"desk: 144.00#GBP\"]\n```\n\n`stockLine` uses `Item` with no `references` entry, because `main.ek9` and `items.ek9` are one module; it needs one for\n`priceWithTax`, because that is another. A `references` block is for other modules. It does not add a file to the build: only\nthe package block does.\n\nLeave the package block out and the files compile one at a time. The error you meet first is for the cross-module reference,\nbecause it is checked before anything else:\n\n```ek9\n  references\n    book.inventory.pricing::priceWithTax\n```\n\n```text\nEK9     : Error   : E03030: 'priceWithTax' on line 5 position 28: 'book.inventory.pricing::priceWithTax' reference does not resolve\n             See: ek9 -h E03030\n```\n\nThe line to read is the one it names, a `references` entry that points at a module the build does not contain. A symbol from\nthe *same* module in a file the build does not contain fails later, as E50001, \"not resolved\". `applyStandardIncludes` takes every file\nit finds; the alternative is `includeFiles`, a list that names each file and silently omits any you forget to add.\n\nA consequence of the build being a block in a source file: the program you run is in the file you name. A file holding only\nthe package block and no program is a legitimate thing to compile and has nothing to run (`ek9: no programs to run`).\n\n### What goes in `dev/`\n\nTests live in a `dev/` folder beside the named file, and the standard includes leave that folder out of a normal build, so\nno test code reaches a deployed program. `ek9 -t main.ek9` builds the project with `dev/` included and runs every `@Test`\nprogram in it. A test is its own module; it names what it tests in a `references` block, as any other module would.\n\nThe package block is needed for exactly one reason: the file you name must reach other source files that are not under\n`dev/`. A project of a single source file with a `dev/` folder beside it needs no package block at all, and the file you\nname need not be called `main.ek9`: `ek9 -t` on that file picks up every program in the `dev/` folder beside it, nested\nfolders included. Add a second source file that the named file uses, and the package block (with `applyStandardIncludes`)\nis what puts it in the build.\n\n```ek9\ndefines module book.inventory.tests\n\n  references\n    book.inventory.pricing::priceWithTax\n    book.inventory::Item\n    book.inventory::stockLine\n    book.inventory::stockLines\n\n  defines program\n\n    @Test\n    PriceWithTaxTest()\n      assert priceWithTax(100#GBP) == 120#GBP\n\n    @Test\n    StockLineTest()\n      assert stockLine(Item(\"lamp\", 30#GBP)) == \"lamp: 36.00#GBP\"\n\n    @Test\n    ItemIsSetTest()\n      assert Item(\"lamp\", 30#GBP)?\n\n    @Test\n    StockLinesTest()\n      stock <- [Item(\"lamp\", 30#GBP), Item(\"desk\", 120#GBP)]\n      assert length stockLines(stock) == 2\n```\n\n```text\nℹ️ Found 4 tests:\n  4 assert (unit tests with assertions)\n\nExecuting 4 tests...\n\n✅ PASS book.inventory.tests::ItemIsSetTest [Assert] (2ms)\n✅ PASS book.inventory.tests::PriceWithTaxTest [Assert] (3ms)\n✅ PASS book.inventory.tests::StockLineTest [Assert] (3ms)\n✅ PASS book.inventory.tests::StockLinesTest [Assert] (5ms)\n\nSummary: 4 passed, 0 failed (4 total)\nTypes: 4 assert\nDuration: 15ms\n```\n\nThe project passes the coverage bar because the program is kept thin: it builds a list and prints one line, and everything\nthat can be tested is a function. *Testing the Compiler Trusts* returns to how coverage is counted; *Packaging and Sharing\nYour Program* shows what happens to a project that cannot meet it.\n\n## How modules reach each other\n\nThe `references` block lists what a module imports, one `module::name` per line, and it must be alphabetically ordered:\n\n```ek9\n  references\n    book.inventory.pricing::priceWithTax\n    book.inventory.audit::auditLine\n```\n\n```text\nEK9     : Error   : E11026: 'book' on line 6 position 4: 'book.inventory.audit::auditLine' should come before 'book.inventory.pricing::priceWithTax' - references must be alphabetically ordered: references not in alphabetical order - reorder for consistency\n             See: ek9 -h E11026\nEK9     : Error   : E03030: 'priceWithTax' on line 5 position 28: 'book.inventory.pricing::priceWithTax' reference does not resolve\n             See: ek9 -h E03030\n```\n\nThe second error is only there because this file is compiled alone, with neither module present. E11026 is one of the\ncompiler's consistency rules rather than a matter of taste, which is the volume's argument in miniature: when ordering is a\ncompile error, a diff of a `references` block is always small, and nobody argues about it in review.\n\nTwo things you would expect a compiler to stop are not stopped. A module reference cycle is legal. These two modules\nreference each other, compile together, and run:\n\n```ek9\ndefines module book.cycle.alpha\n\n  references\n    book.cycle.beta::fromBeta\n\n  defines function\n\n    fromAlpha() as pure\n      <- rtn as String: \"alpha\"\n\n    roundTrip() as pure\n      <- rtn as String: fromBeta()\n\n  defines program\n\n    Cycle()\n      Stdout().println(roundTrip())\n\n  defines package\n    version <- 1.0.0-0\n    description <- \"Two modules that reference each other\"\n    applyStandardIncludes <- true\n```\n\n```ek9\ndefines module book.cycle.beta\n\n  references\n    book.cycle.alpha::fromAlpha\n\n  defines function\n\n    fromBeta() as pure\n      <- rtn as String: `beta then ${fromAlpha()}`\n\n    betaName() as pure\n      <- rtn as String: \"beta\"\n```\n\n```text\nbeta then alpha\n```\n\nAll the files of a build are compiled together, so there is no ordering for a cycle to violate. EK9's cycle errors are about\ntype hierarchies (E05020), dependency injection (E08190) and dependencies between packages; a cycle of modules is a design\nsmell the compiler will not decide for you. What it does measure is coupling: a module that references more than ten other\nmodules is E11016, which counts modules, not types, and the cure its help text gives is a wrapper module that groups the\ndependencies.[^coupling]\n\nThe other is how constants are spread. A module's constants belong in one file, and when they are in three or more files\nof one module the compiler says so. The project is three files of module `book.scattered`, each declaring a constant:\n\n```text\nEK9     : Error   : E11066: 'book' on line 2 position 15: Constants found in 3 files within module 'book.scattered': constants should be consolidated into a single file\n             See: ek9 -h E11066\n```\n\n(The error is reported on the module line of one of the three files; with two files it is allowed, so a module can have its\nconstants beside its main program or in a file of their own.) It is a small rule with a large effect on how fast someone new\nfinds the vocabulary of a module.\n\n## Comments\n\nA comment is the one thing in a program the compiler cannot check. Types, absence, purity, coverage and coupling are all\nverified; a comment can say anything, can go stale the day after it was true, and nothing will ever notice. That puts it\noutside \"if it compiles, it is good\", and it is why EK9 takes a position.\n\n> **A design note.** A program is organised by its constructs. An application wires its components and aspects together, a\n> service is a web service, and classes, functions and constants are exactly that; a `text` construct holds what must be\n> localised, a trait is a conceptual abstraction and a record carries data between parts. Because the construct says what\n> something is and the role it plays, no comment or `@` annotation has to. Meaningful naming is meant to do the rest - EK9\n> refuses a name that says nothing - and the strict semantics of the operators make each one self-explanatory wherever it\n> appears. I have been misled by comments for forty years: a wrong comment is worse than none, because the reader trusts it\n> and the code can no longer correct them. Say what the code does in the code; say *why* in a comment, and only when the\n> reader could not otherwise know. *- Steve*\n\nThe language does most of this by making the code carry the intent. A literal in a comparison must be named (E11064), and a\nliteral repeated three times must be a constant (E11065), so the comment that would have explained a bare number is replaced by a\nname the compiler holds you to:\n\n<!-- listing: fragment -->\n```ek9\nif stock < 5  // reorder when low\n```\n\nbecomes `if stock < REORDER_LEVEL`, as in the primer. A constrained type states a range in a place the compiler enforces,\nwhere a comment would only state it. A `?` on a type, a `pure` on a function and an `assert` in a test are checked claims about\nthe same things that comments make unchecked ones about.\n\nEK9 has four comment forms, and no others:\n\n```ek9\n#!ek9\n<?-\n  The documentation form, written before the construct it describes.\n-?>\ndefines module book.comments\n\n  defines function\n\n    <?-\n      Why this function exists. The compiler checks the lines below; nothing checks this.\n    -?>\n    describe() as pure\n      -> count as Integer\n      <- rtn as String: `${count} item(s)` // a line comment runs to the end of the line\n\n  <!--\n    A block comment: everything in here is ignored.\n  -->\n\n  <!-\n    The second block form, also ignored.\n  -!>\n\n  defines program\n\n    Comments()\n      stdout <- Stdout()\n      stdout.println(describe(3))\n```\n\n```text\n3 item(s)\n```\n\n`//` runs to the end of the line, and is the only form Volume 1 used. `<!-- -->` and `<!- -!>` are block forms; the first is\nthere for people who think in HTML, and the second is the one EK9's own tooling uses to comment lines out. `<?- -?>` is the\ndocumentation form: the grammar marks it as intended to be attached to the source as documentation, and it is the one to use for\na concept or a reason, as the function above does. To the compiler all four are hidden text.\n\nC's `/* */` is not one of the four, deliberately. Written in a file it is a parse error, and the error is helpful about it:\n\n```ek9\n    /* A C-style block comment is not one of EK9's four comment forms. */\n```\n\n```text\nSyntax  : '/* A C-style block comment is not one of EK9's four comment forms. */' on line 6 position 4: extraneous '/* A C-style block comment is not one of EK9's four comment forms. */' expecting valid statement or expression \nUnable to parse source file [cStyleComment.ek9]\n\nHint: 'ek9 -ff cStyleComment.ek9' can repair what stops this file parsing; it never renames anything, and rewrites the file only if the result parses. It would make 1 repair:\n  line 6: a '/* */' comment written as '<!- -!>' - EK9's block comment\n```\n\nThat is a `Syntax` error, not an `E` code, because the file never got as far as the checks that have codes. `ek9 -ff` will make the\nrepair it names.\n\nUse a documentation comment when something about the code cannot be expressed in it: a domain rule, a trade-off, why an odd\nthing is done because a particular edge case bites. Use a block comment for the rare \"this looks strange and is deliberate\".\nDo not use either to narrate a line the reader can already see. The examples in this book follow that rule, which is why they have\nalmost none.\n\n## What it costs\n\nThe build in a source file has a price. You cannot script it: there is no task runner, no plugin point and no way to say \"also\nrun this step\". The package block holds metadata, includes and dependencies, and a Maven user will miss the lifecycle. A folder\nlayout that the compiler ignores means that nothing stops you putting a file in the wrong one; the compiler checks modules and\nreferences, not your tidiness. And a rule like sorted `references` or consolidated constants is a rule you did not choose.\n\nWhat that buys is that every EK9 project builds the same way, and the way is visible in the code it builds: a new reader never\nopens a second file in a second language to learn how the first is assembled. The compiler's checks (sorted references,\nconsolidated constants, coupling, coverage) reach the layout of the project as they reach its functions. Comments are the\nexception that proves the rule, and the volume has argued as far as a compiler can: it cannot check the *why*, so it makes sure\nyou rarely need to write one.\n\n[^coupling]: `ek9 -h E11016` states the threshold (\"10 external modules (11+ triggers error)\") and the wrapper-module\nrefactoring. A skipper who wants the testing side of `dev/` should read *Testing as You Go* in Volume 1.\n","examples":["books/ek9-in-depth/ch31-organising-a-growing-codebase/Comments.ek9","books/ek9-in-depth/ch31-organising-a-growing-codebase/cycle/alpha.ek9","books/ek9-in-depth/ch31-organising-a-growing-codebase/cycle/beta/beta.ek9","books/ek9-in-depth/ch31-organising-a-growing-codebase/cycle/dev/cycleTests.ek9","books/ek9-in-depth/ch31-organising-a-growing-codebase/inventory/catalogue/items.ek9","books/ek9-in-depth/ch31-organising-a-growing-codebase/inventory/dev/inventoryTests.ek9","books/ek9-in-depth/ch31-organising-a-growing-codebase/inventory/main.ek9","books/ek9-in-depth/ch31-organising-a-growing-codebase/inventory/pricing/pricing.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Errors and Exceptions","url":"https://ek9.io/books/ek9-in-depth/errors-and-exceptions.html","markdown":"# Errors and Exceptions\n\n*Making Decisions and Repeating Work* listed exceptions among EK9's ways of controlling flow, \"*when something goes wrong*\",\nand left them for this volume. *Optional and Result* covered the failure you expect; this chapter covers the one you do not.\nIf you write Java, C# or Python you will find `try`, `catch`[^handle], `finally` and `throw` where you expect them, and you will\nwrite your first handler without help. Four things differ, and the rest of the chapter is those four: a `try` has exactly\none `catch` with one parameter, and a family of exceptions is routed by a dispatcher instead of a ladder; a `try` can be\nan expression; the construct that owns a resource closes it, you cannot, and it does so *after* your `catch` and `finally`\nhave run; and there is a third kind of failure, the Panic, that no `catch` can see.\n\n## Which failure is which\n\nRust splits failure into `Result` and `panic!`, and Go into `error` and `panic`. Java splits it into checked and unchecked\nexceptions, and then spends a language's worth of argument on which to use. EK9 splits it three ways, and the split is\nabout who is expected to act on the failure:\n\n| The failure | What you write | Who sees it |\n|---|---|---|\n| One the caller should expect and branch on | `Result` or `Optional`; ignoring one is E11052 | The caller, at the call, in the same block |\n| One the caller cannot sensibly continue past | `throw` an `Exception` | The nearest enclosing `catch`; otherwise the process ends with the exception's exit code |\n| A broken contract: `require`, a constraint violation | A `Panic`, raised by the language | Nothing you can write; the process ends with status 1 |\n\nNothing in a function's signature says what it may throw. There is no `throws` to maintain and no checked exception to\nwrap and rewrap, which is also why the choice between the first two rows is a judgement the compiler cannot make for you.\nThe cost section at the end of the chapter gives a workable way to make it.\n\n## Throwing, and catching in one place\n\nA user exception extends `Exception`, which is closed to extension by default like every EK9 type, so a base you mean to\nextend says `as open`. This till charges a card and can fail three ways: a card it has never heard of, a balance too low,\nand an amount that should not have been asked for at all. The first two are payment failures with details; the third is\na plain `Exception`.\n\n```ek9\n#!ek9\ndefines module book.payments.exceptions\n\n  defines constant\n    goldCard <- \"4111\"\n\n    silverCard <- \"5500\"\n\n    unknownCard <- \"9999\"\n\n  defines class\n\n    PaymentException extends Exception as open\n      cardNumber <- String()\n\n      PaymentException()\n        ->\n          reason as String\n          cardNumber as String\n\n        super(reason)\n        this.cardNumber :=: cardNumber\n\n      cardNumber() as pure\n        <- rtn as String: cardNumber\n\n      default operator ?\n      default operator $\n      default operator $$\n\n    CardDeclined extends PaymentException\n      declineCode <- Integer()\n\n      CardDeclined()\n        ->\n          cardNumber as String\n          declineCode as Integer\n\n        super(\"Card declined\", cardNumber)\n        this.declineCode :=: declineCode\n\n      declineCode() as pure\n        <- rtn as Integer: declineCode\n\n      default operator ?\n      default operator $\n      default operator $$\n\n    InsufficientFunds extends PaymentException\n      shortfall <- Integer()\n\n      InsufficientFunds()\n        ->\n          cardNumber as String\n          shortfall as Integer\n\n        super(\"Insufficient funds\", cardNumber)\n        this.shortfall :=: shortfall\n\n      shortfall() as pure\n        <- rtn as Integer: shortfall\n\n      default operator ?\n      default operator $\n      default operator $$\n\n    Till\n      balances as Dict of (String, Integer): {goldCard: 300, silverCard: 50}\n\n      pay()\n        ->\n          cardNumber as String\n          amount as Integer\n        <- rtn as String: String()\n\n        try\n          rtn: charge(cardNumber, amount)\n        catch\n          -> ex as Exception\n          rtn: handleFailure(ex)\n\n      private charge()\n        ->\n          cardNumber as String\n          amount as Integer\n        <- rtn as String: `charged ${amount} to card ${cardNumber}`\n\n        if amount <= 0\n          throw Exception(`amount must be positive, not ${amount}`)\n        balance <- balances.getOrDefault(cardNumber, Integer())\n        if not balance?\n          throw CardDeclined(cardNumber, 51)\n        if balance < amount\n          throw InsufficientFunds(cardNumber, amount - balance)\n        balances += DictEntry(cardNumber, balance - amount)\n\n      private handleFailure() as dispatcher\n        -> ex as Exception\n        <- rtn as String: `unexpected: ${ex.reason()}`\n\n      private handleFailure()\n        -> ex as PaymentException\n        <- rtn as String: `payment failed on card ${ex.cardNumber()}: ${ex.reason()}`\n\n      private handleFailure()\n        -> ex as CardDeclined\n        <- rtn as String: `card ${ex.cardNumber()} declined with code ${ex.declineCode()}`\n\n      default operator ?\n\n  defines program\n\n    PaymentExceptions()\n      stdout <- Stdout()\n      till <- Till()\n\n      stdout.println(till.pay(goldCard, 120))\n      stdout.println(till.pay(unknownCard, 10))\n      stdout.println(till.pay(silverCard, 80))\n      stdout.println(till.pay(goldCard, 0))\n      stdout.println(till.pay(goldCard, 500))\n```\n\nIt prints:\n\n```text\ncharged 120 to card 4111\ncard 9999 declined with code 51\npayment failed on card 5500: Insufficient funds\nunexpected: amount must be positive, not 0\npayment failed on card 4111: Insufficient funds\n```\n\nRead `pay` first. It has one `try` and one `catch`, and the `catch` takes one parameter typed as `Exception`, the nearest\nsuper type of everything `charge` can throw. It does not choose a response; it hands the exception to `handleFailure`,\nwhich is declared `as dispatcher`:\n\n```ek9\nprivate handleFailure() as dispatcher\n  -> ex as Exception\n  <- rtn as String: `unexpected: ${ex.reason()}`\n\nprivate handleFailure()\n  -> ex as PaymentException\n  <- rtn as String: `payment failed on card ${ex.cardNumber()}: ${ex.reason()}`\n\nprivate handleFailure()\n  -> ex as CardDeclined\n  <- rtn as String: `card ${ex.cardNumber()} declined with code ${ex.declineCode()}`\n```\n\nA dispatcher is the call routed by the *run-time* type of its argument (*The Dispatcher* is the chapter on how). Here that\ngives three outcomes in the output. `CardDeclined` has an overload of its own, and `card 9999 declined with code 51` came\nfrom it. `InsufficientFunds` has none, so the call went to the nearest overload above it, `PaymentException`'s, which is why\ntwo lines read `payment failed on card`. And the plain `Exception` for the zero amount went to the dispatcher's own body,\nthe `unexpected:` line, which is the default for anything no overload names. Add another sub-type of `PaymentException` tomorrow and it\nis routed to the nearest overload above it with no change to `pay`.\n\nThat is the replacement for the catch ladder, and EK9 refuses the ladder rather than discouraging it. A second `catch` is\na syntax error:\n\n```ek9\ncatch\n  -> ex as CardDeclined\n  stdout.println(`declined: ${ex.reason()}`)\ncatch\n  -> ex as Exception\n  stdout.println(`failed: ${ex.reason()}`)\n```\n\n```text\nSyntax  : '\n        ' on line 30 position 11: unexpected '\\n        ' expecting '.' or '::'\nSyntax  : 'indentation' on line 31 position 8: mismatched input indentation expecting valid statement or expression\nSyntax  : '.' on line 32 position 14: mismatched input '.' expecting 'pure', 'as', 'with', 'dispatcher', 'abstract', '(' or newline\nSyntax  : 'dedentation' on line 34 position 0: extraneous dedentation expecting end of file or newline\nUnable to parse source file [.../twoCatches.ek9]\n```\n\nThe message is the parser's, not a teacher's: it reads the second `catch` as a name at the start of an ordinary statement,\nexpects a `.` or `::` after it, and complains about what follows. A `catch` with several parameters, the shape a Java multi-catch suggests,\ngets a plainer message:\n\n```ek9\ncatch\n  ->\n    first as Exception\n    second as Exception\n    third as Exception\n  stdout.println(first.reason())\n```\n\n```text\nEK9     : Error   : E07850: '->' on line 19 position 8: only a single Exception is supported\n             See: ek9 -h E07850\n```\n\nThere is one first-attempt trap in the hierarchy. An exception sub-type that adds a field inherits `$` and `$$` from\n`Exception`, and the inherited ones were written for the base's fields. Leave the operators out and the compiler says so (E07238):\n\n```ek9\nPaymentException extends Exception as open\n  cardNumber <- String()\n\n  PaymentException()\n    ->\n      reason as String\n      cardNumber as String\n\n    super(reason)\n    this.cardNumber :=: cardNumber\n\n  default operator ?\n```\n\n```text\nEK9     : Error   : E07238: 'PaymentException' on line 6 position 4: 'PaymentException' has 1 field(s) of its own but would inherit '$' from 'Exception', '$$' from 'Exception' - declare 'default operator $', 'default operator $$' (or write the operator): a type that adds fields, concrete or abstract, must declare its own '$', '$$' and ':=:', and its own sameness ('<=>' or '==', with '#?'), where it would inherit one: the inherited operator was written for the super's fields and cannot know these - use 'default operator' for each (or the bare 'default operator') or write one\n             See: ek9 -h E07238\n```\n\nThe three `default operator` lines in `PaymentExceptions` are the fix. The message is long because it states the whole\nrule: a type that adds state declares its own `$`, `$$`, `:=:` and sameness. The operator model behind it is the subject of\n*Operators and Pragmatic Purity, in Full*.\n\n### A narrower catch lets the rest through\n\nThe parameter's type is also a filter. A `catch -> ex as CardDeclined` catches a `CardDeclined` and its sub-types, and any\nother exception travels on to the enclosing `try`, or out of the program. Selective handling exists; what does not exist is\na second clause on the same `try`. Two handlers for two types is two `try` statements, the narrow one inside:\n\n```ek9\nNarrowCatch()\n  stdout <- Stdout()\n  try\n    for amount in [0, -1, 5]\n      try\n        stdout.println(`charged ${charge(amount)}`)\n      catch\n        -> ex as CardDeclined\n        stdout.println(`declined here: ${ex.reason()}`)\n  catch\n    -> ex as Exception\n    stdout.println(`escalated: ${ex.reason()}`)\n```\n\n```text\ndeclined here: nothing to charge\nescalated: amount must not be negative\n```\n\nThe inner `catch` took the `CardDeclined` and the loop went on. The plain `Exception` for `-1` was not its type, so it\nleft the inner `try`, left the loop, and was caught by the outer one; `5` was never charged. Inside any `catch`, `throw ex`\nthrows what you were given on again, for the cases where you want to log a failure where it happened and still let it climb.\n\n## `try` as an expression\n\nWhen the point of a `try` is a value, the `try` can produce it. The returning variable is declared inside the `try`, its\ninitialiser is inside the protected region, and the `catch` assigns it a replacement:\n\n```ek9\n#!ek9\ndefines module book.try.expression\n\n  defines constant\n    fallbackPort <- 8080\n\n  defines function\n\n    portFrom()\n      -> text as String\n      <- rtn as Integer: Integer(text)\n      if not rtn?\n        throw Exception(`not a port number: ${text}`)\n\n  defines program\n\n    TryExpression()\n      -> configured as String\n      stdout <- Stdout()\n\n      port <- try\n        <- rtn as Integer: portFrom(configured)\n      catch\n        -> ex as Exception\n        stdout.println(`using the fallback: ${ex.reason()}`)\n        rtn: fallbackPort\n\n      stdout.println(`listening on ${port}`)\n```\n\nRun it with a good argument and with a bad one:\n\n```text\nlistening on 9090\n```\n\n```text\nusing the fallback: not a port number: oops\nlistening on 8080\n```\n\nKotlin's `try` is an expression for the same reason. The fallback is a named constant, not a literal in the `catch`, because\n`fallbackPort` is a number with a reason. Use this form when the substitute value is a real answer. If the failure is one\nthe caller ought to hear about, you wanted a `Result`.\n\n## Resources the compiler closes\n\nJava has try-with-resources, C# has `using`, Python has `with`. Each exists because a hand-written `close()` is forgotten on\nthe path that is tested least. EK9 goes one step further than closing for you: it will not let you write the close. A\n**closeable** is a type with an `operator close`; a `try` that is handed one owns it and closes it on every exit.[^closeable]\nWriting the close yourself is refused, whichever way you spell it:\n\n```ek9\nCloseStatement()\n  try\n    -> conn <- Connection(\"ledger\")\n    conn.send(\"debit 100\")\n    close conn\n```\n\n```text\nEK9     : Error   : E01094: 'close' on line 28 position 8: 'close' is not a statement in EK9 - closing is generated: declare 'default operator close' (or write 'operator close' for extra work); a local closes through try or its statement\n             See: ek9 -h E01094\n```\n\n```ek9\nCloseCall()\n  try\n    -> conn <- Connection(\"ledger\")\n    conn.send(\"debit 100\")\n    conn.close()\n```\n\n```text\nEK9     : Error   : E81060: 'close' on line 28 position 13: 'Connection.close()': the close operator is never called as a method, 'super.close()' included - make the value a try-with-resources resource; a type's own properties and its super class are closed by its generated close\n             See: ek9 -h E81060\n```\n\nThe first is the statement form, which EK9 does not have. The second is the operator called as a method, and the compiler\ngives its reason: a type's own properties and its super class are closed by its generated close. Opening a closeable into an ordinary local, with no `try`\naround it, is the third refusal:\n\n```ek9\nLocalCloseable()\n  conn <- Connection(\"ledger\")\n  conn.send(\"debit 100\")\n```\n\n```text\nEK9     : Error   : E81056: 'conn' on line 25 position 6: 'conn' (declare it as 'try' then '-> conn <- ...'): a closeable value held in a named local must be a try-with-resources resource\n             See: ek9 -h E81056\n```\n\nSo a closeable lives where a `try` or a holder puts it, and nowhere else. The `operator close` in these examples is\ndeclared `as pure`, because it only prints, and a pure function may print.\n\n### The order, which is not Java's\n\nHere is the order of events in the cases that matter: a body that completes, a body that throws, and a second resource\nthat cannot be opened. Every one has a `catch` and, where it matters, a `finally`.\n\n```ek9\n#!ek9\ndefines module book.resources.order\n\n  defines constant\n    firstLabel <- \"first\"\n\n    secondLabel <- \"second\"\n\n    brokenLabel <- \"broken\"\n\n  defines class\n\n    Connection\n      name <- String()\n\n      Connection()\n        -> label as String\n        if label == brokenLabel\n          throw Exception(`cannot open ${label}`)\n        name := label\n        Stdout().println(`opened ${name}`)\n\n      operator close as pure\n        Stdout().println(`closed ${name}`)\n\n      default operator ?\n\n  defines program\n\n    ResourceOrder()\n      stdout <- Stdout()\n\n      stdout.println(\"--- the body completes, with catch and finally ---\")\n      try\n        ->\n          first <- Connection(firstLabel)\n          second <- Connection(secondLabel)\n        stdout.println(\"body done\")\n      catch\n        -> ex as Exception\n        stdout.println(`catch: ${ex.reason()}`)\n      finally\n        stdout.println(\"finally\")\n\n      stdout.println(\"--- the body throws, with catch and finally ---\")\n      try\n        ->\n          first <- Connection(firstLabel)\n          second <- Connection(secondLabel)\n        throw Exception(\"body failed\")\n      catch\n        -> ex as Exception\n        stdout.println(`catch: ${ex.reason()}`)\n      finally\n        stdout.println(\"finally\")\n\n      stdout.println(\"--- the second resource cannot be opened ---\")\n      try\n        try\n          ->\n            first <- Connection(firstLabel)\n            second <- Connection(brokenLabel)\n          stdout.println(\"never reached\")\n        catch\n          -> ex as Exception\n          stdout.println(`inner catch: ${ex.reason()}`)\n      catch\n        -> ex as Exception\n        stdout.println(`outer catch: ${ex.reason()}`)\n```\n\n```text\n--- the body completes, with catch and finally ---\nopened first\nopened second\nbody done\nfinally\nclosed second\nclosed first\n--- the body throws, with catch and finally ---\nopened first\nopened second\ncatch: body failed\nfinally\nclosed second\nclosed first\n--- the second resource cannot be opened ---\nopened first\nclosed first\nouter catch: cannot open broken\n```\n\nRead the first two blocks against what Java does. In Java the resources are closed *before* `catch` and `finally` run. In\nEK9 the body runs, then the try's own `catch`, then its `finally`, and **then** the resources are closed, last opened first\n(`closed second` before `closed first`), and only then does the exception, if there still is one, leave the `try`. A\n`catch` therefore runs while the resources are still open. If you write from Java intuition you will have this backwards.\n\nThe third block is the other half. A failure while *acquiring* a resource is not handled by the `try` that declares it. The\ninner `catch` printed nothing; `first` was already open, so it was closed, and the exception went to the enclosing `try`.\n\nA holder of closeables does not close them by hand either. A class that keeps closeables in its properties says\n`default operator close`, and the compiler writes the close for it, last property first. This is `Session` from\nthe example that accompanies this chapter, which has its own `Connection` that opens and closes by printing, as the one above does:\n\n```ek9\nSession\n  primary <- Connection(\"primary\")\n  replica <- Connection(\"replica\")\n\n  send()\n    -> message as String\n    Stdout().println(`sending ${message}`)\n\n  default operator ?\n  default operator close\n```\n\n```text\nopened primary\nopened replica\nsending hello\ncaught link dropped\nfinally\nclosed replica\nclosed primary\n```\n\n`session` is the resource; it was closed after `catch` and `finally`, and it closed `replica` before `primary`.\n\n### When the close itself fails\n\nA close can throw. That failure leaves the `try` after the try's own `catch` has run, which has a consequence worth seeing\nbefore it surprises you in production: a `catch` on the same `try` does not see it. It goes to the enclosing `try`, and if\nthe body had already failed, the close failure does not replace the first exception. It is attached to it and read through\n`suppressed()`, as in Java:\n\n```ek9\n#!ek9\ndefines module book.resources.suppressed\n\n  defines class\n\n    Journal\n      name <- String()\n\n      Journal()\n        -> label as String\n        name := label\n\n      post()\n        -> entry as String\n        Stdout().println(`${name} posts ${entry}`)\n\n      operator close as pure\n        throw Exception(`close of ${name} failed`)\n\n      default operator ?\n\n  defines function\n\n    report()\n      -> ex as Exception\n      stdout <- Stdout()\n      stdout.println(`caught: ${ex.reason()}`)\n      for failure in ex.suppressed()\n        stdout.println(`  suppressed: ${failure.reason()}`)\n\n  defines program\n\n    SuppressedClose()\n      stdout <- Stdout()\n\n      stdout.println(\"--- the body completes, the close fails ---\")\n      try\n        try\n          -> journal <- Journal(\"audit\")\n          journal.post(\"debit 100\")\n      catch\n        -> ex as Exception\n        report(ex)\n\n      stdout.println(\"--- the body fails, then the close fails ---\")\n      try\n        try\n          -> journal <- Journal(\"audit\")\n          journal.post(\"debit 100\")\n          throw Exception(\"posting failed\")\n      catch\n        -> ex as Exception\n        report(ex)\n```\n\n```text\n--- the body completes, the close fails ---\naudit posts debit 100\ncaught: close of audit failed\n--- the body fails, then the close fails ---\naudit posts debit 100\ncaught: posting failed\n  suppressed: close of audit failed\n```\n\nThe inner `try` has no `catch` on purpose; the outer one is what receives the close failure. In the second case the\nexception the handler sees is the body's, `posting failed`, and the close failure is in its `suppressed()` list.\n\n### What may not hold a resource\n\nA resource is closed when its `try` ends, so it may not be given to something that keeps it. Here a list outlives the `try`:\n\n```ek9\nremember()\n  ->\n    remembered as List of Handle\n    handle as Handle\n\n  remembered += handle\n\naudit()\n  <- rtn as Integer: 0\n  remembered <- List() of Handle\n  try\n    -> connection <- Connection(\"ledger\")\n    remember(remembered, connection)\n  rtn: length remembered\n```\n\n```text\nEK9     : Error   : E81075: 'connection' on line 43 position 29: 'connection' is closed when its try ends, but it is given to a call that keeps it: a try resource is closed when its try ends, so it must not be given to a call that keeps it - keep the resource inside the try, pass a value taken from it, or make the holder a closeable that owns it\n             See: ek9 -h E81075\n```\n\nThe compiler reads the callee to decide this; `remember` adds its argument to a list the caller holds, so the list would\nhave held a closed connection. The fix is to keep something taken from the resource, a `String` rather than the connection\nitself. The same rule applies to an unnamed closeable passed to a call that may hand it back (E81072), and an exception\nmay not have an `operator close` at all (E81074): an exception is a value carried to a handler, not a resource.\n\n## What a `catch` cannot see\n\nThe third row of the table is the Panic. A failed `require` raises one, and so does breaking a constrained type's range. It\nis not an `Exception`, so no `catch` can name it:\n\n```ek9\ntry\n  stdout.println(`Average: ${averageOf(List() of Integer)}`)\ncatch\n  -> ex as Panic\n  stdout.println(\"cannot get here\")\n```\n\n```text\nEK9     : Error   : E04030: 'ex' on line 21 position 11: wrt 'ex as Panic': type must be of Exception type\n             See: ek9 -h E04030\n```\n\nThe point is not that the compiler is hiding the failure. A Panic means the program's own contract was wrong, and a handler\nthat carries on would be carrying on from a state nobody can describe. Running one shows the shape:\n\n```ek9\ntry\n  averageOf(noScores)\ncatch\n  -> ex as Exception\n  stdout.println(\"a catch never sees a Panic\")\nfinally\n  stdout.println(\"finally still ran\")\n```\n\n```text\nAverage: 6\nAveraging an empty list\nfinally still ran\nException in thread \"main\" Panic: Requirement failed: `not scores.empty()` at ./RequireExit.ek9:9:7: Exit Code: 1\n```\n\nThe `finally` ran; the `catch` did not. The process ended with status 1, and the Panic line carries the file, line and\ncolumn of the `require`.\n\nAn exception nothing catches ends the program too, and its exit code is the program's exit status. `Exception` takes an\noptional exit code, and this program throws one with 3:\n\n```ek9\nloadSettings()\n  -> fileName as String\n  <- rtn as String?\n  if not fileName?\n    throw Exception(\"No settings file named\", 3)\n  rtn: `Loaded ${fileName}`\n```\n\n```text\nLoaded app.properties\nLoading settings with no file name\nCleanup ran before the process ended\nException in thread \"main\" Exception: No settings file named: Exit Code: 3\n```\n\nThe `finally` ran again, then the process ended with status 3. An exception with no code ends the process with status 1.\nThe same status is how a program reports a result to a script when nothing went wrong: a program that returns an `Integer`\nexits with it.\n\n```ek9\n#!ek9\ndefines module book.exit.returned\n\n  defines program\n\n    ReturnedExit()\n      -> rows as Integer\n      <- exitCode as Integer: 0\n      stdout <- Stdout()\n      stdout.println(`rows found: ${rows}`)\n      exitCode: rows == 0 <- 2 : 0\n```\n\nGiven `0` rows it prints `rows found: 0` and exits with status 2; given `7`, it prints `rows found: 7` and exits with 0.\n\n## Exceptions inside a pipeline\n\nA stage is an ordinary function, so an exception thrown in one travels as any other does. Two things can happen to it. A\n`try` around the whole pipeline statement catches it, and the pipeline stops with nothing collected. Or a stage can catch\ninside itself and substitute a value, after which the pipeline carries on:\n\n```ek9\nparsePriceOrZero()\n  -> text as String\n  <- rtn as Integer: 0\n  try\n    rtn: parsePrice(text)\n  catch\n    -> ex as Exception\n    Stdout().println(`skipped: ${ex.reason()}`)\n```\n\n```text\npipeline stopped: not a price: oops\nskipped: not a price: oops\nrecovered: [12, 0, 30, 45]\n```\n\nThe first pipeline stopped at `oops` and collected nothing, which is why the `unreachable:` line never printed. The\nsecond recovered: `skipped:` came out once, and `0` stands in for the price that would not parse. *Stream Pipelines in\nDepth* covers what else a stage can do about a failure, and *Optional and Result, in Depth* is the way to make the failure\na value instead.\n\n## The cost\n\nThree things in this chapter cost you something, and each buys something.\n\nYou cannot choose between `Result` and an exception by looking at the compiler's output, because the compiler does not mind\nwhich you pick. A workable rule is to ask what the caller will do next. If the caller will branch, ask for a `Result`: parsing a\nport number from a form is a thing that fails every day and the caller wants to say so to the user. If the only sensible\nresponse is to give up the operation and report, throw: a till asked to charge a negative amount has been called wrongly.\nThe classic sin is the exception used as control flow, a `try` around a loop to find out when a lookup ran dry, and EK9\ncannot stop you. It can make it clumsier than the alternative, since a `try` carries one `catch` and one parameter.\n\nYou cannot write a catch ladder. Two handlers for two unrelated types means two nested `try` statements, as in\n`NarrowCatch`, or one `catch` handing the exception to a dispatcher, as in `PaymentExceptions`; either is more ceremony than\nJava for the one case where a ladder is exactly what you want. What it buys is that the order of handlers is no longer part\nof the program's meaning, and that adding a sub-type needs no change at any `catch`.\n\nYou cannot close a resource at a moment of your choosing. A closeable lives to the end of the `try` that was handed it, or\nthe end of the holder that owns it, and a design that wants the handle to outlive both has to be shaped around that. What\nit buys is that the leak has no spelling: there is no close to forget and no close to call twice.\n\n> **A design note.** I did not write a warning for a forgotten `close`. I removed the statement from the language, for the\n> reason `break` is gone: a rule that depends on every author remembering it on the failure path is broken on the failure\n> path, which is the path tested least. Here nobody has to remember. The compiler generates the close, on every path, at\n> the end of the `try` or the holder that owns the handle. *- Steve*\n\n## Where this stops\n\nThe compiler checks what it can see in the block you are in: that a `try` has one `catch` with one parameter, that a closeable is owned\nby a `try` or a holder, that nothing closes a resource by hand, and that a resource is not given to something that keeps it.\nIt does not check that an exception is caught anywhere. An uncaught exception ends the program with its exit code, as\n`FatalExit` showed, and nothing in a signature warned the caller it might. Which failure is a `Result` and which a `throw` is\na design decision, and it stays one.\n\n[^handle]: `handle` is a synonym for `catch`; the compiler treats the two alike.\n\n[^closeable]: The closeable that Volume 1 introduced was a file, in *Programs, Input and Output*: `try -> input <- file.input()`\nhands the `try` a reader, and the `try` closes it.\n","examples":["books/ek9-in-depth/ch32-errors-and-exceptions/FatalExit.ek9","books/ek9-in-depth/ch32-errors-and-exceptions/NarrowCatch.ek9","books/ek9-in-depth/ch32-errors-and-exceptions/PaymentExceptions.ek9","books/ek9-in-depth/ch32-errors-and-exceptions/PipelineFailures.ek9","books/ek9-in-depth/ch32-errors-and-exceptions/RequireExit.ek9","books/ek9-in-depth/ch32-errors-and-exceptions/ResourceOrder.ek9","books/ek9-in-depth/ch32-errors-and-exceptions/ReturnedExit.ek9","books/ek9-in-depth/ch32-errors-and-exceptions/SessionClose.ek9","books/ek9-in-depth/ch32-errors-and-exceptions/SuppressedClose.ek9","books/ek9-in-depth/ch32-errors-and-exceptions/TryExpression.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Concurrency, Safely","url":"https://ek9.io/books/ek9-in-depth/concurrency-safely.html","markdown":"# Concurrency, Safely\n\nIn Java the lock and the data it protects are two things joined by a convention: a field is documented as protected by a monitor, and the\nconvention lives in a comment and in the heads of the people who wrote the class. Go has the same arrangement with a\n`sync.Mutex` beside the variable. Rust's `Mutex<T>` is the nearest relative of what follows, because the data sits *inside*\nthe lock and you cannot reach it without taking the lock. EK9 does that, and then does what none of the three does in the compiler: it\nreads your program for lock-ordering cycles and refuses to compile one. This chapter is about the shape that makes that\npossible, the rules the compiler enforces around it, and what it leaves alone.\n\n## What exists, and what does not\n\nThe whole concurrency surface of the language is small, and none of it looks like a thread:\n\n- `MutexLock of T`, a lock that owns a value of type `T`, entered with `enter(...)` or `tryEnter(...)`;\n- `MutexKey of T`, the function `enter` calls while it holds the lock, with the locked value as `lockedItem`;\n- the stream stage `| async`, which runs each stream element on a virtual thread, and `| call`, which runs them on the\n  caller's thread;\n- `Signals`, whose handlers run on the signal dispatcher's thread, and the handlers of `TCP` and `HTTP`, which run on the\n  runtime's threads.\n\nThere is no `Thread`, no executor, no channel, no future or promise, no atomic, no semaphore and no `sleep`; `ek9 -h\nthread` says so: \"no Thread class or manual thread management\". The last bullet is worth reading twice. Code runs concurrently\nbecause the runtime started it somewhere, and the compiler knows every place it does, which is what the rules below are\nbuilt on.\n\n## One lock over one record\n\nHere is the program every concurrency chapter writes: eight workers each make 250 deposits into one shared tally. In Java it\nis a `synchronized` method or an `AtomicLong`. Here the tally is a record, the record sits under one lock\ninside a class, and the only way in is a key.\n\n```ek9\n#!ek9\ndefines module book.concurrency.tally\n\n  defines constant\n    workerCount <- 8\n\n    depositsPerWorker <- 250\n\n  defines record\n\n    Tally\n      deposits <- 0\n      total <- 0\n\n      default operator\n\n  defines class\n\n    Ledger\n      lockedTally <- MutexLock(Tally())\n\n      deposit()\n        -> amount as Integer\n        depositor <- (amount) is MutexKey of Tally as function\n          lockedItem.deposits += 1\n          lockedItem.total += amount\n        require lockedTally.enter(depositor)\n\n      snapshot()\n        <- rtn as Tally: Tally()\n        reader <- (rtn) is MutexKey of Tally as function\n          rtn :=: lockedItem\n        require lockedTally.enter(reader)\n\n      default operator ?\n\n  defines function\n\n    work() as abstract\n      <- rtn as Integer?\n\n  defines program\n\n    SharedTally()\n      stdout <- Stdout()\n      ledger <- Ledger()\n\n      workers <- List() of work\n      for id in 1 ... workerCount\n        worker <- (ledger, id) is work as function\n          for n in 1 ... depositsPerWorker\n            ledger.deposit(id)\n          rtn: id\n        workers += worker\n\n      finished <- cat workers | async | sort | collect as List of Integer\n      stdout.println(`workers finished: ${finished}`)\n      stdout.println(`tally: ${ledger.snapshot()}`)\n```\n\nIt prints:\n\n```text\nworkers finished: [1, 2, 3, 4, 5, 6, 7, 8]\ntally: Tally(deposits=2000, total=9000)\n```\n\nEight runs in a row printed the same two lines, and a race would have shown as a smaller total. The pieces, in the order\nyou meet them:\n\n`lockedTally <- MutexLock(Tally())` is a field with an initialiser, the only place a `MutexLock` may be built. `deposit`\nmakes a key, a dynamic function[^dynamic] that implements `MutexKey of Tally` and takes `amount` in its capture list, and\nhands it to `enter`. While `enter` runs the key it holds the lock; the key sees the record as `lockedItem`; and when the key\nends, however it ends, `enter` releases. There is no unlock to forget and no `try`/`finally` to write. `enter` returns a\n`Boolean`, and `require` insists it was true.\n\n`snapshot` shows how a value gets out. The key captures `rtn` and copies into it with `:=:`; a copy is a new object, so\nnothing outside the lock holds a reference to the locked one. The reason is below.\n\nThe workers are the other half. `| async` takes no function: each element of the stream *is* a zero-argument function, and\nresults arrive in the order the calls *finish*, so the pipeline sorts them; *Stream Pipelines in Depth* has the whole rule.\n\n### Getting a result out of a key\n\nInside a key you carry a result out by mutating a captured variable, and the verb that mutates is `:=:`, not `:`.\nA capture shares the caller's object, not the caller's variable (*Dynamic Functions and Classes* has the rule), so\nreassigning a captured variable with `:` would point only the key's own name at another object, and the caller would\nnever see it. The compiler refuses that version of `hasFunds`:\n\n```ek9\nhasFunds()\n  -> amount as Integer\n  <- rtn as Boolean: false\n  checker <- (amount, rtn) is MutexKey of Integer as function\n    rtn: lockedItem >= amount\n  require lockedBalance.enter(checker)\n```\n\n```text\nEK9     : Error   : E08280: ':' on line 16 position 13: 'rtn': a dynamic function never re-points a variable it captured - a capture is an initial value (read it, and declare a new variable for a new value) or a way back out (copy into it with ':=:', merge with ':~:' or replace with ':^:', which the caller sees); re-pointing changes only the function's own name\n             See: ek9 -h E08280\n```\n\nHad it compiled, the answer would have been `false`: the balance is 100 and the request is for 80, but the `Boolean` the\ncaller holds would never have been touched. The fix is `rtn :=: lockedItem >= amount`, which changes the one object both\nnames share:\n\n```text\nfunds for 80: true\n```\n\nThe compiler also stops the nearby mistake, letting something outside the lock keep an object that lives in it,\nwith E08258 (below).\n\n## You often do not need the lock\n\nThe program above shares one tally because it was written to. Nothing requires the sharing. Each worker can build its own\nsubtotal and *return* it, and the pipeline hands the results to the thread that submitted them:\n\n```ek9\nWorkerTotals()\n  stdout <- Stdout()\n\n  workers <- List() of work\n  for id in 1 ... workerCount\n    worker <- (id) is work as function\n      subtotal <- 0\n      for n in 1 ... depositsPerWorker\n        subtotal += id\n      rtn: subtotal\n    workers += worker\n\n  subtotals <- cat workers | async | sort | collect as List of Integer\n  total <- Integer()\n  cat subtotals > total\n  stdout.println(`subtotals: ${subtotals}`)\n  stdout.println(`total: ${total}`)\n```\n\n```text\nsubtotals: [250, 500, 750, 1000, 1250, 1500, 1750, 2000]\ntotal: 9000\n```\n\nThere is no lock here because there is nothing to lock: `subtotal` belongs to the worker that made it. This is the nearest\nEK9 gets to Go's channels or to message passing, and `ek9 -h MutexLock` recommends it (\"Prefer message-passing when\npossible\"). The chapter's rules are for when you cannot.\n\n## What the compiler refuses\n\nEach rule below is a compile-time error with its own code, and each has a program in this chapter that triggers it.\n\n### The race (E08251)\n\nTake the first program and remove the ledger. Each worker captures the `Tally` itself and writes to it:\n\n```ek9\nworker <- (tally, id) is work as function\n  for n in 1 ... depositsPerWorker\n    tally.deposits += 1\n    tally.total += id\n  rtn: id\nworkers += worker\n```\n\n```text\nEK9     : Error   : E08251: 'tally' on line 31 position 12: mutation of shared state must happen inside MutexLock.enter(...) — wrap the write in a MutexKey body\n             See: ek9 -h E08251\nEK9     : Error   : E08251: 'tally' on line 32 position 12: mutation of shared state must happen inside MutexLock.enter(...) — wrap the write in a MutexKey body\n             See: ek9 -h E08251\n```\n\nTwo conditions meet here: the `tally` is shared, because the creating thread still holds it, and the code writing to it\nruns on another thread. The compiler's own name for the second is \"a concurrent entry point\": the runtime starts the code\non a thread of its own. That covers the functions of a pipeline containing `async` (the workers *and* every other\nstage in it), an HTTP service operation (each request has its own thread), a TCP or `Signals` handler, and everything those\ncall, directly or not. A write to anything another thread can reach has to be inside a key. `ek9 -h E08251` is the full list\nof what counts as shared and what does not (an object the concurrent code makes for itself, a copy, a re-pointed local,\na line to `Stdout`).\n\nOne further route stops the same mistake earlier. A worker declared `as pure` cannot write to what it captured at all:\n\n```ek9\nfor id in 1 ... 3\n  worker <- (tally, id) is work as pure function\n    tally.deposits += 1\n    rtn: id\n  workers += worker\n```\n\n```text\nEK9     : Error   : E08120: '+=' on line 25 position 25: mutating variables is not allowed when scope is marked as 'pure'\n             See: ek9 -h E08120\n```\n\n`pure` is enforced: a pure function may not reassign anything but its own return, may not mutate what it was handed, and\nmay call only pure code. It is not \"no side effects\", and *Operators and Pragmatic Purity, in Full* has the rules. For\nconcurrency the consequence is direct: a pure worker cannot write to what it captured, so it cannot be the writer in a race.\nThe two checks are separate; this one is E08120, not E08251.\n\n### Lock order (E08252)\n\nTwo locks are not a problem. Two locks taken in opposite orders on two paths are. This `CacheService` nests the log inside\nthe cache in `refresh` and the cache inside the log in `audit`:\n\n```ek9\nrefresh()\n  -> entry as String\n  log <- lockedLog\n\n  logIt <- (entry) is MutexKey of List of String as function\n    lockedItem += `refreshed ${entry}`\n\n  cacheIt <- (entry, log, logIt) is MutexKey of List of String as function\n    lockedItem += entry\n    require log.enter(logIt)\n\n  require lockedCache.enter(cacheIt)\n\naudit()\n  -> note as String\n  cache <- lockedCache\n\n  countCache <- () is MutexKey of List of String as function\n    Stdout().println(`cache holds ${length lockedItem}`)\n\n  logAudit <- (note, cache, countCache) is MutexKey of List of String as function\n    lockedItem += note\n    require cache.enter(countCache)\n\n  require lockedLog.enter(logAudit)\n```\n\n```text\nEK9     : Error   : E08252: 'enter' on line 32 position 24: acquiring 'errors.depth.lockordercycle::lockedCache' while holding 'errors.depth.lockordercycle::lockedLog' participates in lock-order cycle: errors.depth.lockordercycle::lockedCache → errors.depth.lockordercycle::lockedLog → errors.depth.lockordercycle::lockedCache nested enter() on a different lock identity — potential deadlock from lock-order cycle\n             See: ek9 -h E08252\nEK9     : Error   : E08252: 'enter' on line 19 position 22: acquiring 'errors.depth.lockordercycle::lockedLog' while holding 'errors.depth.lockordercycle::lockedCache' participates in lock-order cycle: errors.depth.lockordercycle::lockedCache → errors.depth.lockordercycle::lockedLog → errors.depth.lockordercycle::lockedCache nested enter() on a different lock identity — potential deadlock from lock-order cycle\n             See: ek9 -h E08252\n```\n\nThe compiler builds one graph of \"holding this, acquiring that\" edges for the whole program and finds its cycles. Both edges\nare reported, and each message names the whole cycle. A single direction is not an error: `evict` in `ConsistentOrder` nests\nthe log inside the cache just as `refresh` does, and that program compiles and runs.[^spelled]\n\n```ek9\nevict()\n  -> entry as String\n  log <- lockedLog\n\n  logIt <- (entry) is MutexKey of List of String as function\n    lockedItem += `evicted ${entry}`\n\n  cacheIt <- (log, logIt) is MutexKey of List of String as function\n    lockedItem :=: List() of String\n    require log.enter(logIt)\n\n  require lockedCache.enter(cacheIt)\n```\n\n```text\n[\"refreshed alpha\", \"evicted alpha\"]\n```\n\nThe fix for a real cycle is the one `ek9 -h E08252` gives. Put both lists in one record under one lock; with only one\nlock there is no order to get wrong:\n\n```ek9\nCacheService\n  lockedState <- MutexLock(CacheState())\n\n  refresh()\n    -> entry as String\n    refresher <- (entry) is MutexKey of CacheState as function\n      lockedItem.entries += entry\n      lockedItem.log += `refreshed ${entry}`\n    require lockedState.enter(refresher)\n\n  audit()\n    -> note as String\n    auditor <- (note) is MutexKey of CacheState as function\n      lockedItem.log += `${note}: cache holds ${length lockedItem.entries}`\n    require lockedState.enter(auditor)\n\n  report()\n    <- rtn as CacheState: CacheState()\n    reader <- (rtn) is MutexKey of CacheState as function\n      rtn :=: lockedItem\n    require lockedState.enter(reader)\n\n  default operator ?\n```\n\n```text\nCacheState(entries=[\"alpha\", \"beta\"], log=[\"refreshed alpha\", \"refreshed beta\", \"nightly: cache holds 2\"])\n```\n\nThe record is the same idea as `Tally`. It costs you contention, since every operation on either list now takes the same\nlock, and it buys a program with nothing to order.\n\n### Across a thread boundary (E08253)\n\nA `MutexLock` is reentrant on one thread: code that holds it can enter it again. Reentrancy does not cross threads. A key\nthat holds the lock and then fans out to `async` workers, one of which enters the same lock, makes the worker wait for a\nholder that is waiting for the worker:\n\n```ek9\nreindex <- (lockedIndex) is work as function\n  bump <- () is MutexKey of Integer as function\n    lockedItem += 1\n  rtn: lockedIndex.enter(bump)\n\nholdAndFanOut <- (reindex) is MutexKey of Integer as function\n  stdout <- Stdout()\n  workers <- [ reindex ]\n  cat workers | async | map with toLine > stdout\n\nrequire lockedIndex.enter(holdAndFanOut)\n```\n\n```text\nEK9     : Error   : E08253: 'enter' on line 19 position 25: 'lockedIndex...lockedIndex' (cross-thread of outer 'lockedIndex...lockedIndex'): same lock acquired across a thread boundary — inner acquire blocks waiting for outer holder; MutexLock reentrancy does not cross threads\n             See: ek9 -h E08253\n```\n\n`ek9 -h E08253` names three thread boundaries, `TCP` accept, `Signals` registration and `| async`, and the alternative,\n`| call`, which stays on the same thread where reentrancy is legal. The usual fix is to do\nthe locked work before the boundary and pass a copy across it.\n\n### The dining philosophers (E08255)\n\nTwo locks of the *same* type, handed in by the caller, are the textbook ring deadlock, because the order depends on the\narguments and not on the source. Here `dine` takes two forks and holds one while it takes the other; somewhere else a caller\ncan pass them the other way round:\n\n```ek9\ndine()\n  ->\n    leftFork as Fork\n    rightFork as Fork\n\n  eat <- () is MutexKey of Integer as function\n    lockedItem += 1\n\n  holdLeft <- (rightFork, eat) is MutexKey of Integer as function\n    require rightFork.lock().enter(eat)\n\n  require leftFork.lock().enter(holdLeft)\n```\n\n```text\nEK9     : Error   : E08255: 'enter' on line 25 position 33: nesting 'rightFork...forkLock' inside 'leftFork...forkLock' — same-type locks, caller-supplied, no provable acquisition order: two locks of the same type are nested but no consistent acquisition order can be statically proven — under some interleaving this will deadlock; protect the state under ONE lock over an owning record (and if the state is durable or shared across instances, a mutex cannot protect it — that is a transaction concern)\n             See: ek9 -h E08255\n```\n\nThe compiler refuses it outright. There is no ordered-acquire helper and no lock-ranking annotation to\nreach for: the compiler's answer is the same as before, one lock over an owning record.\n\n### Where a lock may live\n\nThe remaining rules say where a lock can exist, so that every `enter` can be traced to a lock the analysis can name. Four\nshapes are refused, and each refusal is one line:\n\n```ek9\nlocks <- List() of MutexLock of Integer\n```\n\n```text\nEK9     : Error   : E08254: 'List' on line 7 position 15: 'MutexLock of Integer' as type argument to 'List of type T': MutexLock cannot appear in a generic type parameter — move the lock to a class or component field\n             See: ek9 -h E08254\n```\n\n```ek9\nlockedCount <- MutexLock(0)\n```\n\n```text\nEK9     : Error   : E08256: 'MutexLock' on line 7 position 21: MutexLock construction is only allowed as a field initialiser on a class or component\n             See: ek9 -h E08256\n```\n\n```ek9\nnames <- List() of String\nlockedNames as MutexLock of List of String: MutexLock(names)\n```\n\n```text\nEK9     : Error   : E08257: 'MutexLock' on line 8 position 50: MutexLock(...) argument must be a fresh value — a literal or a constructor call (MutexLock(List() of Item) builds an empty payload; MutexLock(String(existing)) copies, but only for a type with a copy constructor - List and Dict have none); not a reference to existing state\n             See: ek9 -h E08257\n```\n\n```ek9\nleak <- (kept) is MutexKey of Name as function\n  kept += lockedItem\n```\n\n```text\nEK9     : Error   : E08258: 'lockedItem' on line 22 position 18: 'lockedItem' is the lock's payload, and 'kept += lockedItem' keeps it outside the lock in 'kept' - copy what you need out (a new value made from it), or keep it in the payload: data inside a MutexLock must be purely contained — nothing outside the lock may keep the payload or an object in it (a built-in value, or a List, Set or Dict of built-in values, is copied out for you; copy anything else out yourself)\n             See: ek9 -h E08258\n```\n\nA lock may not be a type argument, so there is no list or dictionary of locks and no lock per key; it may not be built\noutside a field initialiser; its payload must be a fresh value, not a name for state something else holds; and nothing\noutside the key may keep the locked value, or an object in it. Here `kept` is a list the caller passed in, and `Name` is\na record, so the caller would hold the lock's own `Name`. A `String`, or a list of them, would have been copied out for\nyou; a record you copy yourself, `kept += Name(lockedItem.text)`. The last two are what keep a reference to the payload\nfrom existing outside the lock. The per-key pattern a Java programmer reaches for, a `ConcurrentHashMap` of locks, is\nthe one pattern those rules make impossible; the philosophy behind that is that a lock the compiler cannot name is a\nlock it cannot order.\n\n## What the compiler does not try to do\n\nThe compiler enforces its rules on the shapes it accepts. The deadlock check covers in-process lock-order cycles and\ncross-thread use of the same lock, on the shapes EK9 accepts, and nothing more: it does not try to prove anything about\natomicity across separate `enter` calls, livelock, starvation or fairness, or hazards that live outside the process, such as\na database or a message queue. The data-race rule is a separate check, E08251, and is the one above: it refuses a write to\nshared state outside a key where it can see one.\n\nThe first of those is the one that catches people, because it looks like it should be covered. Each `enter` is atomic; two\nof them in a row are not. This account checks that funds exist in one `enter` and takes them in another:\n\n```ek9\n#!ek9\ndefines module book.concurrency.checkthenact\n\n  defines constant\n    withdrawal <- 80\n\n  defines class\n\n    Account\n      lockedBalance <- MutexLock(100)\n\n      hasFunds()\n        -> amount as Integer\n        <- rtn as Boolean: false\n        checker <- (amount, rtn) is MutexKey of Integer as function\n          rtn :=: lockedItem >= amount\n        require lockedBalance.enter(checker)\n\n      take()\n        -> amount as Integer\n        taker <- (amount) is MutexKey of Integer as function\n          lockedItem :=: lockedItem - amount\n        require lockedBalance.enter(taker)\n\n      takeIfFunds()\n        -> amount as Integer\n        <- rtn as Boolean: false\n        taker <- (amount, rtn) is MutexKey of Integer as function\n          if lockedItem >= amount\n            lockedItem :=: lockedItem - amount\n            rtn :=: true\n        require lockedBalance.enter(taker)\n\n      balance()\n        <- rtn as Integer: Integer()\n        reader <- (rtn) is MutexKey of Integer as function\n          rtn :=: lockedItem\n        require lockedBalance.enter(reader)\n\n      default operator ?\n\n  defines program\n\n    CheckThenAct()\n      stdout <- Stdout()\n\n      split <- Account()\n      firstSeesFunds <- split.hasFunds(withdrawal)\n      secondSeesFunds <- split.hasFunds(withdrawal)\n      stdout.println(`both saw enough: ${firstSeesFunds and secondSeesFunds}`)\n      split.take(withdrawal)\n      split.take(withdrawal)\n      stdout.println(`check and take apart: ${split.balance()}`)\n\n      together <- Account()\n      firstTaken <- together.takeIfFunds(withdrawal)\n      secondTaken <- together.takeIfFunds(withdrawal)\n      stdout.println(`check and take together: ${together.balance()}, taken ${firstTaken} then ${secondTaken}`)\n```\n\n```text\nboth saw enough: true\ncheck and take apart: -60\ncheck and take together: 20, taken true then false\n```\n\nBoth customers saw enough, both took 80, and the balance is -60. The program makes the bad interleaving happen on purpose,\non one thread, so that it is reproducible; with real threads it happens when two of them land between the check and the\ntake, which is the unlucky interleaving and not the usual one. No lock is misused, no cycle exists and the compiler is right to say nothing. The\nsecond account is the fix: `takeIfFunds` checks and takes inside one key, and the second customer is refused.\n\n## The cost\n\nYou cannot share a variable. Anything two threads both write has to live in a `MutexLock`, inside a class, behind methods\nthat make keys; the key syntax is heavier than a `synchronized` block, and a result has to be copied out with `:=:`. You\ncannot keep a map of locks, build one where you need it, or hand a lock to whichever helper is convenient; the rule that\nthe compiler can name every lock excludes some designs a Java or Go programmer would reach for first. And the fix the\ncompiler offers for almost every refusal, one lock over a record, serialises operations that might have run in parallel.\nEK9 does not hide that cost. What it buys is that the failures you have read about, the unprotected counter, the two-lock\ncycle, the ring of philosophers, are errors at compile time and not intermittent faults in production.\n\n> **A design note.** I would rather refuse a program that is correct than accept one I cannot read in thirty seconds. If\n> you have to think hard to convince yourself that a pattern of locking is safe, then it is only safe on the day you\n> thought about it, and code under maintenance for years does not keep the argument that justified it. So the compiler\n> does not ask for the argument. It asks for a shape where the answer is visible: one lock over one record, and a worker\n> that returns its result. *- Steve*\n\n## Where this stops\n\nThe checks are an analysis of the shapes above, and where they stop is stated, not hidden: the two-call atomicity gap, the\nliveness hazards and the distributed ones are yours. Nothing here says a program is correct. It says that, in the shapes the compiler analyses, it found no lock-order cycle, no\nsame lock entered across a thread, and no write to shared state outside a lock. *A Web Service, Step by Step* uses these rules on a repository\nbehind a service, where every request is a concurrent entry point, and *Networking: TCP and UDP* meets the handlers that\nstart the other threads.\n\n[^spelled]: The two locks in `ConsistentOrder` are declared with their type spelled out, `lockedCache as MutexLock of List of\nString: MutexLock(List() of String)`, because `<-` cannot infer a lock over a generic payload (E04050).\n\n[^dynamic]: The capture list `(amount)` and the `is MutexKey of Tally as function` form are covered in *Dynamic Functions\nand Classes*; for this chapter, a key is a function body that is handed `lockedItem` and the values in its capture list.\n","examples":["books/ek9-in-depth/ch33-concurrency-safely/CheckThenAct.ek9","books/ek9-in-depth/ch33-concurrency-safely/ConsistentOrder.ek9","books/ek9-in-depth/ch33-concurrency-safely/LockOrderFixed.ek9","books/ek9-in-depth/ch33-concurrency-safely/LostResult.ek9","books/ek9-in-depth/ch33-concurrency-safely/SharedTally.ek9","books/ek9-in-depth/ch33-concurrency-safely/WorkerTotals.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Dependency Injection and Applications","url":"https://ek9.io/books/ek9-in-depth/dependency-injection-and-applications.html","markdown":"# Dependency Injection and Applications\n\n*Components* in Volume 1 ended with a promise: \"*injecting* a component so one implementation can be swapped for another\" was a\ntopic for the second volume. *Build a Game, End to End* made a second one: \"You cannot unit-test a conversation\", and the\nsecond volume would show how to replace a program's surroundings so that even the loop that talks to a person comes under test.\nThis chapter keeps both, and they are the same mechanism. If you know Spring, Guice or .NET's built-in container, you know the\nshape: a class asks for a contract, and something outside it decides which implementation arrives. The difference is *when*\nthat decision is checked. A Spring container discovers a missing bean, a cycle or a bad construction order when it starts\nup, by reflection. EK9 checks the wiring when the program compiles, and a program that is wired wrongly does not run at all.\n\n## A component, an application and a program\n\nA component is declared `as abstract`, and each implementation `is` it. The consumer holds the abstract one, marked with `!`,\nwhich means \"ask the application for whatever was registered under this type\". An `application` is the registry: one complete\nset of choices. A program names the application it runs against. Here the same `OrderService` is wired to two notifiers:\n\n```ek9\n#!ek9\ndefines module book.di.notifiers\n\n  defines class\n\n    OrderService\n      notifier as Notifier!\n\n      placeOrder()\n        ->\n          customer as String\n          item as String\n\n        notifier.notify(customer, `Your order for ${item} is confirmed`)\n\n      default operator ?\n\n  defines component\n\n    Notifier as abstract\n      notify() as abstract\n        ->\n          customer as String\n          message as String\n\n    EmailNotifier is Notifier\n      override notify()\n        ->\n          customer as String\n          message as String\n\n        Stdout().println(`EMAIL to ${customer}: ${message}`)\n\n    ConsoleNotifier is Notifier\n      override notify()\n        ->\n          customer as String\n          message as String\n\n        Stdout().println(`CONSOLE [${customer}] ${message}`)\n\n  defines application\n\n    liveApp\n      register EmailNotifier() as Notifier\n\n    developmentApp\n      register ConsoleNotifier() as Notifier\n\n  defines program\n\n    LiveShop() with application of liveApp\n      orders <- OrderService()\n      orders.placeOrder(\"alice@example.com\", \"a kettle\")\n      orders.placeOrder(\"bob@example.com\", \"two mugs\")\n\n    DevelopmentShop() with application of developmentApp\n      orders <- OrderService()\n      orders.placeOrder(\"alice@example.com\", \"a kettle\")\n      orders.placeOrder(\"bob@example.com\", \"two mugs\")\n```\n\n`LiveShop` prints:\n\n```text\nEMAIL to alice@example.com: Your order for a kettle is confirmed\nEMAIL to bob@example.com: Your order for two mugs is confirmed\n```\n\nand `DevelopmentShop` prints:\n\n```text\nCONSOLE [alice@example.com] Your order for a kettle is confirmed\nCONSOLE [bob@example.com] Your order for two mugs is confirmed\n```\n\n`OrderService` never mentions a concrete notifier and nothing in it changed between the two runs; only the program's\n`with application of` did. Three details are worth stating before the checks.\n\n- `register EmailNotifier() as Notifier` constructs the implementation once, when the application starts, in the order the\n  registrations are written; a registered component is a singleton for the life of the program. When the program ends the\n  application releases them in the opposite order.\n- An injection is not a lookup. The compiler resolves `notifier as Notifier!` to a load from a generated application object, so\n  there is no reflection, no scanning, no name to mistype, and nothing configured outside the source.\n- `default operator ?` is on `OrderService` for the usual reason: it is an aggregate with a field. The component types need\n  none, because they have no fields.\n\nThe compiler will draw the wiring for you. `ek9 -di` reads the file and reports each application, what it registers and\nwhich program uses it:\n\n```text\nDI/AOP Analysis\n═══════════════\nApplications: 2\n  liveApp: 1 registrations, 0 aspects, all injections satisfied\n  developmentApp: 1 registrations, 0 aspects, all injections satisfied\n\nPrograms: 2\n  LiveShop -> liveApp (OK)\n  DevelopmentShop -> developmentApp (OK)\n\nTotals: 2 registrations, 1 injection sites, 0 aspect proxies\nStatus: All injections satisfied, construction order valid\n```\n\n\"Construction order valid\" is the second of three checks the compiler runs over every application, and they are the point of\nthe chapter.\n\n## What the compiler checks before anything runs\n\nSpring's three classic start-up failures are a missing bean, a circular dependency and a bean created before the bean it needs.\nEach is a compile error here, and each is found by following what the program can actually reach, through the call graph, not\nby looking at declarations alone.\n\n**A missing registration.** Add an audit log to the order service and forget to register it:\n\n```ek9\n    OrderService\n      notifier as Notifier!\n      audit as AuditLog!\n```\n\n```ek9\n  defines application\n\n    shopApp\n      register EmailNotifier() as Notifier\n```\n\n```text\nEK9     : Error   : E08210: 'Shop' on line 44 position 4: program 'Shop' reaches the injection of 'AuditLog' (first in 'OrderService'), not registered in application 'shopApp': program uses injection but application has no registration for the required component type\n             See: ek9 -h E08210\nEK9     : Error   : E08210: 'audit' on line 8 position 6: injection of 'AuditLog' in 'OrderService' is reached from program 'Shop' but is not registered in application 'shopApp', add a register statement: program uses injection but application has no registration for the required component type\n             See: ek9 -h E08210\n```\n\nThe same fault is reported twice, once at the program that reaches the injection and once at the injection itself, because\neither end may be the one you are looking at. The program does not mention `AuditLog`; it constructs `OrderService`, and\n`OrderService` does. A program that has injections but is bound to no application at all is a different code, E08220.\n\n**A cycle.** Let the order service need billing, and billing need the order service:\n\n```ek9\n    OrderService is Orders\n      billing as Billing!\n\n      override place()\n        -> item as String\n        billing.charge(item)\n\n      default operator ?\n\n    BillingService is Billing\n      orders as Orders!\n\n      override charge()\n        -> item as String\n        orders.place(item)\n\n      default operator ?\n```\n\n```text\nEK9     : Error   : E08190: 'OrderService' on line 14 position 4: OrderService -> BillingService -> OrderService circular dependency detected in component injection chain\n             See: ek9 -h E08190\n```\n\n**A registration out of order.** Registrations are constructed in the order they are written, so a component that injects\nanother must be registered below it:\n\n```ek9\n  defines application\n\n    shopApp\n      register OrderService() as Orders\n      register EmailNotifier() as Notifier\n```\n\n```text\nEK9     : Error   : E08200: 'register' on line 31 position 6: 'OrderService' requires 'Notifier' which is not yet registered, reorder registrations: component used before registration in application block\n             See: ek9 -h E08200\nEK9     : Error   : E08200: 'notifier' on line 20 position 6: injection of 'Notifier' not available when 'OrderService' is used, reorder registrations: component used before registration in application block\n             See: ek9 -h E08200\n```\n\n\"Out of order\" is wider than the injected fields of the component. An injection is loaded from the application at the moment\nits declaration runs, so anything that runs while a registration is being made counts: the constructor, the property\ninitialisers, the functions and classes they call, the constructor of an aspect (*Aspects*), even a call in the arguments of the\n`register` line. The compiler follows all of them and rejects the registration if any reaches an injection of a type registered\nlater.\n\nThese are the other tools' mechanisms for the first of those faults, the circular dependency:\n\n| Container | When a circular dependency is found |\n|---|---|\n| Spring | at run time, when the context initialises (`BeanCurrentlyInCreationException`); some cycles are masked by lazy proxies or setter injection |\n| .NET `Microsoft.Extensions.DependencyInjection` | at run time (`InvalidOperationException`): when the provider is built if `ValidateOnBuild` is on, as it is by default in Development, otherwise when the service is first resolved |\n| Go Wire | at code-generation time, when it refuses to generate the injector |\n| EK9 | at compile time, in the compiler itself; no lazy proxy and no setter to defer it |\n\nGo Wire is close to EK9, because it also refuses before the program runs. The difference is that EK9 has no separate generation\nstep to run, and no escape hatch such as a lazy proxy that moves the cycle somewhere a test might not reach.\n\nA cycle is reported once, at the member registered first, and the members of the cycle get no ordering error as well: no\norder could satisfy them, so \"reorder your registrations\" would be advice that cannot be followed. A component that merely\nsits outside the cycle and is registered too early still gets its E08200.\n\n> **A design note.** A cycle is only half of it. In Spring a dependency that nothing provides is found when the application\n> context starts, as an `UnsatisfiedDependencyException` - or, behind `@Lazy` or a `getBean` call, only when that path first\n> runs, which may be in production. I wanted both faults to be compile errors. An injection the program can reach with no\n> registration is E08210, one registered too late is E08200 and a cycle is E08190, so by the time a program compiles, the\n> compiler has checked that every injection it can reach is registered, in an order that works. *- Steve*\n\n## Only an abstract component can be injected\n\nYou might expect `out as Stdout!` to work, since writing to the console is the first thing a test wants to replace. It does\nnot:\n\n```ek9\n    ConsoleGreeter is Greeter\n      override greet()\n        -> name as String\n        out as Stdout!\n        out.println(`Hello ${name}`)\n```\n\n```text\nEK9     : Error   : E08160: 'out' on line 13 position 8: is not a component but a 'CLASS': dependency injection is not allowed\n             See: ek9 -h E08160\n```\n\nOnly an abstract component is injectable. A concrete one is E08150 (`notifier as EmailNotifier!` asks for an implementation,\nnot a contract), and anything that is not a component is E08160: `Stdout`, `Stdin` and `OS` are classes, and `Clock` is a\ntrait. The rule is deliberate; the compiler's own help puts it as \"ONLY components can be injected -- NOT classes\", to keep\ninjection from becoming a way to reach any object from anywhere. What it costs is a layer: to put the keyboard or the\nrandom-number source under a test you wrap it in a small component of your own, a contract of one or two methods and one\nproduction implementation that holds the real thing. That layer is exactly what the next section builds, and it turns out to\nbe what you wanted anyway.\n\n## The seam Volume 1 promised\n\n*Build a Game, End to End* ended with a guessing game whose loop could not be tested, because the loop needs a person at a\nkeyboard and a random secret from the operating system. Those two are the program's *surroundings*. Make each a contract:\n`SecretSource` says \"give me a secret\", `Player` says \"give me the next guess\". The production implementations are the thin part\nthat talks; the game itself, `GuessGame`, depends only on the contracts.\n\n```ek9\n#!ek9\ndefines module book.di.seam\n\n  defines constant\n    HIGHEST <- 100\n\n    MAX_TRIES <- 7\n\n  defines class\n\n    GuessGame\n      secrets as SecretSource!\n      player as Player!\n\n      play()\n        <- rtn as String?\n        secret <- secrets.secret()\n        if not onTheBoard(secret)\n          throw Exception(`the secret ${secret} is not from 1 to ${HIGHEST}`)\n        tries <- 0\n        solved <- false\n        while triesLeft(tries) and not solved\n          tries++\n          if guess <- player.nextGuess()\n            solved := guess == secret\n            Stdout().println(hint(secret, guess))\n        rtn: verdict(solved, tries)\n\n      default operator ?\n\n  defines function\n\n    hint() as pure\n      ->\n        secret as Integer\n        guess as Integer\n      <- rtn as String: String()\n\n      order <- guess <=> secret\n      rtn: order < 0 <- \"higher\" : order > 0 <- \"lower\" : \"correct\"\n\n    onTheBoard() as pure\n      -> secret as Integer\n      <- rtn as Boolean: secret >= 1 and secret <= HIGHEST\n\n    triesLeft() as pure\n      -> tries as Integer\n      <- rtn as Boolean: tries < MAX_TRIES\n\n    verdict() as pure\n      ->\n        solved as Boolean\n        tries as Integer\n      <- rtn as String: String()\n\n      rtn: solved <- `solved in ${tries} tries` : `not solved in ${tries} tries`\n\n  defines component\n\n    SecretSource as abstract\n      secret() as abstract\n        <- rtn as Integer?\n\n    Player as abstract\n      nextGuess() as abstract\n        <- rtn as Integer?\n\n    RandomSecret is SecretSource\n      override secret()\n        <- rtn as Integer: OS().random(1, HIGHEST)\n\n    KeyboardPlayer is Player\n      override nextGuess()\n        <- rtn as Integer: Integer(Stdin().next())\n\n  defines application\n\n    liveGame\n      register RandomSecret() as SecretSource\n      register KeyboardPlayer() as Player\n\n  defines program\n\n    Play() with application of liveGame\n      game <- GuessGame()\n      Stdout().println(game.play())\n```\n\n`RandomSecret` calls the same `OS().random(1, HIGHEST)` Volume 1 used, and `KeyboardPlayer` wraps `Stdin`, which is the layer the\nprevious section said you would write. A test needs no mocking framework, because a stand-in is another component. It\nlives in the project's `dev/` folder, beside the tests, and it is wired by a *test application*:\n\n```ek9\ndefines module book.di.seam.tests\n\n  references\n    book.di.seam::GuessGame\n    book.di.seam::HIGHEST\n    book.di.seam::hint\n    book.di.seam::Player\n    book.di.seam::RandomSecret\n    book.di.seam::SecretSource\n    book.di.seam::triesLeft\n    book.di.seam::verdict\n\n  defines component\n\n    FixedSecret is SecretSource\n      override secret()\n        <- rtn as Integer: 37\n\n    ScriptedPlayer is Player\n      guesses as Iterator of Integer?\n\n      ScriptedPlayer()\n        script <- [50, 25, 37]\n        guesses: script.iterator()\n\n      override nextGuess()\n        <- rtn as Integer: Integer()\n        if guesses.hasNext()\n          rtn: guesses.next()\n\n      default operator ?\n\n    HopelessPlayer is Player\n      override nextGuess()\n        <- rtn as Integer: 1\n\n    OffTheBoardSecret is SecretSource\n      override secret()\n        <- rtn as Integer: 0\n\n  defines application\n\n    scriptedGame\n      register FixedSecret() as SecretSource\n      register ScriptedPlayer() as Player\n\n    hopelessGame\n      register FixedSecret() as SecretSource\n      register HopelessPlayer() as Player\n\n    brokenGame\n      register OffTheBoardSecret() as SecretSource\n      register HopelessPlayer() as Player\n```\n\n`FixedSecret` is the pretend `\"random\"` that \"always returns the same number\" and `ScriptedPlayer` is \"a pretend player who types a\nfixed script\", Volume 1's own words, and each is a few lines of the language you already have. The test applications are checked\nexactly as `liveGame` is: leave the `Player` out of `hopelessGame` and the test does not compile (E08210). A test chooses its\napplication the way a program does:\n\n```ek9\n  defines program\n\n    @Test\n    ThirdGuessWins() with application of scriptedGame\n      game <- GuessGame()\n      assert game.play() == \"solved in 3 tries\"\n\n    @Test\n    RunsOutOfTries() with application of hopelessGame\n      game <- GuessGame()\n      assert game.play() == \"not solved in 7 tries\"\n\n    @Test\n    ASecretOffTheBoardIsRefused() with application of brokenGame\n      game <- GuessGame()\n      assertThrows (Exception, game.play())\n\n    @Test\n    HintsPointTheRightWay()\n      assert hint(37, 50) == \"lower\"\n      assert hint(37, 25) == \"higher\"\n      assert hint(37, 37) == \"correct\"\n\n    @Test\n    VerdictCountsTheTries()\n      assert verdict(true, 3) == \"solved in 3 tries\"\n      assert verdict(false, 7) == \"not solved in 7 tries\"\n\n    @Test\n    TheLastTryIsTheSeventh()\n      assert triesLeft(6)\n      assert not triesLeft(7)\n\n    @Test\n    LiveSecretStaysOnTheBoard()\n      secret <- RandomSecret().secret()\n      assert secret >= 1 and secret <= HIGHEST\n      assert RandomSecret()?\n\n    @Test\n    GameIsSet() with application of scriptedGame\n      assert GuessGame()?\n```\n\nThe loop that Volume 1 called untestable now runs under a script. `ek9 -t` with the coverage summary gives:\n\n```text\nℹ️ Found 8 tests:\n  8 assert (unit tests with assertions)\n\nExecuting 8 tests...\n\n✅ PASS book.di.seam.tests::ASecretOffTheBoardIsRefused [Assert] (7ms)\n✅ PASS book.di.seam.tests::GameIsSet [Assert] (8ms)\n✅ PASS book.di.seam.tests::HintsPointTheRightWay [Assert] (33ms)\n✅ PASS book.di.seam.tests::LiveSecretStaysOnTheBoard [Assert] (6ms)\n✅ PASS book.di.seam.tests::RunsOutOfTries [Assert] (9ms)\n✅ PASS book.di.seam.tests::TheLastTryIsTheSeventh [Assert] (3ms)\n✅ PASS book.di.seam.tests::ThirdGuessWins [Assert] (26ms)\n✅ PASS book.di.seam.tests::VerdictCountsTheTries [Assert] (7ms)\n\nSummary: 8 passed, 0 failed (8 total)\nTypes: 8 assert\nDuration: 103ms\n\n📊 Coverage Summary\n  ⚠️ Methods:  66.7% (10/15)\n  ✅ Lines:    80.9% (38/47)\n  ✅ Branches: 100.0% (7/7)\n\n  ✅ Overall: 81.13% (43/53 probes hit)\n\n📦 By Module:\n  ✅ book.di.seam: 81.13% (43/53)\n```\n\nWhat is still uncovered is the five methods that talk to the world: `KeyboardPlayer`, the `liveGame` application and the `Play`\nprogram. They hold no decisions, which is the thin part Volume 1 said would be left. The bar is real, though. With only the\nfirst two tests, both of which pass, the same project ends `E83001: Code coverage 66.0% is below required threshold 80%` and\nexits 12. *Testing the Compiler Trusts* is about what coverage measures and what it does not.\n\n## What it costs\n\nThe checks above are the benefit; here is the price, in the order you will meet it.\n\n**There is one application per program, and it is chosen when you compile.** A program names its application in its\ndeclaration; nothing swaps an implementation while the program runs, and nothing reads a configuration file to decide. If you\nwant a different wiring you write a different program or a different test, as `DevelopmentShop` and the three test\napplications did. That is less flexible than a container that reads a profile from the environment at start-up, and it is the\nreason every check in this chapter is possible: the compiler knows the whole graph because the graph cannot change.\n\n**An injected variable is fixed.** It is never assigned, not even with `:=?`, and it is always set:\n\n```ek9\n    Shop() with application of shopApp\n      notifier as Notifier!\n      notifier := EmailNotifier()\n      notifier.notify(\"hello\")\n```\n\n```text\nEK9     : Error   : E08170: ':=' on line 24 position 15: an injected component is never assigned, not even with ':=?' - for a fallback, assign to a new variable ('chosen <- supplied' then 'chosen :=? injected')\n             See: ek9 -h E08170\n```\n\nThe habit of checking whether an injected value arrived, which you may bring from a container where an optional injection\ncan be null, is refused for the same reason. E08210 rejects a program whose reachable injection has no registration, so the\ncheck could only ever be true:\n\n```ek9\n    Play() with application of fixedGame\n      dice as Dice!\n      if dice?\n        Stdout().println($dice.roll())\n```\n\n```text\nEK9     : Error   : E08266: '?' on line 23 position 13: 'dice?': an injected component is always set, so checking that it is set is always true - use the injected value directly; for a fallback, use a new variable ('chosen <- supplied' then 'chosen :=? injected')\n             See: ek9 -h E08266\n```\n\n**Wrapping the built-ins is your job.** `Stdout`, `Stdin`, `OS` and `Clock` are not components, so the layer between them and your\nlogic is code you write, as `KeyboardPlayer` was. The benefit is a contract named for what the program needs rather than for\nwhat the platform offers, which is the better design in any language; the cost is that you must write it before the first test.\n\n**A component may inject only four others.** Five `!` fields in one class or component is E11040:\n\n```text\nEK9     : Error   : E11040: 'OrderService' on line 27 position 4: has 5 injected fields (limit 4) - use a facade component to group dependencies: too many injected fields - use a facade component to group dependencies\n             See: ek9 -h E11040\n```\n\nThe compiler's help says the limit of four is EK9's choice, and cites Clean Code on long argument lists and Seemann's\n\"constructor over-injection\". It also caps an application at twelve registrations (E11042) and a single callable at four\ninjected types (E11043). The fix is the one the message names: group the collaborators behind a facade component, which is a\ndesign improvement the limit forces. You may disagree with four, but you cannot configure it away.\n\nWhat the cost buys is a program whose wiring is a fact the compiler has already checked, whose test doubles are ordinary\ncomponents, and which needs neither a container nor a mocking library. *Aspects*, next, hangs behaviour on the registration\nline without touching either the component or its consumers. A project too large for one file moves its contracts and\nimplementations into modules; *Organising a Growing Codebase* sets out the layout.\n","examples":["books/ek9-in-depth/ch34-dependency-injection-and-applications/Notifiers.ek9","books/ek9-in-depth/ch34-dependency-injection-and-applications/guess-seam/GuessSeam.ek9","books/ek9-in-depth/ch34-dependency-injection-and-applications/guess-seam/dev/GuessSeamTests.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Aspects","url":"https://ek9.io/books/ek9-in-depth/aspects.html","markdown":"# Aspects\n\nLogging, timing, auditing and tracing are written once and needed in many places, and the usual cost of adding them is an\nedit to every method they touch. Java's answer is AspectJ, which weaves advice into bytecode under a pointcut language and\nneeds its own build step, or Spring AOP, which wraps beans in run-time proxies chosen by pointcut expressions held in strings.\nPython reaches for a decorator at the definition; a web framework reaches for middleware. EK9 attaches the advice at a\ndifferent place: the registration line of an `application`, the same line that *Dependency Injection and Applications* used to\nchoose an implementation. The component is not edited and neither is anything that calls it. This chapter is about what that\nline can do, in what order it does it, and what it cannot.\n\n## Advice at the registration line\n\nAn aspect is a class that extends the built-in `Aspect`. Its two methods are called around every method of the component it is\nattached to: `beforeAdvice` receives a `JoinPoint` (the component's name and the method's name) and returns a\n`PreparedMetaData`; `afterAdvice` receives that same `PreparedMetaData` back. You attach one or more aspects after the\nregistration, with `with aspect of`, which requires the `as` contract in front of it:\n\n```ek9\n#!ek9\ndefines module book.aspects.order\n\n  defines class\n\n    LabelAspect extends Aspect\n      label as String?\n\n      default private LabelAspect()\n\n      LabelAspect()\n        -> label as String\n        this.label: label\n\n      override beforeAdvice()\n        -> joinPoint as JoinPoint\n        <- rtn as PreparedMetaData: PreparedMetaData(joinPoint)\n        Stdout().println(`${label} before ${joinPoint.componentName()}.${joinPoint.methodName()}`)\n\n      override afterAdvice()\n        -> preparedMetaData as PreparedMetaData\n        Stdout().println(`${label} after ${preparedMetaData.joinPoint().methodName()}`)\n\n      default operator ?\n\n  defines component\n\n    Greeter as abstract\n      greet() as abstract\n        -> name as String\n\n    PoliteGreeter is Greeter\n      override greet()\n        -> name as String\n        Stdout().println(`  hello ${name}`)\n\n  defines application\n\n    greetingApp\n      register PoliteGreeter() as Greeter with aspect of LabelAspect(\"outer\"), LabelAspect(\"inner\")\n\n  defines program\n\n    Greeting() with application of greetingApp\n      greeter as Greeter!\n      greeter.greet(\"Steve\")\n```\n\n```text\nouter before book.aspects.order::PoliteGreeter.greet\ninner before book.aspects.order::PoliteGreeter.greet\n  hello Steve\ninner after greet\nouter after greet\n```\n\n`PoliteGreeter` has no aspect code and `Greeting` does not mention one; only `greetingApp` does. Two facts are visible in the\noutput. First, the order: before-advice runs in the order the aspects are written, then the component's own method, then\nafter-advice in the *reverse* order, so the first aspect listed is the outermost layer, as with nested middleware. Second,\n`componentName()` names the implementation (`PoliteGreeter`), not the contract the program holds. An aspect is a class like any\nother, so `LabelAspect(\"outer\")` is an ordinary constructor call with an argument, and the compiler checks the arguments as\nit checks any call.\n\nThe compiler will tell you what it has woven. `ek9 -di -E3` lists each registration with its aspects, in order, and states\nthe sequence in words:\n\n```text\nWiring Map\n──────────\n\nApplication: shopApp (./PriceBook.ek9:82)\n  [1] SimplePriceBook as PriceBook:83\n      aspects: LoggingAspect, TimerAspect\n```\n\n```text\n[ASPECT CHAIN]\nAspect weaving is configured for one or more registrations. Each proxied\nmethod will have before/after advice applied in registration order.\n\nExecution flow per proxied method:\n  1. JoinPoint created with method name and type\n  2. Before advice called on each aspect (in order)\n  3. Delegate method called (wrapped in try/finally)\n  4. After advice called on each aspect (in reverse order)\n  5. Return value passed back to caller\n```\n\nThat output is from the program in the next section.\n\n## Carrying a value from before to after\n\nThe `PreparedMetaData` that `beforeAdvice` returns is the only channel between the two calls, which is what makes a timer\npossible: the start time is prepared before, and read after. Extend `PreparedMetaData` with the value you need, and return that\nsubtype:\n\n```ek9\n    TimerData extends PreparedMetaData\n      started as Millisecond?\n\n      default private TimerData()\n\n      TimerData()\n        ->\n          started as Millisecond\n          joinPoint as JoinPoint\n\n        super(joinPoint)\n        this.started: started\n\n      started()\n        <- rtn as Millisecond: started\n\n      default operator ?\n      default operator $\n      default operator :=:\n      default operator <=>\n\n    TimerAspect extends Aspect\n      clock as Clock?\n\n      default private TimerAspect()\n\n      TimerAspect()\n        -> clock as Clock\n        this.clock: clock\n\n      override beforeAdvice()\n        -> joinPoint as JoinPoint\n        <- rtn as TimerData: TimerData(clock.millisecond(), joinPoint)\n\n      afterAdvice()\n        -> timerData as TimerData\n        elapsed <- clock.millisecond() - timerData.started()\n        Stdout().println(`timer: ${timerData.joinPoint().methodName()} took ${elapsed}`)\n\n      default operator ?\n```\n\nTwo details need explaining. `TimerData` adds a field below `PreparedMetaData`, so it must state its own `?`, `$`, `:=:` and\n`<=>`; a subtype that added a field and inherited those would silently leave the new field out of the text, the copy and the\nordering (E07238).[^sameness] And `afterAdvice` in `TimerAspect` is *not* marked `override`. `Aspect` declares\n`afterAdvice` as a **dispatcher** taking a `PreparedMetaData`; the timer's version takes a `TimerData`, which is a second\noverload, and the dispatcher routes the call to it by the *run-time* type of what `beforeAdvice` returned. That is the\nmechanism *The Dispatcher* describes, used here without your writing the word. Mark it `override` and the compiler explains the\ndistinction:\n\n```text\nEK9     : Error   : E05110: 'afterAdvice' on line 52 position 15: 'override public Void <- afterAdvice(timerData as TimerData)' takes other parameter types than the parent's 'public Void <- afterAdvice(preparedMetaData as PreparedMetaData)' in built-in 'Aspect' (see 'ek9 -h Aspect') - an override takes exactly the same types, so this is a new overload; remove 'override' from THIS member, or take the parent's types to override it: does not 'override' any method/operator\n             See: ek9 -h E05110\n```\n\nPut the two aspects on one component, a returning method and one that returns nothing, and the registration is still one line:\n\n```ek9\n  defines application\n\n    shopApp\n      register SimplePriceBook() as PriceBook with aspect of LoggingAspect(), TimerAspect(StandStillClock())\n\n  defines program\n\n    Shop() with application of shopApp\n      stdout <- Stdout()\n      prices as PriceBook!\n\n      stdout.println(\"-- a call that returns a value\")\n      stdout.println(`kettle: ${prices.priceOf(\"kettle\")}`)\n\n      stdout.println(\"-- a call that returns nothing\")\n      prices.reload()\n```\n\n```text\n-- a call that returns a value\nlog: before priceOf\ntimer: priceOf took 0ms\nlog: after priceOf\nkettle: 12.50#GBP\n-- a call that returns nothing\nlog: before reload\n  (price book reloaded)\ntimer: reload took 0ms\nlog: after reload\n```\n\nRead it against the order rule: `log: before` (the timer's before-advice prints nothing), the method, then the timer's after-advice\nand only then the logger's. Every method of the contract is advised, the one that returns a value and the one that does not.\n`StandStillClock` is a `Clock` whose `millisecond()` never advances, which is why the figure is 0ms: it makes the output\nreproducible. Register `SystemClock()` instead and the line reads a different figure on every run.\n\n## When the advised method throws\n\nThe compiler's own description says the delegate call is \"wrapped in try/finally\", and a charge that refuses a negative amount\nshows what that means in practice:\n\n```ek9\n  defines application\n\n    paymentsApp\n      register StrictGateway() as PaymentGateway with aspect of LoggingAspect()\n\n  defines program\n\n    Payments() with application of paymentsApp\n      stdout <- Stdout()\n      gateway as PaymentGateway!\n\n      for amount in [20.00#GBP, -5.00#GBP]\n        try\n          gateway.charge(amount)\n        catch\n          -> ex as Exception\n          stdout.println(`caller caught: ${ex.reason()}`)\n```\n\n```text\nlog: before charge\n  charged 20.00#GBP\nlog: after charge\nlog: before charge\nlog: after charge\ncaller caught: refusing to charge -5.00#GBP\n```\n\nOn the second call the gateway throws, the after-advice still runs, and the caller then catches the same exception. An aspect\ncannot swallow, change or replace what the component throws. It also cannot *tell* that the call threw: `afterAdvice` receives\nonly the `PreparedMetaData`, and nothing in it records success or failure. An aspect that logs \"completed\" in its after-advice\nis wrong for the second call above.\n\n## Only a component, only an Aspect\n\nAn aspect exists only at the registration site, and the compiler holds that line from both ends. A class cannot be registered\nat all, so there is nothing to attach an aspect to:\n\n```ek9\n  defines application\n\n    shopApp\n      register SimplePriceBook() as PriceBook with aspect of LoggingAspect()\n```\n\n```text\nEK9     : Error   : E50020: 'PriceBook' on line 27 position 36: resolved as a 'class' which is a 'type' rather than a 'component': incompatible genus\n             See: ek9 -h E50020\n```\n\nAnd a class that has the right method but does not extend `Aspect` is not one:\n\n```text\nEK9     : Error   : E50030: 'Tracer' on line 27 position 61: 'Tracer' is not assignable to 'Aspect': types are not compatible with each other\n             See: ek9 -h E50030\n```\n\n## What it costs\n\nThe honest criticism of aspects is action at a distance: you read `prices.priceOf(\"kettle\")` and the console shows three lines\nyou cannot find in `priceOf`, `Shop` or the component. EK9 does not remove that; it confines it. Advice can be attached in\nexactly one kind of place, the `register` line, and the compiler will list every such line for you (`ek9 -di -E3`, above). That\nis a smaller surface than annotations scattered over a codebase, and a larger one than a call that does what it says.\n\nThe mechanism is also deliberately narrow, and each narrowness is something you cannot do:\n\n- **No pointcuts.** Every method of the registered contract is advised. To act on only some, the aspect tests\n  `joinPoint.methodName()` itself.\n- **No arguments and no result.** A `JoinPoint` holds two names. The advice cannot see what was passed, what came back, or\n  whether the call threw, so it suits logging, timing and counting, and not validation or caching.\n- **No \"around\".** There is no advice that wraps the call and decides whether to make it; before-advice cannot veto the method.\n- **No per-call-site advice.** Two programs that want different advice register differently, in different applications.\n\nAn aspect is also shared state. One instance serves every call, so a field it writes is written by every caller. In a\nsingle-threaded program that is fine, and a counting aspect works:\n\n```ek9\n    CountingAspect extends Aspect\n      calls <- 0\n\n      override beforeAdvice()\n        -> joinPoint as JoinPoint\n        <- rtn as PreparedMetaData: PreparedMetaData(joinPoint)\n        calls++\n\n      override afterAdvice()\n        -> preparedMetaData as PreparedMetaData\n        Stdout().println(`calls so far: ${calls}`)\n\n      default operator ?\n```\n\nTwo calls to the advised component print:\n\n```text\ncalls so far: 1\none\ncalls so far: 2\ntwo\n```\n\nbut hand the advised component to concurrent code, here a TCP handler that calls it for each connection, and the same write\nis refused:\n\n```ek9\n    EchoServer() with application of countingApp\n      stdout <- Stdout()\n      worker as Worker!\n      handler <- (worker) is TCPHandler as function\n        output.println(worker.work(input.next()))\n      try\n        -> tcpServer <- TCP(NetworkProperties(port: 0, backlog: 2, maxConcurrent: 2, localOnly: true))\n        if tcpServer.accept(handler)\n          stdout.println(\"done\")\n```\n\n```text\nEK9     : Error   : E08251: 'calls' on line 12 position 8: mutation of shared state must happen inside MutexLock.enter(...) — wrap the write in a MutexKey body\n             See: ek9 -h E08251\n```\n\nThe rule belongs to *Concurrency, Safely*. It is one reason to keep per-call state in the `PreparedMetaData`, which belongs\nto a single call, and not in a field of the aspect.\n\nWhat the narrowness buys is that an aspect cannot break the component it wraps: it cannot alter a result, suppress an\nexception or skip a call, and the wiring that attaches it is checked with the rest of the application. A test application\ncan register the same component with the aspect or without it, as the test needs; *Testing the Compiler Trusts* shows what a\ntest application is for.\n\n[^sameness]: The full rule is E07238 (`ek9 -h E07238`); the model behind it is in *Operators and Pragmatic Purity, in Full*.\n","examples":["books/ek9-in-depth/ch35-aspects/AspectException.ek9","books/ek9-in-depth/ch35-aspects/AspectOrder.ek9","books/ek9-in-depth/ch35-aspects/CallCounter.ek9","books/ek9-in-depth/ch35-aspects/PriceBook.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Networking: TCP and UDP","url":"https://ek9.io/books/ek9-in-depth/networking-tcp-udp.html","markdown":"# Networking: TCP and UDP\n\nA Java socket server is a `ServerSocket`, a loop around `accept()`, an executor to run each connection, a flag to tell the\nloop to stop, and a `close()` that has to run on every path, including the one where the handler throws. Go trades the\nexecutor for a goroutine and the `close()` for a `defer`; Node trades both for callbacks. In each, the shape of the server is\nsomething you assemble from parts, and the parts that go wrong are the ones you wrote last: the stop and the close.\n\nEK9 makes three decisions, and the rest of this chapter is those decisions at work. The server is a **resource a `try` owns**,\nso the close is generated and you cannot write it. The code that serves a connection is a **function**, a `TCPHandler` that is\ngiven two streams. And every network setting, for a client or a server, travels in one record, `NetworkProperties`. The\nchapter writes a TCP echo, a TCP server and client in two processes, a UDP echo, a UDP server that is a pipeline, and then the\naddresses those programs talk to. Every server here binds the loopback address only (`localOnly: true`) and uses a port from\nthe 4445-4460 range; every output block was captured from a real run.\n\n| The job | Java | Go | EK9 |\n|---|---|---|---|\n| Run the accept loop | your loop around `accept()` | your loop around `Accept()` | `accept(handler)` runs it |\n| Serve one connection | a `Runnable` on an executor | a goroutine | a `TCPHandler` function |\n| Stop from inside a handler | a flag, then close from another thread | cancel a context, close the listener | `stop()` |\n| Release the socket | `try`-with-resources, by hand | `defer` | the owning `try`, generated |\n\n## A server and its own client\n\nThe quickest way to see a TCP server work needs no second terminal. `acceptUntilComplete` serves connections while a second\nfunction, the **ready handler**, runs on its own thread once the server is listening; when the ready handler ends, the server\nis stopped.\n\n```ek9\n#!ek9\ndefines module book.network.echo\n\n  defines function\n\n    echo() is TCPHandler\n      ->\n        input as StringInput\n        output as StringOutput\n\n      while input?\n        output.println(`echo:${input.next()}`)\n\n  defines program\n\n    EchoInProcess()\n      stdout <- Stdout()\n      props <- NetworkProperties(port: 0, backlog: 2, maxConcurrent: 2, localOnly: true)\n\n      try\n        -> tcpServer <- TCP(props)\n        client <- (stdout, props) is TCPReadyHandler as function\n          loopback <- Networking().loopbackV4()\n          try\n            -> connection <- TCP(NetworkProperties(loopback, props.port)).connect()\n            if connection?\n              connection.output().println(\"hello\")\n              stdout.println(`client received [${connection.input().next()}]`)\n          server.stop()\n\n        if tcpServer.acceptUntilComplete(echo, client)\n          stdout.println(`served until the client finished, server still set: ${tcpServer?}`)\n      stdout.println(\"the try has closed the server\")\n```\n\n```text\nclient received [echo:hello]\nserved until the client finished, server still set: true\nthe try has closed the server\n```\n\nPort `0` asks the operating system to choose one, and the runtime writes the choice back into `props`, which is how the\nclient, built from that same record, learns where to connect. `echo` is a named function that implements `TCPHandler`: it is\nhanded the connection's `StringInput` and `StringOutput` and reads while the input still has something. The ready handler is\na dynamic function that **captures** `stdout` and `props`, the capture list in parentheses (*Dynamic Functions and Classes*\ncovers what that makes it); its `server` parameter comes from `TCPReadyHandler`, and it calls `server.stop()` itself when it\nhas finished. The last line of the output is the point of the `try`: the server was stopped by the client's side, closed by\nthe block that owns it, and nothing in the program says `close`.\n\nBeyond being short, this form is the one to test with. A network program whose client and server share a process needs no\nfixed port and no start-up ordering, so an automated check can drive it (*Testing the Compiler Trusts*).\n\n## Two processes: a handler that stops the server\n\nA real server runs on its own. This one upper-cases each line it receives, and a line that says `shutdown` stops it.\n\n```ek9\n#!ek9\ndefines module book.network.lineserver\n\n  defines constant\n    SERVER_PORT <- 4446\n\n    SHUTDOWN_COMMAND <- \"shutdown\"\n\n  defines program\n\n    LineServer()\n      stdout <- Stdout()\n\n      try\n        -> tcpServer <- TCP(NetworkProperties(port: SERVER_PORT, backlog: 5, maxConcurrent: 4, localOnly: true))\n\n        if tcpServer?\n          handler <- (tcpServer, stdout) is TCPHandler as function\n            stdout.println(\"connection made\")\n            while input?\n              line <- input.next()\n              stdout.println(`received [${line}]`)\n              output.println(line.trim().upperCase())\n              if line == SHUTDOWN_COMMAND\n                tcpServer.stop()\n            stdout.println(\"no more input on the connection\")\n\n          stdout.println(\"awaiting connections\")\n          if tcpServer.accept(handler)\n            stdout.println(\"server stopped, the try will close it\")\n          else\n            stdout.println(`not able to serve requests gracefully [${tcpServer}]`)\n        else\n          stdout.println(`failed to start the server [${tcpServer}]`)\n```\n\nThe handler is a dynamic function that implements `TCPHandler`, and it captures `tcpServer` and `stdout`. The capture is what\nlets a handler that was created inside the server's `try` reach back and end the server: `tcpServer.stop()` on the `shutdown`\nline. `input` and `output` are not declared anywhere in the handler; they are the parameters of `TCPHandler`, in scope\nbecause the function implements it, in the same way `signal` is in scope in a `SignalHandler` later in this chapter.\n\n`stop()` ends the accept loop **without closing the server**. `accept(handler)` then returns `true`, the `if` prints its\nline, the `try` ends, and only then is the socket closed. A stopped server stays set but cannot serve again, and calling\n`stop()` twice is harmless. The help for `TCP` states the rule in one line: only the owner closes a server.[^stopclose]\n\nThe client is a second program, in a second file, that takes the message as its argument:\n\n```ek9\n#!ek9\ndefines module book.network.lineclient\n\n  defines constant\n    SERVER_PORT <- 4446\n\n  defines program\n\n    LineClient()\n      -> message as String\n      stdout <- Stdout()\n      localhost <- Networking().loopbackV4()\n\n      try\n        -> tcpClient <- TCP(NetworkProperties(localhost, SERVER_PORT))\n\n        if tcpClient?\n          stdout.println(`connecting to ${tcpClient}`)\n          try\n            -> connection <- tcpClient.connect()\n            if connection?\n              connection.output().println(message)\n              stdout.println(`response [${connection.input().next()}]`)\n            else\n              stdout.println(`failed to connect [${tcpClient}]`)\n        else\n          stdout.println(`failed to create the client [${tcpClient}]`)\n```\n\nStart the server in one terminal, then run the client twice from another:\n\n```console\n$ ek9 LineServer.ek9\n$ ek9 LineClient.ek9 \"Short Message\"\n$ ek9 LineClient.ek9 shutdown\n```\n\nThe client prints, for the two runs:\n\n```text\nconnecting to TCP{client, ready, NetworkProperties{host: 127.0.0.1, port: 4446}}\nresponse [SHORT MESSAGE]\nconnecting to TCP{client, ready, NetworkProperties{host: 127.0.0.1, port: 4446}}\nresponse [SHUTDOWN]\n```\n\nand the server, which exits by itself after the second connection, printed:\n\n```text\nawaiting connections\nconnection made\nreceived [Short Message]\nno more input on the connection\nconnection made\nreceived [shutdown]\nserver stopped, the try will close it\nno more input on the connection\n```\n\nThe last two lines are a race between two threads, and this run shows one outcome: `stop()` ends the accept loop at once and\ndoes not wait for the handler that called it to run to the end, so \"server stopped\" can arrive before that handler's final\nline. If the order of those two lines matters to you, the handler is the wrong place to decide it.\n\nWhat happens if you do what a Java programmer does, and close the server from the handler that is shutting it down?\n\n```ek9\n        handler <- (tcpServer) is TCPHandler as function\n          while input?\n            line <- input.next()\n            output.println(line)\n            if line == \"shutdown\"\n              tcpServer.close()\n```\n\n```text\nEK9     : Error   : E81060: 'close' on line 17 position 24: 'TCP.close()': the close operator is never called as a method, 'super.close()' included - make the value a try-with-resources resource; a type's own properties and its super class are closed by its generated close\n             See: ek9 -h E81060\n```\n\nThere is no escape hatch. A handler cannot close the server under the `try` that owns it, so the double close, and the close\nof a socket another thread is still reading, are not programs you can write. What you have instead is `stop()`, and the rule\nthat ending the loop and releasing the socket are two steps with two different owners.\n\nErrors on a socket are reported, not thrown: both programs check `tcpServer?` and `tcpClient?` after creating them, and print\nthe object itself in the `else` branch, which shows its state. `lastErrorMessage()` holds the reason. A bind to a port that\nis already taken gives you an unset server and a message, not an exception. Starting the line server a second time while the\nfirst is running prints:\n\n```text\nfailed to start the server [TCP[unset]]\n```\n\n## UDP: everything is a packet\n\nUDP has no connection, so there is no handler and no `stop()`: a server is a socket that you read packets from and write\npackets to. In EK9 a `UDPPacket` carries **its own destination and its content**, so one socket can address many peers, and a\nreply is a packet addressed to where the request came from.\n\n```ek9\n#!ek9\ndefines module book.network.udpechoserver\n\n  defines constant\n    ECHO_PORT <- 4447\n\n    END_COMMAND <- \"end\"\n\n  defines program\n\n    UdpEchoServer()\n      stdout <- Stdout()\n\n      try\n        -> udpConnection <- UDP(NetworkProperties(port: ECHO_PORT, localOnly: true))\n\n        serving <- true\n        while serving and udpConnection?\n          packet <- udpConnection.receive()\n          if packet?\n            if packet.content == END_COMMAND\n              farewell <- UDPPacket(packet.properties, \"OK will stop the server\")\n              udpConnection.send(farewell)\n              serving: false\n            else\n              udpConnection.send(packet)\n\n      stdout.println(\"UDP server complete\")\n```\n\n`receive()` waits up to the timeout in the properties (five seconds if none was given) and answers an unset packet when\nnothing arrived, which is why the loop tests `packet?`. The server echoes every packet to `packet.properties`, the sender's\naddress, and stops when the content is `end`. The client gives its socket no port at all; a client that gives none is bound\nto an ephemeral one, and the replies come back to it.\n\n```ek9\n#!ek9\ndefines module book.network.udpechoclient\n\n  defines constant\n    ECHO_PORT <- 4447\n\n    END_COMMAND <- \"end\"\n\n  defines function\n\n    exchange()\n      ->\n        client as UDP\n        packet as UDPPacket\n\n      stdout <- Stdout()\n      stdout.println(`sending [${packet.content}]`)\n      client.send(packet)\n      response <- client.receive()\n      if response?\n        stdout.println(`received [${response.content}]`)\n      else\n        stdout.println(`no response [${client.lastErrorMessage()}]`)\n\n  defines program\n\n    UdpEchoClient()\n      localhost <- Networking().loopbackV4()\n\n      try\n        -> client <- UDP(NetworkProperties(timeout: 250ms))\n        exchange(client, UDPPacket(NetworkProperties(localhost, ECHO_PORT), \"a test\"))\n        exchange(client, UDPPacket(NetworkProperties(localhost, ECHO_PORT), END_COMMAND))\n\n      Stdout().println(\"UDP client complete\")\n```\n\nWith the server running in another terminal, the client prints:\n\n```text\nsending [a test]\nreceived [a test]\nsending [end]\nreceived [OK will stop the server]\nUDP client complete\n```\n\nand the server prints `UDP server complete` and exits. The `exchange` function is the place a lost datagram shows up: a\n`receive()` that times out gives an unset packet, and the `else` prints `lastErrorMessage()`. UDP loses packets, and EK9 does\nnot hide that; it gives the loss a value you must look at.\n\n### A server that is a pipeline\n\n`UDP` is also an iterator over the packets it receives: `hasNext()` waits for the next one, and it is false only once the\nconnection is closed or can no longer receive. That makes `while udp.hasNext()` and `cat udp | ...` serve for as long as the\nsocket is open, and the second is a stream pipeline whose source is the network.\n\n```ek9\n#!ek9\ndefines module book.network.udppipelineserver\n\n  defines constant\n    PIPELINE_PORT <- 4448\n\n    STOP_SIGNAL <- \"TERM\"\n\n  defines function\n\n    packetHandler() as abstract\n      -> incoming as UDPPacket\n      <- outgoing as UDPPacket?\n\n  defines program\n\n    UdpPipelineServer()\n      stdout <- Stdout()\n\n      try\n        -> udpConnection <- UDP(NetworkProperties(port: PIPELINE_PORT, localOnly: true))\n\n        stopHandler <- (stdout) is SignalHandler as function\n          result: 0\n          stdout.println(`received ${signal}, stopping the server`)\n\n        Signals().register(STOP_SIGNAL, stopHandler)\n\n        echoFunction <- (udpConnection) is packetHandler\n          outgoing = incoming\n          udpConnection.send(outgoing)\n\n        cat udpConnection | map by echoFunction > stdout\n      stdout.println(\"UDP server complete\")\n```\n\n`packetHandler` is an abstract function, a type that `echoFunction` implements as a dynamic function capturing the\nconnection (*Functions as Values: the Type Hierarchy* is about function types of exactly this kind). `map by echoFunction` sends each packet back\nand `> stdout` prints what comes through. The pipeline has no end of its own, so something must end it, and here it is a\nsignal: `Signals().register(\"TERM\", stopHandler)`. A `SignalHandler` that **assigns a set result** ends the whole process with\nthat exit code; the handler assigns `0`, so the process exits when the signal arrives and the final line of the program never\nruns. A handler that wants a clean shutdown assigns an unset result instead and stops the loop itself, which is what the web\nservice in *A Web Service, Step by Step* does.\n\nThe client side is a pipeline too. `>` into a `UDP` sends each item, using the connection's `|` operator:\n\n```ek9\n#!ek9\ndefines module book.network.udppipelineclient\n\n  defines constant\n    PIPELINE_PORT <- 4448\n\n  defines function\n\n    packetConverter() as abstract\n      -> content as String\n      <- outgoing as UDPPacket?\n\n  defines program\n\n    UdpPipelineClient()\n      host <- Networking().loopbackV4()\n\n      try\n        -> udpConnection <- UDP(NetworkProperties(timeout: 250ms))\n\n        cat [\"first\", \"second\", \"third\"]\n          | map (host) extends packetConverter(outgoing: UDPPacket(NetworkProperties(host, PIPELINE_PORT), content))\n          > udpConnection\n\n      Stdout().println(\"UDP client complete\")\n```\n\nRun the server, run the client, then send the server a `TERM` signal. The client prints `UDP client complete`, and the server\nprints:\n\n```text\nUDPPacket{properties=NetworkProperties{host: 127.0.0.1, port: 55008}, content=\"first\"}\nUDPPacket{properties=NetworkProperties{host: 127.0.0.1, port: 55008}, content=\"second\"}\nUDPPacket{properties=NetworkProperties{host: 127.0.0.1, port: 55008}, content=\"third\"}\nreceived TERM, stopping the server\n```\n\nThe port in each line is the ephemeral one the operating system gave the client's socket, so it differs from run to run.\n\n## Where the addresses come from\n\n*Programs, Input and Output* put it in one sentence: \"A web address, a URL, comes from the environment, through\n`Networking`.\" The programs above use `Networking().loopbackV4()` and a port written into the code, and that is the exception\na loopback demonstration earns. A program that talks to anything real takes the address from the environment, and the\nlanguage enforces it: there is no `URL` literal, and `urlOf` refuses text the compiler can see (E08275).\n\nVolume 1 used `withPath` and `withPathSegment` to build a link from a base address. A service that sends links, in a header\nor in a body, has a sharper problem: the base must be the address the world uses, not the address of the request it is\nanswering. The `Host` header of a request is whatever the caller sent. So a service builds every link from a configured base,\n`PUBLIC_BASE_URL`, and derives the rest with the withers, which keep the base's host.\n\n```ek9\n#!ek9\ndefines module book.network.notelinks\n\n  defines program\n\n    NoteLinks()\n      -> noteId as String\n      stdout <- Stdout()\n\n      base <- Networking().urlFromEnv(\"PUBLIC_BASE_URL\")\n      if base?\n        notes <- base.resolve(\"notes\")\n        stdout.println(`note: ${notes.withPathSegment(noteId)}`)\n        stdout.println(`segments: ${notes.withPathSegment(noteId).pathSegments()}`)\n        stdout.println(`next page: ${notes.withQueryParam(\"page\", \"2\")}`)\n      else\n        stdout.println(\"PUBLIC_BASE_URL is not set, or is not an http or https URL\")\n```\n\n`resolve` joins a path onto the base; `withPathSegment` encodes its text as **one** segment, so the `/` in `A/42` cannot\nreshape the path; `withQueryParam` adds a query. With the variable unset, then set (the spelling is deliberately untidy, and\n`resolve` keeps the base's `/api/` prefix):\n\n```console\n$ ek9 NoteLinks.ek9 A/42\n$ PUBLIC_BASE_URL='HTTPS://Notes.Example.COM:443/api/' ek9 NoteLinks.ek9 A/42\n```\n\n```text\nPUBLIC_BASE_URL is not set, or is not an http or https URL\n```\n\n```text\nnote: https://notes.example.com/api/notes/A%2F42\nsegments: [\"api\", \"notes\", \"A/42\"]\nnext page: https://notes.example.com/api/notes?page=2\n```\n\nThe scheme and host are lower-cased and the default port is dropped, so two spellings of one address are written one way.\n\n### A policy for destinations\n\nA program that reads URLs from its environment is configurable; it is not yet constrained. The `EK9_URL_POLICY` environment\nvariable names a file of `allow` and `deny` lines, and every URL the program makes from the environment is checked against it\nas the program runs.\n\n```text\n# The destinations this program may use (EK9_URL_POLICY=url-policy.txt)\nallow  *.partner.example\ndeny   169.254.169.254/32\n```\n\nThe program reads three variables and reports what it was allowed to make:\n\n```ek9\n#!ek9\ndefines module book.network.destinations\n\n  defines function\n\n    report()\n      -> variableName as String\n      stdout <- Stdout()\n      destination <- Networking().urlFromEnv(variableName)\n      if destination?\n        stdout.println(`${variableName}: ${destination}`)\n      else\n        stdout.println(`${variableName}: refused or not set`)\n\n  defines program\n\n    CheckDestinations()\n      report(\"PARTNER_URL\")\n      report(\"METADATA_URL\")\n      report(\"OTHER_URL\")\n```\n\nRun with the policy, and the log format set to plain text so the refusals are readable (they go to standard error):\n\n```console\n$ EK9_URL_POLICY=url-policy.txt EK9_SANITIZER_LOG_FORMAT=SIMPLE \\\n  PARTNER_URL=https://api.partner.example/v1 \\\n  METADATA_URL=http://169.254.169.254/latest/meta-data/ \\\n  OTHER_URL=https://elsewhere.example.org/ ek9 CheckDestinations.ek9\n```\n\n```text\nPARTNER_URL: https://api.partner.example/v1\n[URL_REFUSED] URL refused by the URL policy host=169.254.169.254 entry=deny 169.254.169.254/32 file=url-policy.txt\nMETADATA_URL: refused or not set\n[URL_REFUSED] URL refused by the URL policy host=elsewhere.example.org entry=no allow entry matches file=url-policy.txt\nOTHER_URL: refused or not set\n```\n\nThe partner is allowed by its `allow` line. The cloud metadata address is refused by a `deny` line, and the third destination\nby the absence of any `allow` line that matches it. With the same three variables and no policy, all three are made:\n\n```text\nPARTNER_URL: https://api.partner.example/v1\nMETADATA_URL: http://169.254.169.254/latest/meta-data/\nOTHER_URL: https://elsewhere.example.org/\n```\n\nSo a policy file is opt-in, and a program run without one allows every destination. A policy that cannot be read is not\nignored. With a typing mistake on line 3 of the file, the program does not start:\n\n```text\nek9: URL policy could not be loaded (exit 18)\nEK9_URL_POLICY: url-policy-broken.txt line 3: expected 'allow' or 'deny' followed by one target, found 'den    169.254.169.254/32'\n```\n\nThe policy is a deployment decision, made by whoever runs the program. An HTTP client library gives you none of this: the\ndestinations it may reach are whatever the code decides to call.\n\n## The client side of HTTP\n\nThe last piece is the client of the server in *A Web Service, Step by Step*. `HTTPClient` is a closeable that the `try` owns, `send` takes an\n`HTTPClientRequest` and gives back a `Result of (HTTPClientResponse, HTTPError)`, and the program below runs a service and its\ncaller in one process on a port the operating system chose, the shape of `EchoInProcess` again.\n\n```ek9\n#!ek9\ndefines module book.network.serveandcall\n\n  defines function\n\n    describe()\n      -> result as Result of (HTTPClientResponse, HTTPError)\n      stdout <- Stdout()\n      if result.isOk()\n        response <- result.ok()\n        stdout.println(`${response.status()} ${response.header(\"Content-Type\")}: ${response.bodyText(\"UTF-8\")}`)\n      else if result.isError()\n        stdout.println(`not sent: ${result.error()}`)\n\n    callGreeting()\n      -> port as Integer\n      stdout <- Stdout()\n      base <- Networking().urlOf(`http://127.0.0.1:${port}/greeting`)\n      get <- HTTPMethod(\"GET\")\n      try\n        -> client <- HTTPClient()\n        describe(client.send(HTTPClientRequest(get, base.withPathSegment(\"Ada\"))))\n\n        missing <- client.send(HTTPClientRequest(get, base.resolve(\"/nothing\")))\n        if missing.isOk()\n          stdout.println(`${missing.ok().status()} for /nothing`)\n\n        describe(client.send(HTTPClientRequest(HTTPMethod(\"TRACE\"), base)))\n\n  defines service\n\n    Greeting for :/greeting open\n\n      greet() as GET for :/{name}\n        -> personName as String :=: PATH \"name\"\n        <- response as HTTPResponse: (who: personName) with trait of HTTPResponse\n          override status() as pure\n            <- rtn as Integer: 200\n          override content()\n            <- rtn as Bytes: Bytes().withUtf8(`hello ${who}`)\n          override contentType() as pure\n            <- rtn as String: \"text/plain\"\n          override cacheControl() as pure\n            <- rtn as String: \"no-store\"\n          default operator ?\n\n  defines application\n\n    GreetingApp\n      register Greeting()\n\n  defines program\n\n    ServeAndCall() with application of GreetingApp\n      properties <- NetworkProperties(0, true)\n      try\n        -> httpServer <- HTTP(properties)\n        caller <- (properties) is HTTPReadyHandler as function\n          callGreeting(properties.port)\n          server.stop()\n        httpServer.serveUntilComplete(caller)\n```\n\n```text\n200 text/plain; charset=utf-8: hello Ada\n404 for /nothing\nnot sent: PROTOCOL_ERROR: the request is not set\n```\n\nThree results, three meanings. The first request is answered, so the `Result` is ok and carries a response. The second is\nanswered with a 404: an error **status** is a response, so it is also an ok `Result`, and the program reads `status()`, not\nthe error side. The third asks for a method, `TRACE`, that is not one of the seven `HTTPMethod` values, so the request itself\nis unset and the `Result` carries an `HTTPError`; nothing is thrown and nothing is sent. The port is only known at run time,\nwhich is why `urlOf` is permitted here.[^stderr]\n\n## What the model costs\n\nYou give up control of the socket. A `NetworkProperties` record has seven fields (`host`, `port`, `packetSize`, `timeout`,\n`backlog`, `maxConcurrent`, `localOnly`), `TCP` has one `connect()` that takes no arguments, and there is no host-and-port\nconstructor to reach for; if a socket option is not one of those fields, it is not available. The streams are text: a TCP\nhandler is given a `StringInput` and a `StringOutput`, and the content of a `UDPPacket` is a `String`, so a binary protocol has\nno direct route through these types. Failures arrive as unset values and a `lastErrorMessage()` you must remember to read,\nwhich is lighter than an exception and easier to ignore. And the stop-and-close split means a handler cannot do the one thing\nevery socket tutorial shows it doing.\n\nIn exchange, two bugs of hand-written servers are closed off. A server opened in a `try` is not left open, because\nthe close is generated and runs when the `try` ends, on every path. It cannot be closed under a thread that is serving,\nbecause the language refuses the call. And because the settings are one record and the addresses come from the environment,\nthe question \"what can this program talk to?\" is answered by reading a few lines and a policy file, not the call graph. The\npackage-level version of that question, which system powers a program may use at all, is the subject of *Packaging and Sharing\nYour Program*.\n\n> **A design note.** Every language lets you close a socket from whichever thread holds the button, so people do, and the\n> thread still reading it finds out afterwards. I would rather the language did not let you write it. A handler may *ask* the\n> server to stop, because stopping is a request the owner can honour in its own time; only the owner may close, because only\n> the owner knows that nobody is still using it. *- Steve*\n\n[^stopclose]: The same rule is why the closeable family has no `close()` call at all: `ek9 -h E81060` lists the three places\nthe compiler generates a close, and *Errors and Exceptions* covers the resources a `try` owns.\n\n[^stderr]: `HTTP` logs through `java.util.logging`, so a run also prints two `INFO:` lines on standard error, one when the\nserver starts listening and one when it stops. The block above is standard output only.\n","examples":["books/ek9-in-depth/ch36-networking-tcp-udp/CheckDestinations.ek9","books/ek9-in-depth/ch36-networking-tcp-udp/EchoInProcess.ek9","books/ek9-in-depth/ch36-networking-tcp-udp/LineClient.ek9","books/ek9-in-depth/ch36-networking-tcp-udp/LineServer.ek9","books/ek9-in-depth/ch36-networking-tcp-udp/NoteLinks.ek9","books/ek9-in-depth/ch36-networking-tcp-udp/ServeAndCall.ek9","books/ek9-in-depth/ch36-networking-tcp-udp/UdpEchoClient.ek9","books/ek9-in-depth/ch36-networking-tcp-udp/UdpEchoServer.ek9","books/ek9-in-depth/ch36-networking-tcp-udp/UdpPipelineClient.ek9","books/ek9-in-depth/ch36-networking-tcp-udp/UdpPipelineServer.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"A Web Service, Step by Step","url":"https://ek9.io/books/ek9-in-depth/web-service-step-by-step.html","markdown":"# A Web Service, Step by Step\n\n*Programs, Input and Output* closed its notes-keeper on a sentence about the boundary: \"Everything that arrives from outside\nstarts as plain text ... It might be missing, or the wrong shape. The boundary is where you check, and EK9 makes sure you\ndo.\" That program kept notes in a file for one person at a terminal. This chapter puts the same notes behind HTTP, for any\nnumber of callers at once, and the boundary stops being one command line and becomes every request. It is also where\n*Collections* is paid: it said that \"the second volume covers JSON in full\", and the notes arrive and leave as JSON.\n\nIf you know Spring Boot, Express, Flask or axum, you know the shape. A route is a function you register; state lives wherever\nyou put it; body parsing, validation and security headers are libraries you add; and whether the pieces are wired together is\nfound out when the first request arrives. EK9 builds the service into the language, which moves some of those decisions into\nthe compiler and the rest into the runtime.\n\n| The concern | Spring Boot | Express | EK9 |\n|---|---|---|---|\n| A route | an annotation on a method | `app.get(path, fn)` | an operation or operator of a `service`, bound with `for :/path` |\n| Shared state | a singleton bean | a module variable | a component; a service cannot have fields |\n| Refuse bad input | validation annotations | middleware | a `sanitized` parameter, and typed bindings |\n| Security headers | security configuration | a middleware package | the runtime, on every response |\n| Wiring mistakes | at start-up | at the first request | compile errors (E12020, E12021) |\n\nThe chapter builds the service in steps, and each step is a program that was compiled and run, with the requests made by\n`curl` from a shell. Every server binds the loopback address only and uses a port in the 8081-8095 range. To follow along,\nstart a server in one terminal and use another for the requests; to make the commands short, give that second terminal two\nconveniences:\n\n```console\n$ export NOTES=http://127.0.0.1:8081\n$ alias notes='curl -s -w \"\\n%{http_code}\\n\"'\n```\n\nThe alias prints the response body and then the status code on a line of its own.\n\n## Step one: the smallest service that serves\n\nHere is a service with one route, and the program that serves it until it is told to stop.\n\n```ek9\n#!ek9\ndefines module book.notesservice.hello\n\n  defines constant\n    HELLO_PORT <- 8083\n\n    STOP_SIGNAL <- \"TERM\"\n\n  defines service\n\n    Greeting for :/greeting open\n\n      hello() as GET for :/{name}\n        -> personName as String :=: PATH \"name\"\n        <- response as HTTPResponse: (who: personName) with trait of HTTPResponse\n          override status() as pure\n            <- rtn as Integer: 200\n          override content()\n            <- rtn as Bytes: Bytes().withUtf8(`hello ${who}, the notes service is running`)\n          override contentType() as pure\n            <- rtn as String: \"text/plain\"\n          override cacheControl() as pure\n            <- rtn as String: \"no-store\"\n          default operator ?\n\n  defines application\n\n    GreetingApp\n      register Greeting()\n\n  defines program\n\n    ServeGreeting() with application of GreetingApp\n      stdout <- Stdout()\n\n      try\n        -> server <- HTTP(NetworkProperties(port: HELLO_PORT, localOnly: true))\n\n        stopOnTerm <- (server, stdout) is SignalHandler as function\n          result: Integer()\n          stdout.println(`received ${signal}, stopping`)\n          server.stop()\n\n        Signals().register(STOP_SIGNAL, stopOnTerm)\n        stdout.println(`serving on port ${HELLO_PORT}`)\n        if server.serve()\n          stdout.println(\"stopped, in-flight requests drained\")\n      stdout.println(\"the try has closed the server\")\n```\n\nA `service` is routes bound to operations. `Greeting for :/greeting open` names the service and the path it lives under;\n`hello() as GET for :/{name}` is one route, and `-> personName as String :=: PATH \"name\"` binds the `{name}` segment of the\npath to the parameter. `open` declares that the service has no security gate; the help for `service` says only that, and the\nword is there so that an ungated service is a decision somebody wrote down.\n\nThe return value is an `HTTPResponse`, and it is made where it is needed: `(who: personName) with trait of HTTPResponse`\nbuilds a dynamic class that **captures** the parameter into a field called `who` and overrides the parts of the response it\ncares about (*Dynamic Functions and Classes* covers what that construct is). `status()`, `contentType()` and the rest are\nmethods because a response is an object the server interrogates, not a value you return a number into.\n\nThe program is where the service meets the network. `ServeGreeting() with application of GreetingApp` is wired to the\napplication that registers `Greeting`, and the program creates **one** `HTTP` server from a `NetworkProperties` and calls\n`serve()`, which blocks until something calls `stop()`.\n\nRun it, and from another terminal:\n\n```console\n$ curl -s -i http://127.0.0.1:8083/greeting/Ada\n```\n\n```text\nHTTP/1.1 200 OK\nServer: \nX-frame-options: DENY\nReferrer-policy: strict-origin-when-cross-origin\nPermissions-policy: geolocation=(), camera=(), microphone=()\nDate: Mon, 16 Nov 2026 11:12:08 GMT\nContent-security-policy: default-src 'none'\nContent-type: text/plain; charset=utf-8\nContent-language: en\nContent-length: 39\nX-content-type-options: nosniff\nCache-control: no-store\n\nhello Ada, the notes service is running\n```\n\nNothing in the program set most of those headers. The runtime adds the `X-frame-options`, `Referrer-policy`,\n`Permissions-policy`, `Content-security-policy` and `X-content-type-options` headers to **every** response, and supplies a\n`Content-language` when the response does not override it. The security headers are the runtime's decision, not middleware\nyou must remember to install, and the cost is that the defaults are the runtime's too: the way to a different one is to\noverride the method on the response. `Cache-control` is the one header with no default: the response sent `no-store`\nbecause it said so.\n\n### Every response says how it may be cached\n\n`cacheControl()` is the one method of `HTTPResponse` that a response must write. Leave it out and the response does not\ncompile: E07140 for a dynamic class like this one, E07130 for a named class. That is deliberate. Caching is where the\nHTTP underneath a web service is most easily lost from view, and a framework that decides it for you hides the decision\nfrom the person who should make it. The HTTP Archive's measurements of real sites found a quarter of requests sending\nneither `Cache-Control` nor `Expires`, and a quarter sending neither `ETag` nor `Last-Modified`, so no cache can ask\nwhether its copy is still current.[^almanac] A widely used Java security framework sends `no-store` on every response\nuntil the application sets its own:[^spring] safe for a page behind a login, and also the reason many services are never\ncached at all. The opposite mistake is worse: a shared cache that keeps one person's response hands it to the next, and a\nstudy of real sites found private data and login tokens leaking that way.[^deception]\n\nLeaving the header out does not switch caching off either. A cache given no lifetime may guess one,[^heuristic] so every\ncache between the server and the reader would decide for itself. The answers a response usually wants are four:\n\n| `cacheControl()` | what a cache may do |\n|---|---|\n| `no-store` | keep nothing: one person's data, an error, anything that changes |\n| `no-cache` | keep it, but ask the server before each use; with an `etag()` or `lastModified()`, an unchanged answer is a `304 Not Modified` with no body |\n| `private, max-age=60` | keep it for a minute, in the reader's own browser only |\n| `public, max-age=3600` | keep it for an hour, in any cache, a shared one too |\n\n`no-cache` does not mean \"not cached\"; that is `no-store`. The two are confused often enough that the same measurements\ncounted over three million responses sending both.[^almanac] And because the server asks `etag()` and `lastModified()`\nbefore `content()`, a `304` costs no body at all: not only no bytes on the wire, but no work building them. A filter that\nworks its tag out from the finished body still builds the body on every request.[^shallow]\n\nA team that wants a default of its own still writes one, once: a trait of its own over `HTTPResponse` that declares\n`cacheControl()`, or one function that builds every response, as `reply()` does later in this chapter. The difference is\nwhere the default lives: in the program, where the next person to read it can see it.\n\nThe path is decoded before it reaches the parameter, so a space arrives as a space, and an address nobody mapped is a 404:\n\n```console\n$ notes 'http://127.0.0.1:8083/greeting/Grace%20Hopper'\n$ notes http://127.0.0.1:8083/nothing\n```\n\n```text\nhello Grace Hopper, the notes service is running\n200\n404 Not Found\n404\n```\n\n### Stopping it\n\n`serve()` returns when `stop()` is called, and the thing that calls it is a signal handler registered with\n`Signals().register(\"TERM\", stopOnTerm)`. The handler is a dynamic function that captures the server and `stdout`, and its\nfirst line, `result: Integer()`, is the most important one: a `SignalHandler` that assigns a **set** result ends the process\nwith that exit code, as the UDP server in *Networking: TCP and UDP* did, and an **unset** result means \"I have dealt with it,\ncarry on\". This one stops the server and lets `serve()` return, so the `try` can close it. Sending the process `TERM`\nproduced:\n\n```text\nserving on port 8083\nNov 10, 2026 10:15:12 PM org.ek9.lang.HTTP doStart\nINFO: EK9 HTTP server listening on /127.0.0.1:8083\nreceived TERM, stopping\nNov 10, 2026 10:15:12 PM org.ek9.lang.HTTP lambda$stop$0\nINFO: EK9 HTTP server stopped serving\nstopped, in-flight requests drained\nthe try has closed the server\n```\n\nThe two `INFO:` lines are `java.util.logging` on standard error, written by the `HTTP` runtime on every start and stop;\nthe other lines are the program's. `stop()` drains requests that are already in flight, for up to five seconds, before\n`serve()` returns `true`.\n\nLeave out the assignment to `result`, and the compiler refuses the handler:\n\n```ek9\nstopOnTerm <- (stdout) is SignalHandler as function\n  stdout.println(`received ${signal}, stopping`)\n```\n\n```text\nEK9     : Error   : E08050: '(' on line 9 position 20: 'result': return value is not always initialised\n             See: ek9 -h E08050\n```\n\nA dynamic function that implements a function type inherits that type's returning variable, but its body replaces the\nsuper's body, so every path must assign it. There is no default of \"carry on\"; the choice between exiting and continuing is\none you state.\n\n### Wiring, checked both ways\n\nA service nobody serves is a quiet failure in many frameworks: the routes are registered, the process runs, and every\nrequest is a 404. EK9 checks the pairing in both directions. A program that uses an application which registers a service,\nand creates no `HTTP`:\n\n```ek9\nServeNotes() with application of NotesApp\n  Stdout().println(\"serving notes\")\n```\n\n```text\nEK9     : Error   : E12020: 'ServeNotes' on line 31 position 4: program 'ServeNotes' uses application 'NotesApp' which registers services, but creates no HTTP: application registers services but program has no HTTP server\n             See: ek9 -h E12020\n```\n\nand the other way round, an `HTTP` server over an application that registers no service:\n\n```ek9\nServeNothing() with application of LogApp\n  try\n    -> server <- HTTP(NetworkProperties(port: 8081, localOnly: true))\n    server.serve()\n```\n\n```text\nEK9     : Error   : E12021: 'server' on line 27 position 11: program 'ServeNothing' creates HTTP but application 'LogApp' has no service registrations: program creates HTTP but application has no service registrations\n             See: ek9 -h E12021\n```\n\nA third rule completes it: an `HTTP` in a program with no `with application of` linkage is E12022, and a second `HTTP` in\none program is E12023. The limit of the check is what it can see. It proves that a program that serves is wired to a\nservice, not that the routes in the service are the ones you meant, which the later steps show.\n\n## Step two: the model\n\nThe notes domain is a record, a message table and nothing else.\n\n```ek9\ndefines record\n  Note\n    id <- Integer()\n    text <- String()\n\n    default Note() as pure\n\n    Note() as pure\n      ->\n        noteId as Integer\n        noteText as String\n\n      id :=? Integer(noteId)\n      text :=? String(noteText)\n\n    Note() as pure\n      -> from as Note\n\n      id :=? Integer(from.id)\n      text :=? String(from.text)\n\n    default operator ?\n    default operator :=:\n    default operator $$\n```\n\nThe record is Volume 1's, in the shorter field style. Its `default operator $$` is the interesting line: `$$` means \"this as\nJSON\", and a `default` writes it from the fields. A note's JSON form is an object with its two fields, and a list of notes is\nan array of them; the chapter returns to `$$` below. `default operator :=:` makes a note copyable, the constructor that takes a\n`Note` makes a new one from another, and `default operator ?` says that a note is set when both of its fields are.\n\nThe words the service speaks are not in the logic. They are a `text` construct:\n\n```ek9\ndefines text for \"en\"\n  NoteMessages\n\n    noSuchNote()\n      -> noteId as Integer\n      `there is no note numbered ${noteId}`\n\n    notJson()\n      `the body is not valid JSON`\n\n    needsText()\n      `a note needs a non-empty \"text\" field`\n```\n\n`NoteMessages(\"en\")` selects the English block, and `noSuchNote(noteId)` is a method that returns the text with the number\ninterpolated. A second locale is a second `defines text for \"fr\"` block with the same names; the compiler checks that the\nblocks agree (*Speaking Every Language* in Volume 1). The service below only ever asks for `\"en\"`.\n\n## Step three: state behind a lock, behind a component\n\nA `service` has no fields; the grammar forbids them. The help for `service` gives the reason in a line: services are\nstateless so that they can be scaled out without split state, and any state belongs in components, which are managed\nsingletons. So the notes live in a plain class, `NoteBook`, which knows nothing about threads:\n\n```ek9\ndefines class\n  NoteBook\n    notes <- Dict() of (Integer, Note)\n    lastId <- 0\n\n    add()\n      -> noteText as String\n      <- rtn <- Note()\n\n      lastId++\n      rtn: Note(lastId, noteText)\n      notes += DictEntry(rtn.id, rtn)\n\n    find()\n      -> noteId as Integer\n      <- rtn <- Optional() of Note\n\n      if notes contains noteId\n        rtn: Optional(Note(notes.getOrDefault(noteId, Note())))\n```\n\nand are reached through a component, a `NoteRepository` with an abstract contract and one implementation that owns the\nlock:\n\n```ek9\nLockedNoteRepository extends NoteRepository\n  lockedBook as MutexLock of NoteBook: MutexLock(NoteBook())\n\n  override add()\n    -> noteText as String\n    <- rtn <- Note()\n\n    accessKey <- (noteText, rtn) is MutexKey of NoteBook as function\n      rtn :=: lockedItem.add(noteText)\n    require lockedBook.enter(accessKey)\n```\n\n`MutexLock of NoteBook` is the only door to the book. `enter` takes a `MutexKey`, a function that is handed the locked item\nas `lockedItem`, and the dynamic function `accessKey` captures what it needs (the argument and the return variable) and does\nits work inside the lock. The other five methods have exactly this shape, so the book has no unlocked path. Nor does\nanything leave it: `find` hands back a new note made from the stored one, never the stored note itself. An `Optional` holding\nthe note the book keeps would let a request change it outside the lock, and the compiler refuses that (E08258). *Concurrency,\nSafely* is the chapter on `MutexLock` and on what the compiler checks about locks.\n\nA service gets the component it needs by declaring it with a `!` where it is used. That is the whole of injection at the point\nof use:\n\n```ek9\nrepository as NoteRepository!\n```\n\nThe application decides which implementation that is (*Dependency Injection and Applications* covers the registry), so a\ntest can register a different one without the service noticing. A sanity check that the lock does its job: forty `POST`\nrequests fired at once from the shell, then the notes counted.\n\n```console\n$ for n in $(seq 1 40); do curl -s -o /dev/null -X POST -d \"{\\\"text\\\": \\\"note $n\\\"}\" $NOTES/notes & done; wait\n$ curl -s $NOTES/notes | grep -o '\"id\":[0-9]*' | sort -u | wc -l\n$ curl -s $NOTES/notes | grep -o '\"id\":[0-9]*' | sort -t: -k2 -n | tail -1\n```\n\n```text\n      40\n\"id\":40\n```\n\nForty distinct ids, the highest being 40. That shows the lock works on this run; it is not a proof, and what EK9 proves about\nlocks is the scope *Concurrency, Safely* states.\n\n## Step four: a response that already knows its status\n\nA response object is asked by the server for its content first, and only then for its status and the other headers\n(an `etag()` or `lastModified()` check comes before both, so a `304 Not Modified` builds no body). So a response may work\nout its status while it builds its content. Here is a response that does exactly that:\n\n```ek9\nLateResponse with trait of HTTPResponse\n  code as Integer: STATUS_OK\n\n  override cacheControl() as pure\n    <- rtn as String: \"no-store\"\n\n  override status() as pure\n    <- rtn as Integer: code\n\n  override content()\n    <- rtn as Bytes: Bytes()\n\n    code := STATUS_NOT_FOUND\n    rtn: Bytes().withUtf8(\"there is no such note\")\n\n  override contentType() as pure\n    <- rtn as String: \"text/plain\"\n\n  default operator ?\n```\n\n`status()` answers from the field `code`; `content()` finds there is no such note and sets `code` to 404. It is served on\nport 8084:\n\n```console\n$ curl -s -i http://127.0.0.1:8084/late\n```\n\n```text\nHTTP/1.1 404 Not Found\nServer: \nX-frame-options: DENY\nReferrer-policy: strict-origin-when-cross-origin\nPermissions-policy: geolocation=(), camera=(), microphone=()\nDate: Mon, 16 Nov 2026 11:12:08 GMT\nContent-security-policy: default-src 'none'\nContent-type: text/plain; charset=utf-8\nContent-language: en\nContent-length: 21\nX-content-type-options: nosniff\nCache-control: no-store\n\nthere is no such note\n```\n\nThe status line and the body agree: the note does not exist. Even so, the rest of the service follows a plainer rule, which\ncosts a little ceremony: **an operation decides, and builds a response that reports what was decided.** The operation does\nthe work, picks the status, and only then calls a function that makes a response with that status already in it. Every\nresponse in this service says its own status, and none of them depends on the order the server asks in.\n\n```ek9\nreply()\n  ->\n    status as Integer\n    body as String\n    location as String\n  <- response as HTTPResponse: (status: status, body: body, location: location) with trait of HTTPResponse\n    override status() as pure\n      <- rtn as Integer: status\n    override content()\n      <- rtn as Bytes: body? <- Bytes().withUtf8(body) else Bytes()\n    override contentType() as pure\n      <- rtn as String: \"application/json\"\n    override cacheControl() as pure\n      <- rtn as String: \"no-store\"\n    override contentLocation() as pure\n      <- rtn as String: location\n    default operator ?\n\nanswer()\n  ->\n    status as Integer\n    body as String\n  <- response as HTTPResponse: reply(status, body, String())\n\ncreated()\n  ->\n    body as String\n    location as String\n  <- response as HTTPResponse: reply(STATUS_CREATED, body, location)\n\nproblem()\n  ->\n    status as Integer\n    message as String\n  <- response as HTTPResponse: answer(status, $${\"error\": message})\n```\n\n`reply` is the one place that builds a response: a status, a JSON body and an optional location, captured by name. The\nthree functions below it are the cases: `answer` for a status and a body, `created` for a 201 that carries the new note's\naddress, and `problem`, which wraps a message as a JSON object, `{\"error\": ...}`. A `Dict` has a `$$` too, so the message is\nescaped by the same operator that writes the notes, and there is no string concatenation anywhere near a quote. An empty body,\nas in a 204, is `Bytes()` and is chosen with the usual set test, `body?`.\n\n## Step five: JSON in, JSON out\n\nThree things in the service touch JSON: the notes going out, the body coming in, and the error. Going out is `$$`. Coming in\nis `JSON().parse`, which does not throw: it returns a `Result of (JSON, String)`, the same type you met in *Optional and\nResult, in Depth*, with the parser's complaint on the error side. A program that exercises the whole surface in one place:\n\n```ek9\n#!ek9\ndefines module book.notesservice.jsondocuments\n\n  defines constant\n    TEXT_FIELD <- \"text\"\n\n    TAGS_FIELD <- \"tags\"\n\n    MISSING_FIELD <- \"pinned\"\n\n  defines record\n    Note\n      id <- Integer()\n      text <- String()\n\n      default Note() as pure\n\n      Note() as pure\n        ->\n          noteId as Integer\n          noteText as String\n\n        id :=? Integer(noteId)\n        text :=? String(noteText)\n\n      default operator $$\n      default operator ?\n\n  defines function\n\n    textOf() as pure\n      ->\n        document as JSON\n        field as String\n      <- rtn as String: cat [document.get(field)] | collect as String\n\n    describe()\n      -> document as JSON\n      stdout <- Stdout()\n\n      noteText <- document.get(TEXT_FIELD)\n      stdout.println(`as JSON: ${noteText}`)\n      stdout.println(`as text: ${textOf(document, TEXT_FIELD)}`)\n\n      tags <- document.get(TAGS_FIELD)\n      stdout.println(`tags: ${tags.arrayLength()} of them`)\n      for tag in tags\n        stdout.println(`tag: ${textOf(tag, TEXT_FIELD)}`)\n\n      stdout.println(`pinned set: ${document.get(MISSING_FIELD)?}`)\n\n  defines program\n\n    JsonDocuments()\n      stdout <- Stdout()\n\n      body <- \"{\\\"text\\\": \\\"buy \\\\\\\"oat\\\\\\\" milk\\\", \\\"tags\\\": [{\\\"text\\\": \\\"home\\\"}, {\\\"text\\\": \\\"urgent\\\"}]}\"\n      parsed <- JSON().parse(body)\n      if parsed.isOk()\n        describe(parsed.ok())\n\n      broken <- JSON().parse(\"{not json\")\n      stdout.println(`broken: ok ${broken.isOk()} error ${broken.isError()}`)\n\n      nothing <- JSON().parse(\"\")\n      stdout.println(`empty body: ok ${nothing.isOk()} error ${nothing.isError()}`)\n\n      array <- JSON().parse(\"[1, 2]\")\n      if array.isOk()\n        stdout.println(`an array has a text field: ${array.ok().get(TEXT_FIELD)?}`)\n\n      stdout.println($$Note(1, \"milk\"))\n      stdout.println($$[Note(1, \"milk\"), Note(2, \"bread\")])\n      stdout.println($$Note())\n```\n\n```text\nas JSON: \"buy \\\"oat\\\" milk\"\nas text: buy \"oat\" milk\ntags: 2 of them\ntag: home\ntag: urgent\npinned set: false\nbroken: ok false error true\nempty body: ok false error true\nan array has a text field: false\n{\"id\":1,\"text\":\"milk\"}\n[{\"id\":1,\"text\":\"milk\"},{\"id\":2,\"text\":\"bread\"}]\n{\"id\":null,\"text\":null}\n```\n\nRead it in order. `document.get(\"text\")` answers a `JSON`, not a `String`, and printing it gives the JSON form, quoted and\nescaped. To get the text the property holds, the helper streams the one value into a `String`: `cat [document.get(field)] |\ncollect as String`. `String(json)` is not the way, because it gives the JSON form too. A JSON array iterates with `for`, and\n`arrayLength()` counts it. `get` of a property that is not there answers an unset `JSON`, so a missing field is tested with `?`\nlike any other absence; `get` on an array, or on a scalar, answers unset the same way.\n\nThe last four lines are the edges that matter at a boundary. Malformed text is an error `Result`, as expected, and so is an empty\nbody: there is no document in it, so it is answered like any other text that does not parse, which is why the service\nanswers an empty `POST` with 400. And `$$` of an unset record writes\nthe JSON text `null` for each unset field. The service never emits that, because it only serialises notes it has just made or found.\n\nThe service's use of the `Result` follows the rule from *Optional and Result, in Depth*: the error side is read only inside a\ncheck of the error side. Here it is not read at all, because the 400 does not need the parser's message.\n\n```ek9\ntextOf()\n  ->\n    document as JSON\n    field as String\n  <- rtn as String: cat [document.get(field)] | collect as String\n\nlinkTo()\n  -> noteId as Integer\n  <- rtn <- String()\n\n  base <- Networking().urlFromEnv(BASE_URL_NAME)\n  if base?\n    link <- base.resolve(\"notes\").withPathSegment($noteId)\n    rtn: $link\n```\n\n```ek9\naddNote()\n  ->\n    repository as NoteRepository\n    body as String\n  <- response as HTTPResponse?\n\n  parsed <- JSON().parse(body)\n  if parsed.isOk()\n    noteText <- textOf(parsed.ok(), TEXT_FIELD)\n    if noteText?\n      saved <- repository.add(noteText)\n      response: created($$saved, linkTo(saved.id))\n    else\n      response: problem(STATUS_UNPROCESSABLE, NoteMessages(\"en\").needsText())\n  else\n    response: problem(STATUS_BAD_REQUEST, NoteMessages(\"en\").notJson())\n```\n\n`addNote` is the whole decision tree of a `POST`, and its three outcomes are three statuses: a body that is not JSON, an empty one included, is a 400,\na document with no usable `text` is a 422 (the syntax was fine; the content was not), and a good one is saved and answered\nwith a 201 whose `Content-location` is built by `linkTo`. `linkTo` takes the address from `PUBLIC_BASE_URL`, the base the\nservice is deployed at, and derives the note's address with `resolve` and `withPathSegment`, as in *Networking: TCP and UDP*.\nIt never uses the `Host` header of the request, which is whatever the caller sent. The `else` of `isOk()` is deliberate\nrather than lazy: `else` of an ok-check is the correct place for \"anything that did not parse\".\n\n## Step six: the routes\n\nAll the logic is in functions, so the service is only a binding layer: it says which part of the request becomes which\nargument, and calls one function.\n\n```ek9\ndefines service\n\n  Notes for :/notes open\n\n    search() as GET for :/search\n      -> query as sanitized String :=: QUERY \"query\"\n      <- response as HTTPResponse?\n\n      repository as NoteRepository!\n      found <- repository.matching(query)\n      response: answer(STATUS_OK, $$found)\n\n    list() as GET for :/\n      <- response as HTTPResponse?\n\n      repository as NoteRepository!\n      notes <- repository.all()\n      response: answer(STATUS_OK, $$notes)\n\n    byId() as GET for :/{id}\n      -> noteId as Integer :=: PATH \"id\"\n      <- response as HTTPResponse?\n\n      repository as NoteRepository!\n      response: showNote(repository, noteId)\n\n    operator += for :/\n      -> body as String :=: CONTENT\n      <- response as HTTPResponse?\n\n      repository as NoteRepository!\n      response: addNote(repository, body)\n\n    operator :^: for :/{id}\n      ->\n        noteId as Integer :=: PATH \"id\"\n        body as String :=: CONTENT\n      <- response as HTTPResponse?\n\n      repository as NoteRepository!\n      response: replaceNote(repository, noteId, body)\n\n    operator -= for :/{id}\n      -> noteId as Integer :=: PATH \"id\"\n      <- response as HTTPResponse?\n\n      repository as NoteRepository!\n      response: removeNote(repository, noteId)\n```\n\nA route is either a named operation with its verb, `search() as GET for :/search`, or an **operator**, whose symbol is the\nverb: `+=` is a `POST`, `:^:` (replace) is a `PUT`, `:~:` (merge) is a `PATCH` and `-=` is a `DELETE`. The service maps\n`+=`, `:^:` and `-=`, and does not map `:~:`. The binding on each parameter says where it comes from: `PATH \"id\"` is the\n`{id}` segment, `QUERY \"query\"` the query parameter, `CONTENT` the request body, and `HEADER` and `REQUEST` the headers and\nthe whole request. A parameter's **type** is part of the binding: `noteId as Integer :=: PATH \"id\"` means a path that is not a\nwhole number never reaches the operation.\n\n### The program\n\n```ek9\ndefines application\n\n  NotesApp\n    register LockedNoteRepository() as NoteRepository\n    register Notes()\n\ndefines program\n\n  ServeNotes() with application of NotesApp\n    stdout <- Stdout()\n\n    try\n      -> server <- HTTP(NetworkProperties(port: SERVICE_PORT, localOnly: true))\n\n      stopOnTerm <- (server, stdout) is SignalHandler as function\n        result: Integer()\n        stdout.println(`received ${signal}, stopping`)\n        server.stop()\n\n      Signals().register(STOP_SIGNAL, stopOnTerm)\n      stdout.println(`serving notes on port ${SERVICE_PORT}`)\n      if server.serve()\n        stdout.println(\"stopped, in-flight requests drained\")\n    stdout.println(\"the try has closed the server\")\n```\n\n`NotesApp` registers the repository as a `NoteRepository`, which is what `repository as NoteRepository!` asks for, and the\nservice. The program is step one's again, serving the notes service on its own port. Start it with the settings it reads from\nits environment:\n\n```console\n$ PUBLIC_BASE_URL=http://127.0.0.1:8081/ EK9_SANITIZER_LOG_FORMAT=SIMPLE ek9 NotesService.ek9\n```\n\n## Running it\n\nAn empty list, then a `POST`, shown with its headers, because the status and the `Content-location` are the point:\n\n```console\n$ notes $NOTES/notes\n$ curl -s -i -X POST -d '{\"text\": \"buy milk\"}' $NOTES/notes\n```\n\n```text\n[]\n200\nHTTP/1.1 201 Created\nServer: \nX-frame-options: DENY\nReferrer-policy: strict-origin-when-cross-origin\nPermissions-policy: geolocation=(), camera=(), microphone=()\nDate: Tue, 10 Nov 2026 22:15:15 GMT\nContent-security-policy: default-src 'none'\nContent-type: application/json; charset=utf-8\nContent-language: en\nContent-length: 26\nContent-location: http://127.0.0.1:8081/notes/1\nX-content-type-options: nosniff\nCache-control: no-store\n\n{\"id\":1,\"text\":\"buy milk\"}\n```\n\n`reply()` says `no-store`: a note is one person's data, and no cache between the service and its reader may keep it. Then\na second note,\nthe list, one note by number, and a number nobody has:\n\n```console\n$ notes -X POST -d '{\"text\": \"buy bread\"}' $NOTES/notes\n$ notes $NOTES/notes\n$ notes $NOTES/notes/1\n$ notes $NOTES/notes/9\n```\n\n```text\n{\"id\":2,\"text\":\"buy bread\"}\n201\n[{\"id\":1,\"text\":\"buy milk\"},{\"id\":2,\"text\":\"buy bread\"}]\n200\n{\"id\":1,\"text\":\"buy milk\"}\n200\n{\"error\":\"there is no note numbered 9\"}\n404\n```\n\nThe three ways a `POST` can be wrong, each with the status the decision tree gives it:\n\n```console\n$ notes -X POST -d '{not json' $NOTES/notes\n$ notes -X POST -d '{\"title\": \"x\"}' $NOTES/notes\n$ notes -X POST $NOTES/notes\n```\n\n```text\n{\"error\":\"the body is not valid JSON\"}\n400\n{\"error\":\"a note needs a non-empty \\\"text\\\" field\"}\n422\n{\"error\":\"the body is not valid JSON\"}\n400\n```\n\nReplace a note, replace one that is not there, and delete:\n\n```console\n$ notes -X PUT -d '{\"text\": \"buy oat milk\"}' $NOTES/notes/1\n$ notes -X PUT -d '{\"text\": \"x\"}' $NOTES/notes/9\n$ notes -X DELETE $NOTES/notes/2\n$ notes -X DELETE $NOTES/notes/2\n$ notes $NOTES/notes\n```\n\n```text\n{\"id\":1,\"text\":\"buy oat milk\"}\n200\n{\"error\":\"there is no note numbered 9\"}\n404\n\n204\n{\"error\":\"there is no note numbered 2\"}\n404\n[{\"id\":1,\"text\":\"buy oat milk\"}]\n200\n```\n\nThe first `DELETE` answers 204 with no body, which is the empty line before the status; the second finds nothing and says so.\n\n### What the runtime answers for you\n\nSome responses in a session are not written anywhere in the program. A path that is not a whole number, a `PATCH` to a\nroute that has no `PATCH`, and a trailing slash:\n\n```console\n$ notes $NOTES/notes/abc\n$ notes $NOTES/notes/\n$ curl -s -i -X PATCH -d '{\"text\": \"x\"}' $NOTES/notes/1\n```\n\n```text\n{\"error\":\"Bad Request\",\"status\":400,\"detail\":\"Parameter 'noteId' cannot be converted to org.ek9.lang::Integer\",\"parameter\":\"noteId\",\"source\":\"PATH\"}\n400\n404 Not Found\n404\nHTTP/1.1 405 Method Not Allowed\nServer: \nX-frame-options: DENY\nReferrer-policy: strict-origin-when-cross-origin\nPermissions-policy: geolocation=(), camera=(), microphone=()\nDate: Tue, 10 Nov 2026 22:15:15 GMT\nAllow: GET, PUT, DELETE\nContent-security-policy: default-src 'none'\nContent-type: text/plain; charset=utf-8\nContent-length: 22\nX-content-type-options: nosniff\n\n405 Method Not Allowed\n```\n\nThe 400 is the runtime's, in JSON, naming the parameter and where it was bound from. The trailing slash is a different\naddress: a route `for :/` under `Notes for :/notes` is `/notes` exactly, and `/notes/` is a 404. Trailing slashes are\nsignificant everywhere. The 405 carries an `Allow` header that the runtime worked out from the operations mapped on that path,\nwhich is why it lists `GET, PUT, DELETE` and not `POST`.\n\nA parameter you declare as `QUERY` or `HEADER` is **mandatory**. There is no optional query parameter in the binding; a request\nwithout it is a 400 of exactly the shape above. If a parameter is optional, the way to say so is a second route.\n\n### Route order, and the mistake the compiler cannot see\n\nThe compiler checks routes for the same **shape**: two `GET` routes under one path, each with one path variable, are\nduplicates whatever the variables are called and whatever their types, and both are reported as E02070:\n\n```ek9\nbyNumber() as GET for :/{number}\n  -> number as Integer :=: PATH \"number\"\n  <- response as HTTPResponse: plain(`note number ${number}`)\n\nbyName() as GET for :/{name}\n  -> name as String :=: PATH \"name\"\n  <- response as HTTPResponse: plain(`note named ${name}`)\n```\n\n```text\nEK9     : Error   : E02070: 'byNumber' on line 21 position 6: HTTP verb: 'GET' ':/{number}' and ':/{name}': PATH is duplicated in terms of structure/naming\n             See: ek9 -h E02070\nEK9     : Error   : E02070: 'byName' on line 25 position 6: HTTP verb: 'GET' ':/{number}' and ':/{name}': PATH is duplicated in terms of structure/naming\n             See: ek9 -h E02070\n```\n\nWhat it does not check is a literal route after a variable one. These shapes differ, so both compile; but the **first route\ndeclared that matches wins**, and a literal segment does not beat a variable. Here the search route comes after the numeric\none:\n\n```ek9\n#!ek9\ndefines module book.routeorder\n\n  defines constant\n    ORDER_PORT <- 8082\n\n    NOT_STORED <- \"no-store\"\n\n  defines function\n\n    plain()\n      -> text as String\n      <- response as HTTPResponse: (text) with trait of HTTPResponse\n        override status() as pure\n          <- rtn as Integer: 200\n        override content()\n          <- rtn as Bytes: Bytes().withUtf8(text)\n        override contentType() as pure\n          <- rtn as String: \"text/plain\"\n        override cacheControl() as pure\n          <- rtn as String: NOT_STORED\n        default operator ?\n\n  defines service\n\n    Words for :/words open\n\n      byNumber() as GET for :/{number}\n        -> number as Integer :=: PATH \"number\"\n        <- response as HTTPResponse: plain(`word number ${number}`)\n\n      search() as GET for :/search\n        -> query as String :=: QUERY \"query\"\n        <- response as HTTPResponse: plain(`searching for ${query}`)\n\n  defines application\n\n    WordsApp\n      register Words()\n\n  defines program\n\n    ServeWords() with application of WordsApp\n      try\n        -> server <- HTTP(NetworkProperties(port: ORDER_PORT, localOnly: true))\n        server.serve()\n```\n\n```console\n$ notes http://127.0.0.1:8082/words/42\n$ notes 'http://127.0.0.1:8082/words/search?query=pear'\n```\n\n```text\nword number 42\n200\n{\"error\":\"Bad Request\",\"status\":400,\"detail\":\"Parameter 'number' cannot be converted to org.ek9.lang::Integer\",\"parameter\":\"number\",\"source\":\"PATH\"}\n400\n```\n\n`/words/search` matched `/{number}`, failed to become an `Integer`, and was refused; the search route is unreachable and the\ncompiler said nothing. The notes service avoids it by declaring `search` first. This is a real gap, not a feature: the order\nof the declarations is part of the behaviour, and the only check is a request.\n\n## Input in, secrets out\n\nA web boundary is where the two directions of trust meet, and EK9 has a language feature for each.\n\n### Inbound: `sanitized`\n\nThe search route takes `query as sanitized String :=: QUERY \"query\"`. A `sanitized` parameter is cleaned **by the receiver, on\nentry, whatever route calls it**; a value that carries a threat arrives as an unset `String`, and a safe one as the receiver's\nown copy. In a service the binding does the rest: an unset parameter cannot be bound, so the request is refused before the\noperation's body runs. A clean query, a missing one, a SQL injection and a script:\n\n```console\n$ notes \"$NOTES/notes/search?query=milk\"\n$ notes $NOTES/notes/search\n$ notes -G $NOTES/notes/search --data-urlencode \"query=' OR 1=1 --\"\n$ notes -G $NOTES/notes/search --data-urlencode \"query=<script>alert(1)</script>\"\n```\n\n```text\n[{\"id\":1,\"text\":\"buy oat milk\"}]\n200\n{\"error\":\"Bad Request\",\"status\":400,\"detail\":\"Parameter 'query' cannot be converted to org.ek9.lang::String\",\"parameter\":\"query\",\"source\":\"QUERY\"}\n400\n{\"error\":\"Bad Request\",\"status\":400,\"detail\":\"Parameter 'query' cannot be converted to org.ek9.lang::String\",\"parameter\":\"query\",\"source\":\"QUERY\"}\n400\n{\"error\":\"Bad Request\",\"status\":400,\"detail\":\"Parameter 'query' cannot be converted to org.ek9.lang::String\",\"parameter\":\"query\",\"source\":\"QUERY\"}\n400\n```\n\nThe missing query, the injection and the script are the same 400. That is the cost: the caller is not told *why*. The\nreason is in the server's log, one line per threat\n(`EK9_SANITIZER_LOG_FORMAT=SIMPLE` chose this plain form; the default is JSON with a timestamp):\n\n```text\n[SQL_INJECTION] Dangerous input detected: ' OR 1=1 --\n[SQL_INJECTION_SIGNATURE] Dangerous input detected: ' OR 1=1 --\n[XSS] Dangerous input detected: <script>alert(1)</script>\n```\n\nThe service does not mark the note text `sanitized`, and that is a decision, not an omission: a note is data that is stored and\nreturned inside a JSON string that the service escapes, so `<script>` is a legitimate note and a refused one would be a bug.\nThe query is different, because it is compared against stored text. `sanitized` is a tool for the places where text becomes\nsomething else, and it is the author's judgement which places those are.\n\n### Outbound: `Sensitive`\n\nThe other direction is a credential the service holds. Suppose the notes are synchronised to another service with a key. A\n`Sensitive` wraps it so that it cannot be printed, interpolated or serialised by accident, and it cannot be made from a\n`String` at all: the only way to a set one is `EnvVars().sensitiveGet(\"NAME\")`.\n\n```ek9\n#!ek9\ndefines module book.notesservice.synckey\n\n  defines constant\n    SYNC_KEY_NAME <- \"NOTES_SYNC_KEY\"\n\n  defines class\n\n    NoteSync with trait of Privileged\n      syncKey as Sensitive?\n\n      NoteSync()\n        -> key as Sensitive\n        syncKey: key\n\n      default private NoteSync()\n\n      authorisation()\n        <- rtn as String: String()\n\n        if syncKey?\n          rtn: authorisationFor(syncKey.reveal())\n\n      default operator ?\n\n  defines function\n\n    authorisationFor() as pure\n      -> header as String\n      <- rtn as String: `Bearer header of ${length header} characters`\n\n  defines program\n\n    ShowSyncKey()\n      stdout <- Stdout()\n\n      key <- EnvVars().sensitiveGet(SYNC_KEY_NAME)\n      if key?\n        sync <- NoteSync(key)\n        stdout.println(`key: ${key}`)\n        stdout.println(`as JSON: ${$$key}`)\n        stdout.println(sync.authorisation())\n      else\n        stdout.println(`${SYNC_KEY_NAME} is not set`)\n```\n\nWith the variable set, and then unset:\n\n```console\n$ NOTES_SYNC_KEY=example-key-value-1234 ek9 SyncKey.ek9\n$ ek9 SyncKey.ek9\n```\n\n```text\nkey: ***REDACTED***\nas JSON: \"***REDACTED***\"\nBearer header of 22 characters\nNOTES_SYNC_KEY is not set\n```\n\n`$` and `$$` of a `Sensitive` both answer `***REDACTED***`, so interpolating it into a log line or a response cannot leak it.\nThe program can still use the key, because `NoteSync` has the `Privileged` trait, and `reveal()` is legal only in a method of a\nclass or trait that is `Privileged`:\n\n```ek9\ndescribe()\n  <- rtn as String: String()\n  if syncKey?\n    rtn: syncKey.reveal()\n```\n\n```text\nEK9     : Error   : E11090: 'reveal' on line 18 position 23: 'SyncReport': reveal() on Sensitive is only permitted in a method of a class or trait that is Privileged: it has the Privileged trait, a trait that has it, or a super class that has it\n             See: ek9 -h E11090\n```\n\nSo the places a secret can be read are the places that say so in their declaration, and a code review can find them with a\nsearch for `Privileged`. A function can never be `Privileged`, because a function has no traits. And the compiler looks at the\nsource for the key as well. A key written into the program is refused, and the diagnostic does not print it:\n\n```ek9\nsyncKey <- \"sk_test_abcdefghijklmnopqrstuvwxyz\"\n```\n\n```text\nEK9     : Error   : E11086: '\"sk_test_abcdefghijklmnopqrstuvwxyz\"' on line 7 position 17: 'sk_tes...***' hardcoded API key detected\n             See: ek9 -h E11086\n```\n\nThe catalogue has sibling codes for other credential shapes; `ek9 -h E11086` lists them. What this does not claim is a run-time\nscrubber: nothing here rewrites a credential that is already inside an ordinary `String` on its way to a log. The protection is\nthe type, the gate on `reveal()` and the check of the source.\n\n## What the capstone costs\n\nYou give up breadth. There is one HTTP server, and its behaviour is the runtime's: you do not choose the engine, the security\nheaders or the logging. A response is assembled by hand, as `reply` shows, which is more typing than returning an object from a\nframework and having it serialised. A service has no fields, so every piece of state costs a component and its contract, and a\nlock if it is shared. Routes bind first-match, with a check only for the same shape. A declared query or header is mandatory.\nAnd the ecosystem around a framework is not part of this chapter or of its claims: persistence, templating and\nauthentication are things this service does not do.\n\nWhat the cost buys is that the dull bugs of a service are not available. A service without a server, or a server without a\nservice, does not compile. A status decided while the body is built is the status sent, and a response with no status is not a program. An\ninput that carries a threat never reaches the code that would have trusted it, and a secret has one declared door. Shared\nstate is reached only through a `MutexLock`. *Packaging and Sharing Your Program* covers the same posture one level up: a\npublishable package declares the system powers it uses, so what a dependency may touch is written down before it runs.\n\n> **A design note.** I would rather the compiler refused to start a service that could not work than that it started one and\n> waited for somebody to find out. A route registered and never served, a server with nothing to serve and a handler that does\n> not say whether the process should exit are all ordinary mistakes with a quiet failure, and each is a compile error here\n> because a person who is late for a deadline will not go and look for them. *- Steve*\n\n## What the notes-keeper became\n\nThe Volume 1 program read `argv`, kept a list in a file and printed it. This one reads a request, keeps a list in a locked book\nand answers in JSON. Its record, its `text`, its `Optional`, its component, its dynamic functions and its application are all\nthings you met on the way here, and the promise at the boundary is the same one: what arrives is checked, and the compiler is\nwhat makes you.\n\n[^almanac]: HTTP Archive, *Web Almanac*, \"Caching\": the 2021 edition\n(https://almanac.httparchive.org/en/2021/caching) gives 25.1% of mobile requests (24.6% desktop) with neither\n`Cache-Control` nor `Expires`, and 24.5% with neither `ETag` nor `Last-Modified`; the 2019 edition\n(https://almanac.httparchive.org/en/2019/caching) counts \"over 3 million responses\" combining `no-store`, `no-cache` and\n`max-age=0`.\n\n[^spring]: Spring Security reference, \"Security HTTP Response Headers\"\n(https://docs.spring.io/spring-security/reference/features/exploits/headers.html): \"Spring Security's default is to\ndisable caching\", sending `Cache-Control: no-cache, no-store, max-age=0, must-revalidate`, and it \"backs out of the way\"\nwhen the application provides its own.\n\n[^deception]: Mirheidari et al., \"Cached and Confused: Web Cache Deception in the Wild\", USENIX Security 2020\n(https://www.usenix.org/conference/usenixsecurity20/presentation/mirheidari).\n\n[^heuristic]: RFC 9111, *HTTP Caching*, section 4.2.2 (https://www.rfc-editor.org/rfc/rfc9111.html#section-4.2.2): a\ncache may give a response with no explicit lifetime a heuristic one, and \"a typical setting of this fraction might be 10%\"\nof the time since its `Last-Modified`.\n\n[^shallow]: Spring Framework's `ShallowEtagHeaderFilter`\n(https://docs.spring.io/spring/docs/5.2.x/javadoc-api/org/springframework/web/filter/ShallowEtagHeaderFilter.html):\n\"the response (e.g. a View) is still rendered. As such, this filter only saves bandwidth, not server performance.\"\n","examples":["books/ek9-in-depth/ch37-web-service-step-by-step/HelloNotes.ek9","books/ek9-in-depth/ch37-web-service-step-by-step/JsonDocuments.ek9","books/ek9-in-depth/ch37-web-service-step-by-step/LateStatus.ek9","books/ek9-in-depth/ch37-web-service-step-by-step/NotesService.ek9","books/ek9-in-depth/ch37-web-service-step-by-step/RouteOrder.ek9","books/ek9-in-depth/ch37-web-service-step-by-step/SyncKey.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Packaging and Sharing Your Program","url":"https://ek9.io/books/ek9-in-depth/packaging-and-sharing-your-program.html","markdown":"# Packaging and Sharing Your Program\n\n*Testing as You Go* in Volume 1 said that a library cannot be published without a minimum of coverage; how that is measured\nbelongs to *Testing the Compiler Trusts*. This chapter is about shipping. In Maven,\nCargo and npm, publishing is a separate tool with its own manifest, its own credentials and its own idea of a version. In EK9\nthe manifest is the `defines package` block you met in *Organising a Growing Codebase*, the version is a value in that block,\nand the tool that tests, versions and packages is the compiler you already run. Everything below was run with the compiler's local\ncommands: `-PV`, `-IV`, `-P` and `-I`.\n\n## The package block is the manifest\n\nHere is a small publishable package, a few greeting functions and a thin program, with the package block as the last part of the\nfile:\n\n```ek9\ndefines module book.packaging.greeter\n\n  defines function\n\n    greeting() as pure\n      -> name as String\n      <- rtn as String: `Hello, ${name}`\n\n    farewell() as pure\n      -> name as String\n      <- rtn as String: `Goodbye, ${name}`\n\n    shouted() as pure\n      -> text as String\n      <- rtn as String: text.upperCase() + \"!\"\n\n    whispered() as pure\n      -> text as String\n      <- rtn as String: `(${text.lowerCase()})`\n\n  defines program\n\n    Greet()\n      -> name as String\n      Stdout().println(greeting(name))\n\n  defines package\n    publishable <- true\n    publicAccess <- true\n    version <- 1.0.0-0\n    description <- \"Greetings, packaged for sharing\"\n    license <- \"MIT\"\n    tags <- [\n      \"example\",\n      \"greeting\"\n    ]\n    applyStandardIncludes <- true\n    capabilities <- [\"org.ek9.lang::Stdout\"]\n```\n\n`defines package` takes no name: the module name is the package name. Each line is a `<-` declaration with a literal of the\nfield's own shape; an unknown field name, or the wrong shape (`tags <- \"tools\"`), is E06260. `publishable` turns publication on at\nall, and `publicAccess` then says who may pull it - public, or private to your organisation; the two are always written together.\nPrivate is not secret, though: a project that depends on your package commits that name into its own `ek9.lock`, so put nothing\nsecret in a module's name - the description and documentation are the place for anything sensitive.\n`capabilities` declares the system powers the code uses (a section below), and `applyStandardIncludes`\nis the build setting from *Organising a Growing Codebase*. The version is a native `Version` literal, `MAJOR.MINOR.PATCH-BUILD`, and not a\nstring:\n\n```text\n$Version: 1.0.0-0\n```\n\n`-PV` prints it. `-IV` increments a part of it and rewrites the source file; here is `-IV patch` run on a copy, and the\ndifference it made to the file:\n\n```text\n30c30\n<     version <- 1.0.0-0\n---\n>     version <- 1.0.1-0\n```\n\nA second `-PV` on the copy prints:\n\n```text\n$Version: 1.0.1-0\n```\n\nThe parts are `major`, `minor`, `patch` and `build`, as semantic versioning would have them (a breaking change to the public\ninterface is major, a new capability is minor, a fix is patch), and the build number moves on every build attempt. The version\nlives in the source, so a version bump is a commit that a diff shows, and no second file can disagree with it.\n\n## `-P`: packaging is gated by tests\n\n`ek9 -P main.ek9` packages the project, and it refuses unless the tests pass with at least 80% coverage (E83001, `ek9 -h coverage`).[^coverage]\nBegin with a project that has no tests:\n\n```text\nNo @Test programs found.\nek9: tests failed (exit 11)\nPackage : Not packaged: tests failed or coverage below the required threshold\n```\n\nAdd one test, for `greeting` only, and the tests pass but the project does not:\n\n```text\nℹ️ Found 1 test:\n  1 assert (unit tests with assertions)\n\nExecuting 1 test...\n\n✅ PASS book.packaging.greeter.tests::GreetingTest [Assert] (1ms)\n\nSummary: 1 passed, 0 failed (1 total)\nTypes: 1 assert\nDuration: 1ms\n\n❌ E83001: Code coverage 20.0% is below required threshold 80%\n   Methods:  20.0% (1/5)\n   Lines:    20.0% (3/15)\n\n   Uncovered items:\n     4 method(s)\n       • book.packaging.greeter::farewell (./main.ek9:10)\n       • book.packaging.greeter::shouted (./main.ek9:14)\n       • book.packaging.greeter::whispered (./main.ek9:18)\n       ... and 1 more\n\n   Use -t4 or -t5 for detailed coverage report.\nek9: coverage below the required threshold (exit 12)\nPackage : Not packaged: tests failed or coverage below the required threshold\n```\n\nThe compiler tells you what to cover next, naming the items it found uncovered; what is counted is the subject of\n*Testing the Compiler Trusts*.\n\nWith the four tests in `dev/`:\n\n```ek9\ndefines module book.packaging.greeter.tests\n\n  references\n    book.packaging.greeter::farewell\n    book.packaging.greeter::greeting\n    book.packaging.greeter::shouted\n    book.packaging.greeter::whispered\n\n  defines program\n\n    @Test\n    GreetingTest()\n      assert greeting(\"Ada\") == \"Hello, Ada\"\n\n    @Test\n    FarewellTest()\n      assert farewell(\"Ada\") == \"Goodbye, Ada\"\n\n    @Test\n    ShoutedTest()\n      assert shouted(\"hello\") == \"HELLO!\"\n\n    @Test\n    WhisperedTest()\n      assert whispered(\"HELLO\") == \"(hello)\"\n\n```\n\n`-P` runs them, passes, and writes two files:\n\n```text\nℹ️ Found 4 tests:\n  4 assert (unit tests with assertions)\n\nExecuting 4 tests...\n\n✅ PASS book.packaging.greeter.tests::FarewellTest [Assert] (2ms)\n✅ PASS book.packaging.greeter.tests::GreetingTest [Assert] (2ms)\n✅ PASS book.packaging.greeter.tests::ShoutedTest [Assert] (2ms)\n✅ PASS book.packaging.greeter.tests::WhisperedTest [Assert] (2ms)\n\nSummary: 4 passed, 0 failed (4 total)\nTypes: 4 assert\nDuration: 10ms\n```\n\n```text\nbook.packaging.greeter-1.0.0-0.zip\nbook.packaging.greeter-1.0.0-0.zip.sha256\n```\n\nThe package is an archive of the *source*. This is the second difference from Maven and npm, which publish a built artefact:\n\n```text\nArchive:  .ek9/book.packaging.greeter-1.0.0-0.zip\n  Length      Date    Time    Name\n---------  ---------- -----   ----\n0  dev/\n530  dev/greeterTests.ek9\n804  main.ek9\n229  .package.properties\n---------                     -------\n     1563                     4 files\n```\n\n`main.ek9`, the tests in `dev/`, and a properties file the compiler made:\n\n```text\n#Package Properties\n#Tue Nov 10 22:15:49 GMT 2026\ndepsFingerPrint=78A39FC30DAB8BF221BC9EB8C2567BB2ABEF57E72BA1E4E29A87A23DB4142391\nmoduleName=book.packaging.greeter\npackage=true\nprograms=Greet\nsourceFile=main.ek9\nversion=1.0.0-0\n```\n\nWhoever depends on your package compiles your source, with their compiler, under their checks, and a `.sha256` file beside the\narchive pins its content. The cost is a consumer who recompiles what they depend on; what it buys is that nothing a package ships\nescapes the compiler's rules, and nothing in it is opaque.\n\n### `-I`: installing to your own library\n\n`-I` does what `-P` does, then installs the archive into a local library, which is the folder `~/.ek9/lib` unless it is\npointed elsewhere. The runs in this chapter were made with a private home and a private library folder, so nothing here touched\na real one. After `-I` the library holds the archive and its checksum:\n\n```text\nbook.packaging.greeter-1.0.0-0.zip\nbook.packaging.greeter-1.0.0-0.zip.sha256\n```\n\nA library on your own disk is enough to share between your own projects, which is what the section on dependencies does.\n\n## Declaring what a package may do\n\nA package that other people will build on is, for them, a supply-chain risk: any package can open a socket or read an environment\nvariable, and npm, Cargo and Maven do not ask a package to declare it. EK9's publishable package states its capabilities, and the\ncompiler checks the package's own code against the list. This program reads an environment variable but declares only `Stdout`:\n\n```ek9\n  defines package\n    publishable <- true\n    publicAccess <- true\n    version <- 1.0.0-0\n    description <- \"Reads the environment without declaring it\"\n    license <- \"MIT\"\n    applyStandardIncludes <- true\n    capabilities <- [\"org.ek9.lang::Stdout\"]\n```\n\n```text\nEK9     : Error   : E12010: 'EnvVars' on line 17 position 13: 'EnvVars' requires capability 'org.ek9.lang::EnvVars': type requires declared package capability\n             See: ek9 -h E12010\n```\n\n`EnvVars` is a gated type, and it is not on the list. The gated types include the standard streams, the environment,\n`Networking`, HTTP, TCP, UDP, signals, files and clocks; `ek9 -h E12010` has the list and names the grouped ones (declaring\n`TCP` covers `TCPConnection` and its handlers, and `Networking` needs `EnvVars` as well). The fix is to declare the capability the\ncode uses, and the package block then reads as an honest statement of what the package does:\n\n```ek9\n  defines package\n    publishable <- true\n    publicAccess <- true\n    version <- 1.0.0-0\n    description <- \"Greets a name taken from the environment\"\n    license <- \"MIT\"\n    applyStandardIncludes <- true\n    capabilities <- [\"org.ek9.lang::Stdout\", \"org.ek9.lang::EnvVars\"]\n```\n\nIt prints, with the variable unset:\n\n```text\nnobody to greet\n```\n\nEnforcement starts only when a package declares all four of `publicAccess`, `version`, `license` and `capabilities`; with any missing,\nthe package is not entering the supply chain under review and is not checked. Dev code (tests, fixtures) is exempt, because it is\nnever published. Enforcement is per module, so a dependency that adds a capability does not break your build; the change shows in\nits package block, and that is the change a reviewer should look at when upgrading. The limit is the one the compiler states: it\nverifies that the package's own code uses nothing it did not declare, for the gated types it knows about.\n\n## Depending on another package\n\nA dependency is a `deps` entry in the package block, naming a module and a version:\n\n```ek9\n  defines package\n    version <- 0.1.0-0\n    description <- \"Depends on a library nobody has installed\"\n    applyStandardIncludes <- true\n    deps <- {\n      \"book.shapes.lib\": \"1.0.0-0\"\n      }\n```\n\nWhere does `book.shapes.lib` come from? The resolver looks in the local library, and then it would look in a remote repository.\nThere is no remote repository yet, and the compiler says so, with the exit code a script can test for:\n\n```text\nek9: dependency resolution failed (exit 17)\nResolve : dependency 'book.shapes.lib' version '1.0.0-0' (declared at unresolvedDependency.ek9:9) cannot be resolved: it is not unpacked in '~/.ek9/lib/book.shapes.lib-1.0.0-0' nor zipped as '~/.ek9/lib/book.shapes.lib-1.0.0-0.zip', and there is no remote repository to fetch it from yet\n```\n\nThat is exit 17, a dependency that could not be resolved, and the message names the version and the line that declared it.\nSo to use a library today you install it first. Here is a small library, `book.shapes.lib`, with two functions and two tests:\n\n```ek9\ndefines module book.shapes.lib\n\n  defines constant\n    CIRCLE_CONSTANT <- 3.14159\n\n  defines function\n\n    circleArea() as pure\n      -> radius as Float\n      <- rtn as Float: CIRCLE_CONSTANT * radius * radius\n\n    squareArea() as pure\n      -> side as Float\n      <- rtn as Float: side * side\n\n  defines package\n    publishable <- true\n    publicAccess <- true\n    version <- 1.0.0-0\n    description <- \"Area of simple shapes\"\n    license <- \"MIT\"\n    applyStandardIncludes <- true\n```\n\nInstalling it runs its tests and puts it in the library:\n\n```text\nℹ️ Found 2 tests:\n  2 assert (unit tests with assertions)\n\nExecuting 2 tests...\n\n✅ PASS book.shapes.lib.tests::CircleAreaTest [Assert] (2ms)\n✅ PASS book.shapes.lib.tests::SquareAreaTest [Assert] (2ms)\n\nSummary: 2 passed, 0 failed (2 total)\nTypes: 2 assert\nDuration: 4ms\n```\n\nA consumer module declares `deps <- {\"book.shapes.lib\": \"1.0.0-0\"}`, adds a `references` block naming `book.shapes.lib::circleArea`\nand `book.shapes.lib::squareArea`, and calls them. Building it resolves the dependency from the library and compiles the library's source with the consumer's. With `-v` the\ncompiler reports the dependency among the files it compiles:\n\n```text\nResolve : Checking 'book.shapes.lib-1.0.0-0'\nResolve : Already unpacked 'book.shapes.lib-1.0.0-0'\nResolve : Complete\nCompile!: 1 dependency source file(s)\n```\n\nand the program runs:\n\n```text\ncircle r=2: 12.56636\nsquare s=3: 9.0\n```\n\n`-Dp` resolves dependencies without building, and cleans first. Resolution is transitive, patch-compatible versions are promoted\nto the later one, a major-version mismatch fails the build, and circular package dependencies are detected; `ek9 -h package` is\nthe reference for those rules.\n\n## What is not here yet\n\nTwo steps of the release workflow in `ek9 -h package` are not available to you today. `-D` deploys packaged software and would\ntrigger `-P` first and then `-Gk`, which generates the signing keys a deployed package carries; both belong to a public\nrepository, and there is none yet. They are planned, they are not shown in this chapter, and a package you build today stays\non your disk and the disks you copy it to. Nothing in the rest of the chapter depends on them.\n\n## The cost\n\nA project is packaged only when its tests pass with at least 80% coverage (E83001, `ek9 -h coverage`). A package that exercises a gated type owes a\n`capabilities` entry for each, and keeps it current as the code changes. The consumer builds your source, not a binary you\nvouch for, so a dependency adds to their compile time. Sharing means handing over an archive.\n\nWhat that buys is the sentence the book opened with: every package you can install has passed its own tests, states what it\nmay touch, and arrives as source the compiler has checked as hard as the code you wrote yourself. A version bump is a diff, a\ndependency is a line in a block, and a supply-chain question has an answer in the file that declares the package.\n\n[^coverage]: *Testing the Compiler Trusts* is where coverage is measured and explained. A reader who skipped Volume 1 should read *Testing as You\nGo*, which introduces `dev/`, `@Test` and `ek9 -t`.\n","examples":["books/ek9-in-depth/ch38-packaging-and-sharing/EnvironmentGreeter.ek9","books/ek9-in-depth/ch38-packaging-and-sharing/greeter/dev/greeterTests.ek9","books/ek9-in-depth/ch38-packaging-and-sharing/greeter/main.ek9","books/ek9-in-depth/ch38-packaging-and-sharing/shapes/dev/shapesTests.ek9","books/ek9-in-depth/ch38-packaging-and-sharing/shapes/shapes.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Testing the Compiler Trusts","url":"https://ek9.io/books/ek9-in-depth/testing-the-compiler-trusts.html","markdown":"# Testing the Compiler Trusts\n\n*Testing as You Go* in Volume 1 made three promises about this chapter: \"the second volume goes into testing in depth\", how\ncoverage for publishing is measured \"is covered in the second volume\", and of test-driven development, \"The second volume\nreturns to it\". It also left the loop of the guessing game untested, and *Dependency Injection and Applications* has since\nput that loop under a test. This chapter is the rest. The universal problem it answers is one you have met in JUnit and pytest:\na green suite can be hollow. A test that asserts nothing passes. An assertion in a helper that no test calls never runs, and\nnothing says so. Coverage is a plugin that someone must remember to configure. The EK9 runner is part of the compiler, and the\ncompiler refuses to call that suite green.[^v1]\n\n## Three kinds of test, one runner\n\nEvery example in this chapter is one project: a small pricing and checkout module with a `dev/` folder beside it. The program\nunder test is complete, and it is the one you have seen the shape of already: a component behind an interface, a class that\ninjects it, and a few `pure` functions.\n\n```ek9\n#!ek9\ndefines module book.testing.shop\n\n  defines constant\n    PERCENT_BASE <- 100\n    BULK_QUANTITY <- 10\n    BULK_PERCENT <- 20\n\n  defines class\n\n    OrderService\n      notifier as Notifier!\n\n      placeOrder()\n        ->\n          item as String\n          price as Integer\n          percent as Integer\n\n        notifier.notify(receipt(item, discounted(price, percent)))\n\n      default operator ?\n\n  defines function\n\n    discounted() as pure\n      ->\n        price as Integer\n        percent as Integer\n      <- rtn as Integer: Integer()\n\n      if percent > PERCENT_BASE\n        throw Exception(`a discount of ${percent} percent is more than the price`)\n      rtn: price - price * percent / PERCENT_BASE\n\n    bulkPrice() as pure\n      ->\n        quantity as Integer\n        unitPrice as Integer\n      <- rtn as Integer: quantity * unitPrice\n\n      if quantity >= BULK_QUANTITY\n        rtn: discounted(quantity * unitPrice, BULK_PERCENT)\n\n    receipt() as pure\n      ->\n        item as String\n        price as Integer\n      <- rtn as String: `${item}: ${price}p`\n\n  defines component\n\n    Notifier as abstract\n      notify() as abstract\n        -> message as String\n\n    ConsoleNotifier is Notifier\n      override notify()\n        -> message as String\n        Stdout().println(message)\n\n  defines application\n\n    shopApp\n      register ConsoleNotifier() as Notifier\n\n  defines program\n\n    Checkout() with application of shopApp\n      orders <- OrderService()\n      orders.placeOrder(\"kettle\", 2500, 20)\n      orders.placeOrder(\"mug\", 400, 0)\n```\n\nIt prints the two receipts:\n\n```text\nkettle: 2000p\nmug: 400p\n```\n\nA test is a `program` marked `@Test`, in a source file under `dev/`. There is no test framework to add, and no test class to\nextend. The runner recognises three kinds, and it treats them as equals.\n\n**An assertion test** states what must be true. `assert` is for tests, as `require` is for production code, and\n`assertThrows` and `assertDoesNotThrow` cover exceptions. `assertThrows` hands back the exception it caught, so you can look at\nthe reason:\n\n```ek9\n    @Test\n    MoreThanFullDiscountIsRefused()\n      assertThrows (Exception, discounted(400, 101))\n\n    @Test\n    ReasonNamesThePercent()\n      refused <- assertThrows (Exception, discounted(400, 150))\n      assert refused.reason() == \"a discount of 150 percent is more than the price\"\n\n    @Test\n    SensibleDiscountThrowsNothing()\n      assertDoesNotThrow (discounted(400, 50))\n```\n\n**A black-box test** has no assertion. It prints, and the runner compares everything it printed to a file named\n`expected_output.txt` beside it. Where the program talks to the world, here through `Notifier`, the test brings its own\nstand-in and a *test application* that registers it: `TaggedNotifier` is the whole of what a mocking framework would have done,\nand it is an ordinary component.\n\n```ek9\ndefines module book.testing.shop.checkout\n\n  references\n    book.testing.shop::Notifier\n    book.testing.shop::OrderService\n\n  defines component\n\n    TaggedNotifier is Notifier\n      override notify()\n        -> message as String\n        Stdout().println(`[test] ${message}`)\n\n  defines application\n\n    taggedShop\n      register TaggedNotifier() as Notifier\n\n  defines program\n\n    @Test\n    CheckoutOutput() with application of taggedShop\n      orders <- OrderService()\n      orders.placeOrder(\"kettle\", 2500, 20)\n      orders.placeOrder(\"mug\", 400, 0)\n```\n\nwith `expected_output.txt` beside it holding:\n\n```text\n[test] kettle: 2000p\n[test] mug: 400p\n```\n\n**A parameterized test** takes program arguments, and the runner runs it once per case: a `commandline_arg_<case>.txt` file\nsupplies the arguments, one per line, and `expected_case_<case>.txt` pins that case's output. The table is files, not a data\nprovider:\n\n```ek9\ndefines module book.testing.shop.receipts\n\n  references\n    book.testing.shop::discounted\n    book.testing.shop::receipt\n\n  defines program\n\n    @Test\n    ReceiptForArguments()\n      ->\n        item as String\n        price as String\n        percent as String\n\n      stdout <- Stdout()\n      stdout.println(receipt(item, discounted(Integer(price), Integer(percent))))\n```\n\nTwo cases are `sale` (`kettle`, `2500`, `20`, expecting `kettle: 2000p`) and `free` (`mug`, `400`, `100`, expecting `mug: 0p`).\nIf you know Go's table-driven tests or golden files, these are the same ideas with a file convention instead of a library.\nHere is the whole project under `ek9 -t -tC`:\n\n```text\nℹ️ Found 13 tests:\n  10 assert (unit tests with assertions)\n  2 blackbox (output validated against expected_output.txt)\n  1 parameterized (2 cases total)\n\nExecuting 13 tests...\n\n✅ PASS book.testing.shop.checkout::CheckoutOutput [BlackBox] (8ms)\n✅ PASS book.testing.shop.production::ProductionCheckout [BlackBox] (8ms)\n✅ PASS book.testing.shop.receipts::ReceiptForArguments [Param:free] (6ms)\n✅ PASS book.testing.shop.receipts::ReceiptForArguments [Param:sale] (1ms)\n✅ PASS book.testing.shop.unit::EveryPartIsSet [Assert] (6ms)\n✅ PASS book.testing.shop.unit::FullDiscountIsFree [Assert] (6ms)\n✅ PASS book.testing.shop.unit::MoreThanFullDiscountIsRefused [Assert] (6ms)\n✅ PASS book.testing.shop.unit::NineItemsPayInFull [Assert] (6ms)\n✅ PASS book.testing.shop.unit::NoDiscountKeepsThePrice [Assert] (6ms)\n✅ PASS book.testing.shop.unit::ReasonNamesThePercent [Assert] (6ms)\n✅ PASS book.testing.shop.unit::ReceiptShowsItemAndPrice [Assert] (6ms)\n✅ PASS book.testing.shop.unit::SensibleDiscountThrowsNothing [Assert] (6ms)\n✅ PASS book.testing.shop.unit::TenItemsGetTwentyPercentOff [Assert] (6ms)\n✅ PASS book.testing.shop.unit::TenPercentOff [Assert] (6ms)\n\nSummary: 14 passed, 0 failed (14 results from 13 programs)\nTypes: 10 assert, 2 blackbox, 2 parameterized\nDuration: 89ms\n\n📊 Coverage Summary\n  ✅ Methods:  90.9% (10/11)\n  ✅ Lines:    88.6% (31/35)\n  ✅ Branches: 100.0% (2/2)\n\n  ✅ Overall: 88.89% (32/36 probes hit)\n\n📦 By Module:\n  ✅ book.testing.shop: 88.89% (32/36)\n```\n\nThe labels `[Assert]`, `[BlackBox]` and `[Param:free]` are the three kinds, counted together in one summary. The tests are listed\nin alphabetical order, not source order. A test that fails says where and why. Here are two that were written wrongly, one\nasserting the wrong total and one expecting an exception that is never thrown:\n\n```text\n❌ FAIL book.testing.pricing.failing::NothingThrown [Assert] (3ms)\n    assertThrows FAILED\n      Location: ./dev/testFailingAssertions.ek9:15:7\n      Expression: discounted(2000, 10)\n      Expected: org.ek9.lang::Exception\n      Actual: No exception was thrown\n❌ FAIL book.testing.pricing.failing::WrongExpectation [Assert] (3ms)\n    Assertion failed: `discounted(2000, 10) == 1900` at ./dev/testFailingAssertions.ek9:11:7\n\nSummary: 0 passed, 2 failed (2 total)\nTypes: 2 assert\nDuration: 7ms\nek9: tests failed (exit 11)\n```\n\nThe exit code is 11 for a failed test, which is what a CI step needs to see.\n\n## Test first, and what red looks like\n\n*Testing as You Go* cited Kent Beck for writing the test before the code. In Java or Python the first red is a failing\nassertion, after you have written a stub that returns the wrong thing. In EK9 it can come sooner. Write the bulk-order test\nbefore `bulkPrice` exists, and the project does not compile:\n\n```ek9\ndefines module book.testing.pricing.first\n\n  references\n    book.testing.pricing::bulkPrice\n\n  defines program\n\n    @Test\n    TenItemsGetTwentyPercentOff()\n      assert bulkPrice(10, 200) == 1600\n```\n\n```text\nEK9     : Error   : E03030: 'bulkPrice' on line 5 position 26: 'book.testing.pricing::bulkPrice' reference does not resolve\n             See: ek9 -h E03030\n```\n\nThat is the red step: the test names a function, and the compiler says there is no such thing. Write `bulkPrice` (it is in the\nprogram above), run `ek9 -t`, and the same test is green. The loop is short because `-t` compiles the program and its `dev/`\nfiles together, so a test that does not yet have something to test cannot be mistaken for one that passes.\n\n## What the compiler refuses to call a test\n\nThe three rules that follow are what make the word \"green\" mean something. Each is checked by the compiler, before any test\nruns, and each has a code. The first is a test that cannot fail because it checks nothing:\n\n```ek9\n    @Test\n    TenPercentOff()\n      stdout <- Stdout()\n      stdout.println($discounted(2000, 10))\n```\n\n```text\nEK9     : Error   : E81007: 'TenPercentOff' on line 10 position 4: 'book.testing.pricing.empty::TenPercentOff' has no assertions and no expected output files: @Test program has no assertions and no expected output files\n             See: ek9 -h E81007\n```\n\nThe second half of the message matters. A test with no `assert` is legal when it has an `expected_output.txt` or its\n`expected_case` files, because then its output *is* the assertion; that is a black-box test. With neither, it checks nothing.\n\nThe second is an assertion that no test reaches. A helper that holds an `assert` is only useful if a `@Test` calls it:\n\n```ek9\n  defines function\n\n    checkNeverNegative()\n      -> price as Integer\n      assert discounted(price, 10) >= 0\n\n  defines program\n\n    @Test\n    TenPercentOff()\n      assert discounted(2000, 10) == 1800\n```\n\n```text\nEK9     : Error   : E81011: 'checkNeverNegative' on line 9 position 4: 'book.testing.pricing.orphan::checkNeverNegative' contains assertions but is not reachable from any @Test program: assertion is not reachable from any @Test program\n             See: ek9 -h E81011\n```\n\nThis is the rule that retires the dead assertion. In JUnit the helper compiles, is never called, and the suite is green with\nthe check silently absent; here an *orphan* assertion does not compile.\n\nThe third is the opposite fault, an assertion that production code can reach. If a plain program also calls the helper, the\nassertion would run in production:\n\n```ek9\n    @Test\n    TenPercentOff()\n      checkNeverNegative(2000)\n\n    Report()\n      checkNeverNegative(400)\n```\n\n```text\nEK9     : Error   : E81012: 'checkNeverNegative' on line 9 position 4: 'book.testing.pricing.production::checkNeverNegative' contains assertions but is reachable from production program (use 'require' instead): assertion is reachable from non-test program\n             See: ek9 -h E81012\n```\n\nThe message names the remedy: production code that must check something uses `require`, the other half of the pair from\n*Testing as You Go*. Last, `assert` and `@Test` are only legal in `dev/` source. In the production file both are the same\ncode, E81015, from different phases:\n\n```text\nEK9     : Error   : E81015: 'assert' on line 15 position 6: 'assert': test construct only allowed in dev source files\n             See: ek9 -h E81015\nEK9     : Error   : E81015: 'TenPercentOff' on line 18 position 4: '@Test': test construct only allowed in dev source files\n             See: ek9 -h E81015\n```\n\nKeep the two codes apart. E81015 is about *where the file is*: an `assert` or a `@Test` in production source. E81012 is about\n*what reaches an assertion*: it fires inside `dev/`, on a helper a production program also calls. E81011 and E81007 need the\n`dev/` folder compiled with the program, which is why they appear under `ek9 -t` and not under a plain compile.\n\n| A suite that looks green | JUnit, pytest | EK9 |\n|---|---|---|\n| A test that asserts nothing | passes | E81007, unless an expected-output file is its assertion |\n| An assertion in a helper no test calls | compiles, never runs, nothing is reported | E81011 |\n| An assertion production code can reach | a library call that runs wherever it is called | E81012 |\n| `assert` or a test outside the test folder | allowed | E81015 |\n| Coverage | an add-on you configure | built in; the 80% bar is the next section |\n\n## The gate, and what coverage cannot see\n\nCoverage is not an add-on here. `ek9 -t` collects it on every run, and it gates: below 80% the run ends with E83001 and exit\n12 even if every test passed. The same 80% is the bar `ek9 -P` applies before it will package a program, and there is no flag\nto lower it. Take the project above and leave out its last two additions, the `production` black-box test and `EveryPartIsSet`.\nAll twelve tests are still green, and the build still fails:\n\n```text\nSummary: 12 passed, 0 failed (12 results from 11 programs)\nTypes: 9 assert, 1 blackbox, 2 parameterized\nDuration: 79ms\n\n📊 Coverage Summary\n  ❌ Methods:  36.4% (4/11)\n  ⚠️ Lines:    65.7% (23/35)\n  ✅ Branches: 100.0% (2/2)\n\n  ⚠️ Overall: 63.89% (23/36 probes hit)\n\n📦 By Module:\n  ⚠️ book.testing.shop: 63.89% (23/36)\n\n⚠️  Coverage below 80% - detailed report written to: .ek9/coverage-detail.json\n\n❌ E83001: Code coverage 63.9% is below required threshold 80%\n   Methods:  36.4% (4/11)\n   Lines:    65.7% (23/35)\n   Branches: 100.0% (2/2)\n\n   Uncovered items:\n     7 method(s)\n       • book.testing.shop::OrderService.? (./Shop.ek9:22)\n       • book.testing.shop::Notifier.? (./Shop.ek9:53)\n       • book.testing.shop::ConsoleNotifier.? (./Shop.ek9:57)\n       ... and 4 more\n\n   Use -t4 or -t5 for detailed coverage report.\nek9: coverage below the required threshold (exit 12)\n```\n\nTwo of the uncovered methods are worth explaining, because you will meet them in every small project. The `?` operators are\ncompiler-written, one for each aggregate, and each counts as a method; `assert OrderService()?` in `EveryPartIsSet` runs\nthem. And the production wiring, `shopApp`, only counts as exercised if some test runs against it, which is what the\n`production` test does with the real `ConsoleNotifier`. The `Checkout` program itself stays uncovered, because a test cannot\ncall a program; it is the thin part that talks, and the bar leaves room for it.\n\nCoverage is a fact about lines, though, and it can be 100% while the tests asked only the easy questions. `ek9 -t5` adds a\nreport of *input variety*: for each callable, how many kinds of value the tests passed in. These are the five callables of the\nproject above:\n\n```text\nInput-variety (numerator, measurement-only):\n  book.testing.shop::ConsoleNotifier.notify          driven 2 cell(s), asserted 2: p0: SET  p1: SPECIAL_CHARS\n  book.testing.shop::OrderService.placeOrder         driven 6 cell(s), asserted 6: p0: SET  p1: TYPICAL  p2: POSITIVE,TYPICAL  p3: POSITIVE,ZERO\n  book.testing.shop::bulkPrice                       driven 2 cell(s), asserted 2: p0: POSITIVE  p1: POSITIVE\n  book.testing.shop::discounted                      driven 4 cell(s), asserted 4: p0: POSITIVE,TYPICAL  p1: POSITIVE,ZERO\n  book.testing.shop::receipt                         driven 4 cell(s), asserted 4: p0: TYPICAL  p1: POSITIVE,TYPICAL,ZERO\n```\n\nEvery line of `discounted` ran, but its two `Integer` parameters were only ever given positive numbers and zero: no negative\nprice, no unset one. `ek9 -t6` writes an HTML report whose Input Variety dial puts a number on it, with the denominator, which\nthe `-t5` table does not print:\n\n```text\nInput classes driven\n17.0%\n18 / 106 cells across 7 construct(s)\n```\n\nFor `discounted` alone the report's JSON, `input-variety.json`, gives a floor of 18 classes between its two parameters, of\nwhich the tests drove 4. The report's own text states its status: \"The floor is 1-wise: each input value-class needs driving\nat least once. It is measurement only -- nothing here fails a build.\" That is the whole of its authority. Input variety is the\n*exposure* half of HEX, the advisory change-risk score (`ek9 -h hex`), and *Quality Built In* is where the two halves meet. It\nnever gates; coverage gates. A suite validated only by expected-output files records driven classes and none asserted, because\nonly an `assert` opens the window in which a result is observed, so read a low asserted figure beside the count of\noutput-validated tests before concluding that testing is thin.\n\n## The cost\n\nThe compiler policing your tests is not free, and you will feel it in three places. A test that exists only to print something\nuseful while you debug is E81007 the moment it is committed without an expected-output file, so a scratch test has to be a\nscratch program, outside `dev/`. A black-box test compares *all* of the output, byte for byte, so a changed message or an\nunstable value, a timestamp or a random number, fails it, and you either control the source of the value, as the fixed\nsecret did in *Dependency Injection and Applications*, or you assert on part of it instead. And the 80% bar does not\ndistinguish a thorough test from `assert OrderService()?`: the `?` assertion above exists to run a compiler-written method, and\nthe gate is satisfied by it.\n\nWhat the cost buys is narrower than \"your code is correct\", and the chapter has tried not to say more. It buys a suite in which\nevery green test has either an assertion that production code cannot reach or an output file that pins what was printed, every\nassertion is reachable from a test, coverage is measured without a plugin, and a stand-in for the outside world is a component\nyou write in a dozen lines. What it does not buy is a judgement about whether the right questions were asked. Input variety is\nthe nearest the compiler comes to that, and it only measures.\n\n[^v1]: If you skipped Volume 1, *Testing as You Go* is the chapter to read first: it introduces `@Test`, `assert`, `ek9 -t` and the\ncoverage bar.\n","examples":["books/ek9-in-depth/ch39-testing-the-compiler-trusts/shop/Shop.ek9","books/ek9-in-depth/ch39-testing-the-compiler-trusts/shop/dev/ShopUnitTests.ek9","books/ek9-in-depth/ch39-testing-the-compiler-trusts/shop/dev/checkout/CheckoutOutputTest.ek9","books/ek9-in-depth/ch39-testing-the-compiler-trusts/shop/dev/production/ProductionCheckoutTest.ek9","books/ek9-in-depth/ch39-testing-the-compiler-trusts/shop/dev/receipts/ReceiptTest.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Quality Built In","url":"https://ek9.io/books/ek9-in-depth/quality-built-in.html","markdown":"# Quality Built In\n\n*Testing as You Go* ended on a promise: coverage is the one quality measure that gates, and the variety figure is a report\nthat shows where your tests are thin. *Components* said the compiler \"keeps score\" of coupling and cohesion. *Testing the\nCompiler Trusts* then showed coverage gating a run and input variety measuring beside it. This chapter is the rest of the\nscorecard, and the argument that ties it together: in EK9 the compiler has been grading you since your first function, and\nnearly every grade is a compile error with a figure, a limit and no way round it.[^qualityv1]\n\nIf you use SonarQube, Checkstyle, PMD or ESLint you know most of these measures already, down to the name; EK9's cognitive\ncomplexity is Sonar's idea. What differs is the consequence. A linter reports, a dashboard goes amber, and a deadline turns\nthe finding into a ticket. Here the same finding stops the build.\n\n## Rejected, with a figure\n\nHere is a function that summarises a list of orders: how many lines fall in each price band, how many are bulk, how many are\nempty, how many orders are priority. It does the whole job in one place, and every decision nests inside the one before it:\n\n```ek9\nsummarise()\n  -> orders as List of Order\n  <- rtn as String?\n\n  expensive <- 0\n  moderate <- 0\n  cheap <- 0\n  bulkLines <- 0\n  emptyLines <- 0\n  priorityIds <- List() of String\n\n  for order in orders\n    if order.id?\n      for line in order.lines\n        if line.quantity > 0\n          if line.price > HIGH_PRICE\n            expensive++\n          else if line.price > MID_PRICE\n            moderate++\n          else\n            cheap++\n      for item in order.lines\n        if item.sku?\n          if item.quantity >= BULK\n            bulkLines++\n          else if item.quantity == 0\n            emptyLines++\n      if order.priority\n        if length of order.lines > 0\n          priorityIds += order.id\n\n  rtn: `expensive ${expensive}, moderate ${moderate}, cheap ${cheap}, bulk ${bulkLines}, empty ${emptyLines}, priority ${length of priorityIds}`\n```\n\nIt reads like the code most of us write on a first pass, and it is rejected:\n\n```text\nEK9     : Error   : E11021: 'summarise' on line 47 position 4: Cognitive complexity of 44 exceeds maximum of 35: cognitive complexity exceeds limit - extract functions\n             See: ek9 -h E11021\n           forAI: qualityMetrics.cognitiveComplexity\n```\n\nThe message gives the figure and the limit. Cognitive complexity is scored per control structure and *multiplied by the\nnesting depth it sits at*, and a `<-` guard adds a penalty of one (`ek9 -h complexity`): a loop inside an `if` inside a loop\ncosts far more than three flat ones, which is the intuition behind the metric. The limit is 35 and this function scores 44.\nThere is no `@SuppressWarnings` to put above it, no threshold to raise in a file, and no way to compile it today and fix it\nnext sprint. It is the only error in that file; the two programs share their records and their `OrderReport` program, and\ndiffer in `summarise`.\n\nThe fix is the one the limit steers towards. Each decision becomes a one-line `pure` function with a name, and a pipeline\nsays how they combine:\n\n```ek9\nbandMatcher() as pure abstract\n  -> band as String\n  <- rtn as Boolean?\n\nhasId() as pure\n  -> order as Order\n  <- rtn as Boolean: order.id?\n\nlinesOf() as pure\n  -> order as Order\n  <- rtn as List of OrderLine: order.lines\n\nhasQuantity() as pure\n  -> line as OrderLine\n  <- rtn as Boolean: line.quantity > 0\n\npriceBand() as pure\n  -> line as OrderLine\n  <- rtn as String: line.price > HIGH_PRICE <- EXPENSIVE : (line.price > MID_PRICE <- MODERATE : CHEAP)\n\nisBulk() as pure\n  -> line as OrderLine\n  <- rtn as Boolean: line.quantity >= BULK\n\nhasNothing() as pure\n  -> line as OrderLine\n  <- rtn as Boolean: line.quantity == 0\n\nisPriority() as pure\n  -> order as Order\n  <- rtn as Boolean: order.priority and length of order.lines > 0\n\nbandCount() as pure\n  ->\n    bands as List of String\n    wanted as String\n  <- rtn as Integer: 0\n\n  sameBand <- (wanted) is bandMatcher as pure function\n    rtn :=? band == wanted\n  found <- cat bands | filter by sameBand | collect as List of String\n  rtn: length of found\n\nsummarise() as pure\n  -> orders as List of Order\n  <- rtn as String?\n\n  validOrders <- cat orders | filter by hasId | collect as List of Order\n  lines <- cat validOrders | map with linesOf | flatten | collect as List of OrderLine\n  bands <- cat lines | filter by hasQuantity | map with priceBand | collect as List of String\n  bulkLines <- cat lines | filter by isBulk | collect as List of OrderLine\n  emptyLines <- cat lines | filter by hasNothing | collect as List of OrderLine\n  priorityOrders <- cat validOrders | filter by isPriority | collect as List of Order\n\n  rtn: `expensive ${bandCount(bands, EXPENSIVE)}, moderate ${bandCount(bands, MODERATE)}, cheap ${bandCount(bands, CHEAP)}, bulk ${length of bulkLines}, empty ${length of emptyLines}, priority ${length of priorityOrders}`\n```\n\nTwo details are worth reading. `flatten` turns the list of lines inside each order into one list of lines, which is what\nremoved the second `for`. And `bandCount` takes a *captured* value, `wanted`, into a dynamic function (*Dynamic Functions and\nClasses*), so that one function counts any band. None of the functions in the listing nests a control structure, which is the shape\nthe limits push you towards. The records and the `OrderReport` program are the same as in the rejected file, and the program\nprints the line the summary builds:\n\n```text\nexpensive 1, moderate 2, cheap 1, bulk 2, empty 1, priority 1\n```\n\n*Stream Pipelines in Depth* showed the same effect on a loop that nested seven deep: it printed the cyclomatic, cognitive and\nnesting figures side by side, and the loop form stopped compiling at E11011. Those are three of five limits on a function, and\nall five are errors:\n\n| Measure | Limit | Code |\n|---|---|---|\n| Cyclomatic complexity | 45 per function, 500 per class | E11010 |\n| Cognitive complexity | 35 | E11021 |\n| Nesting depth | 6 | E11011 |\n| Nested `?:`, `<?` and `>?` | 15 | E11013 |\n| Share of the cyclomatic limit multiplied by share of the statement limit | 0.50 | E11020 |\n\nThe last row is the unusual one. Each of the others can be met by a function that is large and flat, or small and tangled.\nE11020 multiplies the share of the cyclomatic limit by the share of the statement limit (50 statements for an operator, 100\nfor a method, 150 for a function), so a function that is *moderately* both is refused although neither limit alone has been\nreached. Every figure above is `ek9 -h complexity`, and the compiler's error text prints the exact figure for\nthe function it refused.\n\n## The architecture layer\n\nMost languages farm the next group of measures out to a second tool, or to a design review. They are about the shape of a\ntype and a module, not of a function, and EK9 checks them in the same pass, with the same lack of mercy. Each of the examples\nthat follow is a program that compiles in every other respect.\n\n**Cohesion.** A class whose methods split into groups that share no fields is two classes pretending to be one. The check is\nLCOM4, the count of connected groups in the graph of which method touches which field; one is ideal. The limit is 8 for a\nclass and 10 for a component. Records, traits, functions and services are exempt by design, because none of them has a graph\nof methods and fields to split; a service has no fields at all. A dashboard that counts nine unrelated things has nine groups:\n\n```text\nEK9     : Error   : E11014: 'Dashboard' on line 6 position 4: LCOM4 of 9 exceeds maximum of 8 for CLASS: low cohesion - class has disconnected method groups, consider splitting\n             See: ek9 -h E11014\n           forAI: qualityMetrics.cohesion\n```\n\nThe class has nine counters and nine one-line methods, each touching its own counter, and an ordinary `default operator ?`.\nTwo methods are joined when they touch the same field or one calls the other, on the object itself: a call or a field read on\nanother instance of the class, `other.total()`, joins nothing. An abstract method has no body, so it is never a group of its\nown, though the methods that call it are joined through it. Constructors and the operators that work on the whole value -\n`?`, `==`, `<=>`, `#?`, `$`, `:=:` and their kind - are left out of the graph, generated or written by hand, because they\nread every field by definition: counting them would join every group and make any class look cohesive. What is left is the\nclass's behaviour, and that is what the check measures.\n\n**Coupling.** Efferent coupling, `Ce`, counts the other types a construct depends on: field, parameter and return types,\nsupers and implemented traits, and variables captured into a dynamic function or class. The built-in types are not counted.\nThe limit is 12 for a class, 15 for a component or service, and 8 for a record, trait or function (E11015). A class that\nholds thirteen domain types as fields is refused:\n\n```text\nEK9     : Error   : E11015: 'OrderDesk' on line 60 position 4: Efferent coupling of 13 exceeds maximum of 12 for CLASS: excessive efferent coupling - depends on too many types\n             See: ek9 -h E11015\n           forAI: qualityMetrics.coupling\n```\n\nThe module has a coupling limit too, E11016: ten *external modules*, counted by module and not by type, so five types from\none module count once and the usual cure is a wrapper module that gathers a family of dependencies behind one. The module\nalso has a cohesion check, E11017, for a module of at least sixty constructs that falls apart into thirty or more groups that\nshare no types; at that size it is a utility module that wants splitting into one module per purpose, and it needs more\nconstructs than a book page can hold, so there is no example.\n\n**Inheritance depth.** The ceilings are 4 levels for a class, trait or component, 3 for a function and 2 for a record\n(E11019), and the message names the alternative, delegation with `by`:\n\n```text\nEK9     : Error   : E11019: 'Director' on line 18 position 4: Inheritance depth of 3 exceeds maximum of 2 for RECORD: excessive inheritance depth - consider delegation with 'by'\n             See: ek9 -h E11019\n           forAI: qualityMetrics.inheritanceDepth\n```\n\n**Shape.** Two checks look at what a class *is*. A class made only of service fields, objects that do things and no data, is\na component in disguise (E11022, four service fields and no data fields), and the message says `defines component`, the\nconstruct *Dependency Injection and Applications* builds on. The limits for the related shapes are in `ek9 -h quality`: a class that\noverrides most of what it extends wants delegation (E11023), and one with three services and three data fields is doing two\njobs (E11025).\n\n```text\nEK9     : Error   : E11022: 'Notifier' on line 44 position 4: has 4 service fields (mailer, auditor, archiver, scheduler) and no data fields: class has component characteristics - use 'defines component'\n             See: ek9 -h E11022\n```\n\nThe last in this family is the data clump: the same four parameters repeated across three functions, which is a record that\nhas not been written yet (E11053):\n\n```text\nEK9     : Error   : E11053: 'book' on line 2 position 15: Data clump of 4+ shared parameters across 3 callables in 'book.quality.clump': [formatAddress, isComplete, labelFor] data clump detected - extract a record to group repeated parameters\n             See: ek9 -h E11053\n```\n\nExtracting the record is the cure, and the three functions each take one argument:\n\n```ek9\ndefines function\n\n  formatAddress() as pure\n    -> address as Address\n    <- rtn as String: `${address.street}, ${address.city}, ${address.state} ${address.zipCode}`\n\n  isComplete() as pure\n    -> address as Address\n    <- rtn as Boolean: address.street? and address.city? and address.state? and address.zipCode?\n\n  labelFor() as pure\n    -> address as Address\n    <- rtn as String: `${address.zipCode}: ${address.street} ${address.city} ${address.state}`\n```\n\n```text\n1 High Street, Leeds, West Yorkshire LS1 1AA\ntrue\nLS1 1AA: 1 High Street Leeds West Yorkshire\n```\n\nNaming, which Volume 1 introduced one rule at a time, belongs to the same family: a banned word such as `temp` or `data` is\nE11031, two names one edit apart are E11030, and an unsorted `references` list is E11026. They share the property that matters:\nnone of them is a warning. `ek9 -h quality` ends its list with the statement that the compiler has \"NO warnings -- only\nerrors\", and the program that gets through has passed all of them. Packaging asks for the same gate plus the 80% coverage bar\nbefore it will build (*Packaging and Sharing Your Program*).\n\n## What coverage cannot say\n\nCoverage gates. It is also easy to meet with tests that ask only the one easy question, which is the weakness *Testing the\nCompiler Trusts* measured with input variety. The quality report goes one step further and joins that measurement to the\ncomplexity figures above. The result is **HEX**, hazard multiplied by exposure, a change-risk score from 0 to 100 where higher\nis worse (`ek9 -h hex`):\n\n- **hazard** is how much a change can break, from cognitive complexity and efferent coupling;\n- **exposure** is how little the tests would notice, from coverage and from *asserted* input variety.\n\nThe question it answers is one coverage cannot: if I change this, how much can break, and would anything notice? Here is a\nsmall function with some branches in it, and a first test:\n\n```ek9\ndefines constant\n  LIGHT_LIMIT <- 500\n\n  HEAVY_LIMIT <- 5000\n\n  LIGHT_PRICE <- 300\n\n  STANDARD_PRICE <- 450\n\n  HEAVY_PRICE <- 900\n\n  EXPRESS_SURCHARGE <- 250\n\ndefines function\n\n  postage() as pure\n    ->\n      grams as Integer\n      express as Boolean\n    <- rtn as Integer: STANDARD_PRICE\n\n    if grams <= LIGHT_LIMIT\n      rtn: LIGHT_PRICE\n    else if grams > HEAVY_LIMIT\n      rtn: HEAVY_PRICE\n\n    if express\n      rtn: rtn + EXPRESS_SURCHARGE\n```\n\n```ek9\n@Test\nLetterByStandardPost()\n  assert postage(100, false) == 300\n```\n\nOne test, the letter sent by standard post. Run it with `ek9 -t -tC`, and the gate stops it:\n\n```text\n📊 Coverage Summary\n  ✅ Methods:  100.0% (1/1)\n  ⚠️ Lines:    60.0% (6/10)\n  ❌ Branches: 33.3% (1/3)\n\n  ⚠️ Overall: 60.00% (6/10 probes hit)\n\n📦 By Module:\n  ⚠️ book.quality.postage: 60.00% (6/10)\n```\n\nThe run then names the file that holds the detail of what was missed, and ends:\n\n```text\n❌ E83001: Code coverage 60.0% is below required threshold 80%\n   Methods:  100.0% (1/1)\n   Lines:    60.0% (6/10)\n   Branches: 33.3% (1/3)\n\n   Uncovered items:\n     2 branch(es)\n\n   Use -t4 or -t5 for detailed coverage report.\nek9: coverage below the required threshold (exit 12)\n```\n\nCoverage is the gate, and it is right to stop here: two of the three branches never ran. `-t6` writes the HTML quality report,\nand the entry it holds for `postage` shows the figures this chapter has been naming, together. The text below is that entry\nwith the markup removed and the lines wrapped:\n\n```text\npostage()  ./postage.ek9:14\nCC:6 Complexity — cyclomatic 6, cognitive 3, nesting depth 1. Cyclomatic counts the independent paths through the\n    code; cognitive is how hard it is to follow; nesting is the deepest stack of control structures. Higher means\n    harder to test and to change safely.\nI:2/12 Input variety — 2 of 12 input value-classes driven (16.7%); 2 asserted on (16.7%). Coverage says the lines ran;\n    this says across how many kinds of input, and how many of those a test actually checked. Green coverage over a low\n    variety is thin testing.\nH9·E83 Change risk (HEX 7) — hazard 9% (how much a change here can break, from complexity and coupling) × exposure 83%\n    (how little the tests would notice). Two levers, always: make the code less dangerous, or make the tests notice\n    more.\n```\n\nHazard is 9: the function is small, with a cyclomatic complexity of 6 and a cognitive complexity of 3. Exposure is\n83: of twelve input classes the parameters allow, two were driven, and the HEX score is the product, 7. It is a *low* score\nand the function is untested. The help text is blunt about this: \"A LOW score means low change-RISK, NOT 'safe' or 'well\ntested'. A trivial construct scores low because there is little to go wrong, not because it is guarded.\" HEX is not a verdict on\nthe tests. It estimates what a mistake in this function would cost and whether the tests would catch it.\n\nNow give it six tests that between them take the branches and a range of weights, among them zero and a negative one\n(`dev/tests.ek9` in the download):\n\n```text\n📊 Coverage Summary\n  ✅ Methods:  100.0% (1/1)\n  ✅ Lines:    100.0% (10/10)\n  ✅ Branches: 100.0% (3/3)\n\n  ✅ Overall: 100.00% (10/10 probes hit)\n\n📦 By Module:\n  ✅ book.quality.postage: 100.00% (10/10)\n```\n\nCoverage is full, and the gate is satisfied. The entry from the same report:\n\n```text\npostage()  ./postage.ek9:14\nCC:6 Complexity — cyclomatic 6, cognitive 3, nesting depth 1. Cyclomatic counts the independent paths through the\n    code; cognitive is how hard it is to follow; nesting is the deepest stack of control structures. Higher means\n    harder to test and to change safely.\nI:6/12 Input variety — 6 of 12 input value-classes driven (50.0%); 6 asserted on (50.0%). Coverage says the lines ran;\n    this says across how many kinds of input, and how many of those a test actually checked. Green coverage over a low\n    variety is thin testing.\nH9·E50 Change risk (HEX 4) — hazard 9% (how much a change here can break, from complexity and coupling) × exposure 50%\n    (how little the tests would notice). Two levers, always: make the code less dangerous, or make the tests notice\n    more.\n```\n\nExposure fell from 83 to 50 and HEX from 7 to 4. The reason it fell no further is the line `-t5` prints under its coverage\nsummary, the classes the tests drove:\n\n```text\nInput-variety (numerator, measurement-only):\n  book.quality.postage::postage                      driven 6 cell(s), asserted 6: p0: NEGATIVE,POSITIVE,TYPICAL,ZERO  p1: FALSE,TRUE\n```\n\nEvery line ran, and six of the twelve input classes were driven. The floor is a static figure the compiler works out from the\nparameter types, and nothing enforces it. The sentence that follows the figures in the report states its authority exactly:\nHEX is advisory and is never a gate, and coverage gates (`ek9 -h variety`). If you read a score as a threshold you would be\nasking the compiler for something it does not claim to compute.\n\nThree reading rules come from `ek9 -h hex`, and each guards a mistake that is easy to make:\n\n- **Read the mean and the maximum together.** A calm average over a dangerous outlier is the usual misreading; the maximum\n  names the construct that will bite.\n- **The cohorts differ.** A construct whose parameter type is loose, a bare `String`, has no exact input space, so its floor is\n  a guess and it is counted apart as *approximate*. The cure is to tighten the type, an enumeration or a constrained type, which\n  moves it into the measured cohort and makes the input space explicit to the next reader. A construct with no parameters, or a\n  compiler-written body, has no input space at all and is scored on coverage alone.\n- **Afferent coupling is deliberately not in the score.** How many callables depend on a construct is reported on its own,\n  because multiplying blast radius by test adequacy would let a well-tested type that fifty things depend on look safe. High\n  dependents with a low score means: change the insides freely, and do not change the signature.\n\nA suite validated by expected-output files rather than assertions shows driven classes and no asserted ones, because only an\n`assert` opens the window in which a result is observed; *Testing the Compiler Trusts* made the same point. HEX's two levers\nare in the report's own sentence, and they are the only two: make the code less dangerous, or make the tests notice more.\n\n## The cost\n\nYou cannot wave any of this through. A function at 36 is refused as firmly as one at 360, so a long `switch` that is clear to\nread, and exactly the right shape for the job, will still have to be split. The limits are the compiler's, not yours: you\ncannot raise one for the module that is a special case, and the special case is real more often than anyone likes. Most of the\nchecks measure a proxy, not the harm. LCOM4 counts groups of fields and methods, and a class can have one group and still be a\nmuddle; a count of types is not a count of reasons to change. You will meet the first error just when you wanted to finish,\nand the instinct it provokes, to split the function until the number drops, can produce the thing the limit was written to\navoid: five functions that are only meaningful together, named after their position in the original. A pipeline can be a worse\nread than the loop it replaced (*Stream Pipelines in Depth* says so).\n\n> **A design note.** A linter that can be turned off will be turned off, on the afternoon before a release, by someone who is right that the\n> deadline matters. I do not want to win that argument with a better argument. I want the argument not to be available. So the\n> limit lives in the compiler, there is no comment that disables it, and the figure in the message is the same for everyone\n> who reads it, including the next person to inherit the code. It costs you the afternoon on which the limit is wrong. I\n> think that is a good price for never again inheriting a function that nobody dared touch. *- Steve*\n\nWhat it buys is a floor, not a ceiling. Code that compiles has passed every check in this chapter, so a reader meets no\nfunction above the cognitive limit and no class that depends on thirteen types, in this project or in a dependency that built.\nWhat it does not say is that the design is good, or that the tests ask the right questions: HEX estimates exposure and the\ncompiler has no way to know what the right question was. The comment is still the one thing the compiler cannot check\n(*Organising a Growing Codebase*), and this chapter is the other side of that argument: everything that *can* be measured has\nbeen, and the result is an error.\n\n[^qualityv1]: If you skipped Volume 1, *Testing as You Go* introduces coverage and the 80% bar, and *Components* introduces coupling\nand cohesion.\n","examples":["books/ek9-in-depth/ch40-quality-built-in/AddressRecord.ek9","books/ek9-in-depth/ch40-quality-built-in/OrderReport.ek9","books/ek9-in-depth/ch40-quality-built-in/postage/dev/tests.ek9","books/ek9-in-depth/ch40-quality-built-in/postage/postage.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"The Payoffs: Liskov and Hoare","url":"https://ek9.io/books/ek9-in-depth/the-payoffs-liskov-and-hoare.html","markdown":"# The Payoffs: Liskov and Hoare\n\n*The Evidence*, at the end of Volume 1, said that \"two names sit behind the whole language, and the second volume returns to\nthem\": Hoare's null mistake, and the Liskov Substitution Principle. You have now met every mechanism that serves them, one at a\ntime and under other names: a tri-state value and a checked `get()`, a `pure` that an override must keep, one sameness per type,\na type that is closed unless it says otherwise, a dispatcher where another language writes a cast. This chapter does not teach\nanything new. It says what the mechanisms were for, shows the compiler refusing each way of breaking the promise, and then says\nexactly how much of each promise is checked today, which is not the same for the two names.\n\nBoth problems are ones every language has, and the usual answer to both is a rule that a reviewer is expected to remember. EK9's\nanswer is to make the betrayal impossible to write where it can, and to say so where it cannot yet.\n\n## Substitution, as the compiler checks it\n\nBarbara Liskov's principle (1987, and with Jeannette Wing as a behavioural definition in 1994) says that a subtype must be\nusable wherever its parent is, *without the caller being able to tell*. A caller written against `Shape` may rely on whatever\n`Shape` promises, and every subtype must keep those promises, not only the ones the type checker happens to see. The principle\nhas no enforcement in most languages; it is advice. You have probably met its breaches in Java: a `List.of(...)` whose `add`\nthrows, an `equals` that disagrees with `hashCode`, an `instanceof` ladder that has to be extended for every new subclass, an\noverride that was meant to replace a method and did not because the signature drifted. This is the working case, a `Shape`\nhierarchy whose callers hold the parent type:\n\n```ek9\n#!ek9\ndefines module book.payoffs.shapes\n\n  defines class\n\n    Shape as abstract\n      area() as pure abstract\n        <- rtn as Float?\n\n    Square extends Shape\n      side <- Float()\n\n      Square()\n        -> side as Float\n        this.side: side\n\n      override area() as pure\n        <- rtn as Float: side * side\n\n      override operator ? as pure\n        <- rtn as Boolean: side?\n\n    Rectangle extends Shape\n      width <- Float()\n      height <- Float()\n\n      Rectangle()\n        ->\n          width as Float\n          height as Float\n\n        this.width: width\n        this.height: height\n\n      override area() as pure\n        <- rtn as Float: width * height\n\n      override operator ? as pure\n        <- rtn as Boolean: width? and height?\n\n  defines function\n\n    describe() as pure\n      -> shape as Shape\n      <- rtn as String: `area ${shape.area()}`\n\n  defines program\n\n    Substitution()\n      stdout <- Stdout()\n      shapes <- List() of Shape\n      shapes += Square(3.0)\n      shapes += Rectangle(2.0, 5.0)\n      for shape in shapes\n        stdout.println(describe(shape))\n```\n\n```text\narea 9.0\narea 10.0\n```\n\n`describe` knows nothing of `Square` or `Rectangle`, and `area()` is declared `pure` on `Shape`, so a caller can rely on it\nbeing a query. The rest of this section is the list of ways a subtype could betray that, and what the compiler does about each.\nNone of the examples that follow is an experiment in being clever. Each is the natural thing to write, and each is refused.\n\n**An override may not change the purity contract.** The parent promised `area()` is a query. A subtype whose version assigns\nstate, or one that adds `pure` where the parent did not, would make the same call mean different things depending on the\nobject behind it.\n\n```ek9\nShape as open\n  area() as pure\n    <- rtn as Float: 0.0\n\nCircle extends Shape\n  radius <- Float()\n\n  Circle()\n    -> radius as Float\n    this.radius: radius\n\n  override area()\n    <- rtn as Float: radius * radius\n\n  override operator ? as pure\n    <- rtn as Boolean: radius?\n```\n\n```text\nEK9     : Error   : E05150: 'area' on line 17 position 15: 'override public Float <- area()' and 'public Float <- area()' on line 7 in 'overrideDropsPure.ek9': 'pure' in super requires 'pure' for this definition\n             See: ek9 -h E05150\n           forAI: purityRules\n```\n\nThe compiler's own explanation of the rule (`ek9 -h E05150`) is in Liskov's terms: a child that is substituted for its parent must\nuphold the contract the parent declared, and breaking purity would violate behavioural substitution. It runs the other way too.\nAn override may not add `pure` to a parent that was not pure (E05160); the contract is the parent's, in both directions.\n\n**A subtype that adds state must say what equality means now.** An `Account` is equal to another by `id`. A `NamedAccount` adds an\n`owner`. If it silently inherits `==` and `$`, two accounts that differ only in owner compare equal and print alike, and the\nparent's comparison has been inherited by a type it cannot see into.\n\n```ek9\nAccount as open\n  id <- Integer()\n\n  Account()\n    -> id as Integer\n    this.id: id\n\n  default operator ?\n  default operator $\n  default operator ==\n\nNamedAccount extends Account\n  owner <- String()\n\n  NamedAccount()\n    ->\n      id as Integer\n      owner as String\n\n    super(id)\n    this.owner: owner\n\n  default operator ?\n```\n\n```text\nEK9     : Error   : E07238: 'NamedAccount' on line 17 position 4: 'NamedAccount' has 1 field(s) of its own but would inherit '$' from 'Account', '==' from 'Account', '#?' from 'Account' - declare 'default operator $', 'default operator ==', which also gives '#?' - or the bare 'default operator' for all of them (or write the operator): a type that adds fields, concrete or abstract, must declare its own '$', '$$' and ':=:', and its own sameness ('<=>' or '==', with '#?'), where it would inherit one: the inherited operator was written for the super's fields and cannot know these - use 'default operator' for each (or the bare 'default operator') or write one\n             See: ek9 -h E07238\n```\n\nThe message names the operators the subtype would have inherited and the one-line cure for each. The same rule applies to an\nabstract type that adds fields. That is the point of the one-sameness model in *Operators and Pragmatic Purity, in Full*: a\ntype has exactly one of `<=>` and `==`, the other comparisons are generated from it, and a hand-written pair that could\ndisagree (Java's `equals` against `compareTo`) cannot be written.\n\n**An ordering written for a hierarchy is not the subtype's to change.** When an abstract base writes `<=>` by hand, the whole\nfamily is ordered one way. A `Circle` that orders itself differently, even by asking for a generated comparison of its own, breaks\ntransitivity once different kinds of shape are mixed: one circle sorts before a shape, the shape before another circle, and the\ntwo circles do not sort that way, so a sort depends on the order of its input. `ek9 -h E07182` states the argument and cites\nBloch's item on `equals` in *Effective Java*.\n\n```ek9\nShape as abstract\n  area() as pure abstract\n    <- rtn as Float?\n\n  operator <=> as pure\n    -> other as Shape\n    <- rtn as Integer: area() <=> other.area()\n\n  operator #? as pure\n    <- rtn as Integer: #?area()\n\nCircle extends Shape\n  radius <- Float()\n\n  Circle()\n    -> radius as Float\n    this.radius: radius\n\n  override area() as pure\n    <- rtn as Float: PI * radius * radius\n\n  default operator <=>\n\n  default operator ?\n```\n\n```text\nEK9     : Error   : E07182: '<=>' on line 30 position 23: 'Circle' inherits '<=>' from 'Shape', whose sameness is hierarchy-wide: sameness ('<=>' or '==') written by hand on an abstract base or a trait is hierarchy-wide sameness; a subtype inherits it and cannot redefine it\n             See: ek9 -h E07182\n```\n\n**Replacement is explicit in both directions.** An override must say `override`; a member that overrides nothing must not. A\nsubtype method that matches the parent's by name and signature without the keyword, and one marked `override` with no parent\nversion, are both errors, and the second is how a parent whose signature changed fails loudly in its children and not quietly:\n\n```ek9\nShape as open\n  describe()\n    <- rtn as String: \"a shape\"\n\nCircle extends Shape\n  describe()\n    <- rtn as String: \"a circle\"\n\n  override radius()\n    <- rtn as Float: 1.0\n```\n\n```text\nEK9     : Error   : E05120: 'describe' on line 11 position 6: 'override' required on 'public String <- describe()' in 'Circle' (add it to THIS member only - a member with no parent version must not carry 'override', E05110) as it overrides method of same name/signature in hierarchy\n             See: ek9 -h E05120\nEK9     : Error   : E05110: 'radius' on line 14 position 15: 'radius' has no parent version - remove 'override' from THIS member only (members that do override a parent, such as 'operator ?', keep it): does not 'override' any method/operator\n             See: ek9 -h E05110\n```\n\n**You cannot extend what was not opened.** A class is closed unless it is declared `as open`, so substitution is a decision the\nauthor of the base type makes, and not something any caller can force by subclassing:\n\n```text\nEK9     : Error   : E05030: 'Account' on line 15 position 20: not open to be extended\n             See: ek9 -h E05030\n           forAI: closedByDefault\n```\n\n**There is no cast and no run-time type test.** The remaining betrayal is outside the type system altogether: code that asks an\nobject what it really is, and branches. EK9's grammar has neither a type test nor a cast, so the parser refuses both, and\nbehaviour that depends on the run-time type lives in a `dispatcher` (*The Dispatcher*), where the compiler checks the whole set\nof handlers. A type test written as a condition, and a cast written with `as`:\n\n```text\nSyntax  : 'Circle' on line 19 position 18: unexpected 'Circle' expecting 'empty', 'of', '(', '.', '?', ':', 'not', 'in', '::', ':~:', ':=' or '=' \n```\n\n```text\nSyntax  : 'as' on line 19 position 22: mismatched input 'as' expecting ';' or newline \n```\n\nBoth are syntax errors: there is no rule saying \"do not cast\", because there is no way to say it. A `ClassCastException` has\nno spelling. Two rules from earlier chapters belong in the same list and are not repeated here: a query operator such as `$`\nmust be `pure` and a mutating one must not be, so a subtype cannot make `+` change its operand (E07500 and E07510, in\n*Operators and Pragmatic Purity, in Full*), and an immutable collection is not a subtype that throws, because there is no\nimmutable collection (the same chapter's design note).\n\n| How a subtype betrays its parent | Java | EK9 |\n|---|---|---|\n| a mutator where a query was promised | allowed; the `List.of` pattern throws at run time | the override keeps `pure` (E05150, E05160) |\n| equality and ordering that disagree, or that ignore added state | `equals`, `hashCode` and `compareTo` are three methods | one sameness, the rest generated; added fields must restate it (E07181, E07182, E07238) |\n| a replacement that did not replace | `@Override` is optional | `override` is required and checked both ways (E05120, E05110) |\n| extension nobody planned | every class is open unless `final` | every class is closed unless `as open` (E05030) |\n| asking an object what it is | `instanceof` and a cast | none; a `dispatcher` |\n\n> **A design note.** I closed types by default because inheritance is a promise the author of the base class has to be able\n> to keep, and an author cannot keep a promise to subclasses that do not exist yet. Java's open `ArrayList` is the example I\n> would point at: a class that nobody meant to be a base, extended by programs that now depend on its internals. The answer\n> is delegation, and traits with `by` make it as easy as inheritance. A class declared `with trait of View by inner` has\n> every method of `View` forwarded to `inner` without writing one; it overrides only the methods it means to change, as a\n> subclass would, and what it holds stays the type that was tested. *- Steve*\n\n### Where substitution stops\n\nThe compiler checks the *shape* of the contract, and not its content. It knows an override kept `pure`, restated its sameness,\nand said `override`. It cannot know that `area()` returns an area: a `Rectangle` whose `area()` returns the perimeter compiles,\nis pure, and breaks every caller. Preconditions and postconditions, the part of Liskov and Wing that is about meaning, are\nstill `require`, `assert` and tests (*Testing the Compiler Trusts*). What the structure does is shrink the set of ways a\nsubtype can betray its parent to the ones that need a human to have written the wrong *value*, and remove the ones that only\nneeded a human to have forgotten a keyword.\n\n## The null mistake\n\nTony Hoare introduced the null reference in 1965 and called it, in 2009, his billion-dollar mistake. The mistake is not the\nabsence of a value; every program has to model that. It is that absence arrives as a value of the ordinary type, so the type\nchecker says nothing, and the program fails far from where the absence was introduced. EK9's answer has three parts, and each is\na chapter you have read.\n\n**There is no way to write one.** `null` is not a keyword, and a program that tries is refused:\n\n```ek9\nNullProbe()\n  stdout <- Stdout()\n  name as String: null\n  stdout.println(name)\n```\n\n```text\nEK9     : Error   : E01073: 'null' on line 8 position 22: 'null' does not exist in EK9 - use tri-state semantics (unset/set) with '?' operator\n             See: ek9 -h E01073\n           forAI: excludedFeatures.null\n```\n\nThe message names the replacement. A value is absent, present but unset, or present and set, and the program tests the second\nand third with `?`. `Integer()` and `String()` are *unset*: real objects that answer the question and propagate unset through\narithmetic. The removed null-coalescing token is refused with its own code, E01096, whose message points at `?:` and `:=?`; it\ntested for an absence that EK9 is designed not to let a program see.\n\n**The tri-state operators do what they say.** `:=?` assigns only when the target is unset, so it never overwrites a real value;\n`?:` supplies a fallback when its left is unset:\n\n```ek9\nAssignIfUnset()\n  stdout <- Stdout()\n  name <- nameOf(true)\n  name :=? FALLBACK_NAME\n  stdout.println(`a set name stays [${name}]`)\n  missing <- nameOf(false)\n  missing :=? FALLBACK_NAME\n  stdout.println(`an unset name becomes [${missing}]`)\n```\n\n```text\na set name stays [Ada]\nan unset name becomes [anon]\n```\n\n```ek9\nFallback()\n  stdout <- Stdout()\n  unknown <- numberOf(false)\n  chosen <- unknown ?: OFFSET\n  stdout.println(`unset or ${OFFSET} gives ${chosen}, set? ${chosen?}`)\n  known <- numberOf(true)\n  kept <- known ?: OFFSET\n  stdout.println(`set or ${OFFSET} gives ${kept}, set? ${kept?}`)\n```\n\n```text\nunset or 5 gives 5, set? true\nset or 5 gives 42, set? true\n```\n\n**What cannot be set is checked at the read.** The one place a value can be missing is a declaration that says so, `x as T?`,\nwhich is a slot with nothing in it yet. The compiler's job is to prove the slot is never read before it is written:\n\n```ek9\nEmptySlot()\n  stdout <- Stdout()\n  name as String?\n  stdout.println(name)\n```\n\n```text\nEK9     : Error   : E08020: 'name' on line 9 position 21: 'name as String': might be used before being initialised\n             See: ek9 -h E08020\n```\n\nThe check is a whitelist, not a search for known bad shapes. A test in the compiler's own suite lists every position in the\ngrammar where a name can be read, and fails the build if any is unclassified or has no checking rule behind it; one shared\ncheck, behind E08020, covers the reads of local names. `Optional` and `Result` add E08030 on top, for a `get()` or an `ok()` outside a block\nwhose check proved it.\n\n### The cost of tri-state\n\nYou cannot ask an unset value to fail, and it will not. An unset operand makes an arithmetic result unset, quietly, and that is\nthe defined behaviour, not an accident. The price is that it can go unnoticed. Here an unset number takes part in a sum, and the\nprogram asks to print it three ways:\n\n```ek9\nUnsetFlows()\n  stdout <- Stdout()\n  unknown <- numberOf(false)\n  total <- unknown + OFFSET\n  stdout.println(`total is [${total}]`)\n  stdout.println(`total set? ${total?}`)\n  stdout.println($total)\n  stdout.println(\"after the unset lines\")\n```\n\n```text\ntotal set? false\nafter the unset lines\n```\n\nTwo of the four lines are missing. An interpolated string that holds an unset value is itself unset, and printing an unset\n`String` prints nothing, neither a blank line nor `[]`. Only `${total?}` shows it. That is the cost of the model: where Java\nwould have thrown an exception at the first use of the missing value, EK9 carries the unset through and says nothing until you\nask with `?` or a guard. The guard is the cure, because it makes you ask where the value arrives (*Guards and Safe Code*), but\nthe language does not make you.\n\n## What is claimed, and what is not yet proven\n\nFor absence, the sentence that can be said today is this: EK9 is **designed so that absence is unobservable; the compiler checks\nevery read; the proof is in progress.** Each of the three clauses is narrower than it sounds.\n\n*Designed so that* is a statement about design intent and about a work list that has no known open item: no route to a\nvalue-less slot is known to be open, and the document that records the investigation says plainly that the guarantee is not\nyet a theorem. *The compiler checks every read* is the whitelist above, and it is built. *The proof is in\nprogress* means that the layers that would turn \"no counterexample found\" into a theorem are not built: a check, in the middle\nof the compiler, that every load in the generated intermediate form is preceded by a store on every path; a check over the\nruntime library, at build time, that none of its operations can return an absent value; a generator that fuzzes programs\nspecifically to provoke an absent value; and the written proof over all of them. Third-party code, once it can be called from\nEK9 (it cannot be today), will sit outside the guarantee and its results will be checked at the boundary.\n\nThere is also a switch for the cautious. Running a compiled program with the Java property `ek9.absent.strict` set to `true`\nturns an observed absence into a panic that names the place, instead of a quiet wrong answer. It is off by default, and a cached\nbuild has to be cleaned before it takes effect.\n\nThat is the most the evidence supports, and it is why this book has said *designed so that* every time. When the remaining\nlayers exist and the corpus runs clean under the strict switch, the sentence changes. Until then, what you can rely on is what\nthe compiler *does*: a read it cannot prove legal is an error, with a code and a line.\n\n## The cost\n\nYou cannot reach for the shortcut. There is no `null` to return when you do not know, no cast to get past a type you could not\nprove, no override that quietly differs, and no way to loosen a limit on the afternoon it is wrong. Each refusal is a place\nwhere another language would have let you finish and left the consequence for a later reader or a later run. In EK9 the\nconsequence arrives as a compile error, sooner and in your hands, which is a real cost when the thing you refused was right.\n\nWhat it buys is the ability to read a program and know what a call may do. A call through a parent type keeps the parent's\npurity and the parent's equality. A value is either set or you were made to ask. A name that can be read has been checked.\nThose are narrower than \"the program is correct\", and the two problems this chapter names are narrower still: a subtype can\nstill return a wrong value, and the proof about absence is not finished. The preface asked of every rule whether it removes a category of\nfailure or merely discourages it. This volume has shown where the answer is removal, where the compiler checks it, and where\nthe work is still in progress.\n\nFor the research behind each rule, and for Hoare's own account, see *The Evidence*.\n","examples":["books/ek9-in-depth/ch41-the-payoffs/Substitution.ek9","books/ek9-in-depth/ch41-the-payoffs/TriState.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Coming from another language?","url":"https://ek9.io/books/ek9-in-depth/appendix-coming-from.html","markdown":"# Coming from another language?\n\nThis appendix is a lookup, not a tour. Find the thing you would reach for in Java, Kotlin, C#, Rust, Go, Python or\nTypeScript, and the table says what EK9 has in its place and which chapter explains it. Where the table says \"none\", that is\na decision and not an omission: *The Evidence* gives the reason for each removal, and the first rows are the reflexes that\ncost newcomers the most time.\n\n## Reflex to EK9\n\n| You reach for | EK9 has | Where it is taught |\n|---|---|---|\n| `null`, `None`, `nil` | no such keyword and no way to write one (E01073). A value is absent, unset or set, and `?` asks whether it is set | *Values and the Three States*; *Optional and Result, in Depth* |\n| `Optional.get`, `unwrap`, `!!`, `.Value` | `get()` only inside a block whose check proved the value present (E08030 otherwise) | *Optional and Result, in Depth* |\n| optional chaining and null-coalescing operators | a `<-` guard on `if`, `switch`, `for`, `while` and `try`, and `?:` for \"this, or that when unset\" | *Guards and Safe Code* |\n| `break`, `continue`, `return`, `goto` | none. Pipelines, guards, a declared return variable and multiple case values | *Making Decisions and Repeating Work*; *Stream Pipelines in Depth* |\n| `switch` with fall-through | `switch` with several values per `case`; no fall-through | *Making Decisions and Repeating Work* |\n| `instanceof`, casts, `as`, type patterns | none. A `dispatcher` routes a call on the argument's run-time type | *The Dispatcher* |\n| `equals`, `hashCode`, `compareTo`, `toString`, `clone` | operators `==`, `#?`, `<=>`, `$`, `:=:`; one sameness per type and the rest generated | *Using Operators*; *Operators and Pragmatic Purity, in Full* |\n| a new operator, or any meaning for an old one | a fixed set; a query operator must be `pure` and a mutating one must not be | *Operators and Pragmatic Purity, in Full* |\n| `final`, `const`, `val`, immutable collections | none. Every value is mutable; `pure` is a property of the function that does the work | *Operators and Pragmatic Purity, in Full* |\n| lambdas, closures, `Func<>`, `fn` | a function is a value; an inline one is a *dynamic function*, with a capture list when it uses the surrounding scope | *Functions as Values: the Type Hierarchy*; *Dynamic Functions and Classes* |\n| `interface` | a `trait` (behaviour, no state) for composition; an abstract `component` for a wired dependency | *Traits and Composition*; *Components* |\n| inheriting from any class | closed by default, open only with `as open` (E05030 otherwise) | *Classes*; *Abstract Types, Subtypes and Polymorphism* |\n| `record`, data class, `struct` | `defines record`: public fields, operators, no methods | *Records and Enumerations* |\n| `enum` with fields and methods | an enumeration; constrain a base type with `constrain as` for a range | *Records and Enumerations*; *Constrained Types* |\n| generics with bounds | `of type T` for a type and `of type (K, V)` for several; a bare `T` gets only what `Any` offers | *Using Generics*; *Write-Your-Own Generic Types and Functions* |\n| `static` methods and fields | none. A module holds functions and constants | *Functions* |\n| `import`, `using`, `use` | a `module`, and `references` to bring in another module's names, in alphabetical order (E11026) | *Organising a Growing Codebase* |\n| checked or unchecked exceptions, `panic`, `error` values | `try`/`catch`/`finally` for the unexpected, `Result` for the expected; the compiler closes a `try` resource on every path | *Errors and Exceptions* |\n| `synchronized`, `Mutex<T>`, channels, `async`/`await` | a `MutexLock of T`, entered with a `MutexKey` function; `| async` is a pipeline stage | *Concurrency, Safely* |\n| Spring, Guice, Dagger | `component`, `application` and `register`; wiring is checked before the program runs | *Dependency Injection and Applications* |\n| AspectJ, decorators, middleware | `with aspect of` at the registration line | *Aspects* |\n| JUnit, pytest, `go test`, `cargo test` | an `@Test` program under `dev/`; assertion, black-box and parameterized tests share one runner | *Testing as You Go*; *Testing the Compiler Trusts* |\n| SonarQube, Checkstyle, ESLint, coverage plugins | limits that are compile errors, and a coverage bar that stops `-P` | *Quality Built In* |\n| `BigDecimal`, a currency library | `Money`, with its own literal | *Text, Numbers, Time and Money* |\n| Maven, Gradle, Cargo, npm, Go modules | a `package` block and `ek9 -P`; dependencies declared in the source | *Packaging and Sharing Your Program* |\n| `public static void main` | a `program`, with typed arguments | *Programs, Input and Output* |\n| string formatting and templates | a backtick string with `${expression}` | *Text, Numbers, Time and Money* |\n| a web framework | a built-in `service` with HTTP verbs on its operations | *A Web Service, Step by Step* |\n\nTwo of those rows hide a surprise worth saying aloud. EK9 has no immutable data structures, and that is deliberate: the safety\nis in which function may change what (*Operators and Pragmatic Purity, in Full*), not in freezing the data, and a Rust or Haskell\nprogrammer will notice the gap. And an `Integer` that overflows is unset and does not wrap, which makes an arithmetic overflow\na tri-state question and not a silent wrong number.\n\n## By language\n\n**Java and Kotlin.** The obvious things carry over: classes, generics with type arguments, a single module namespace. The\nreflexes that fail are `equals`/`hashCode` pairs, which are operators here and cannot disagree; open classes, which are closed\nunless declared otherwise; checked-versus-unchecked exceptions, replaced by `Result` for what you expect; and Spring's runtime\nwiring, replaced by checks the compiler makes. Kotlin's safe-call and elvis operators are the nearest relatives of a guard and of `?:`, and\nthe difference is that the unsafe form does not exist (*Optional and Result, in Depth*).\n\n**C#.** `Func<>` and `Action<>` are function types, and EK9 derives the equivalent from the shape of a function and whether it\nis `pure` (*Functions as Values: the Type Hierarchy*). LINQ queries are stream pipelines. There is no `await`; concurrency is a\nlock around a value and an `async` pipeline stage.\n\n**Rust.** `Result` and exhaustive matching are familiar, and so is the wish to make misuse impossible. EK9 has no borrow checker\nand no ownership annotations; shared mutable state is permitted only through a `MutexLock`, and the compiler's analysis covers the\nshapes it accepts, which *Concurrency, Safely* states.\n\n**Go.** Explicit `error` returns are replaced by `Result` for what you expect and an exception for what you do not. There are no\ngoroutines or channels; a `| async` stage and a `MutexLock` are the nearest. Table-driven tests become a parameterized `@Test`\nwhose table is files (*Testing the Compiler Trusts*), and `go fmt` is `ek9 -f`, one canonical format.\n\n**Python and TypeScript.** The shift is largest here: every type is checked at compile time, and indentation is syntax, as in\nPython, with `ek9 -f` giving every file one canonical layout. Comprehensions are pipelines, dictionaries are `Dict`, and a\ndecorator is an aspect at a registration line. `None` and `undefined` do not exist.\n\n## What is not here yet\n\nTwo things you would reasonably ask for are planned and are not available today, and the book does not teach them as working.\n\n**Calling Java libraries from EK9** is not yet available. EK9 programs compile to Java bytecode and run on the JVM, but a program\ncannot import and call a Java library. It is planned, and until it ships, what your program needs from the outside world is what\nthe built-in types provide (*Built-in Types at a Glance*).\n\n**A public package repository, and deploying to one,** is planned too. Packaging, installing from your own library and versioning\nare available today and are shown in *Packaging and Sharing Your Program*, along with the point at which a dependency resolves and\nthe point at which it does not yet.\n","examples":[]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Built-in Types at a Glance","url":"https://ek9.io/books/ek9-in-depth/appendix-types.html","markdown":"# Built-in Types at a Glance\n\nEvery type here is in the `org.ek9.lang` module and needs no `references`. This appendix is a map, one line per type; the\nauthority for any one of them is the compiler's own help, `ek9 -h <Type>`, which lists every constructor, method and\noperator of the type and is generated from the runtime. `ek9 -H` lists every keyword, the built-in types among them. Every\ntype is tri-state: it can be set, unset or absent, and `?` asks whether it is set (*Values and the Three States*). Collections\nare the one place where that differs by type: a list or dictionary is set the moment it exists, empty or not.\n\n## Values\n\n| Type | What it is | Written as |\n|---|---|---|\n| `Boolean` | logical true or false; `and`, `or`, `xor`, `not` | `true`, `false` |\n| `Character` | one Unicode character | `'A'`, `'\\n'` |\n| `String` | Unicode text; `+`, `length`, `contains`, `matches` | `\"hello\"`, `` `Hello ${name}` `` |\n| `Integer` | 64-bit signed whole number; overflow gives *unset*, never a wrapped value | `42`, `0x1F`, `1_000` |\n| `Float` | 64-bit IEEE 754; `<~>` is the fuzzy comparison | `3.25`, `-2.5e10` |\n| `Money` | exact decimal currency, so never a `Float` | `25.99#GBP` |\n| `Bits` | variable-length bit sequence; `and`, `or`, `xor`, `~`, shifts; `+` joins | `0b1010` |\n| `Byte` | unsigned 8-bit value with no arithmetic; out of range is unset | `Byte(255)` |\n| `Bytes` | immutable binary data; the literal is hex digits in pairs | `0yDEADBEEF` |\n| `BytesBuilder` | the mutable write side of `Bytes` | `BytesBuilder()` |\n| `BytesReader` | forward-only cursor over `Bytes`; a read past the end is unset | `aBytes.reader()` |\n| `Colour` | RGB or ARGB colour | `#FF5500` |\n| `Dimension` | a size with its unit | `42.5km`, `1920px` |\n| `Resolution` | dots per inch or per centimetre | `300dpi`, `118dpc` |\n| `Locale` | language and region | `Locale(\"en_GB\")` |\n| `Version` | semantic version | `1.2.3-0` |\n| `GUID` | a UUID; `GUID()` makes a new one | `GUID()` |\n| `RegEx` | a regular expression with its own literal | `/[a-z]+/` |\n| `Path` | a JSONPath, an address *into* structured data and not a file path | `$?.store.book[0].title` |\n| `Void` | \"no return value\" in a signature; not a variable type | |\n\nOne program holds a literal of every type that has one, and prints each. It is the quickest way to see the forms:\n\n```ek9\n#!ek9\ndefines module book.types.literals\n\n  defines program\n\n    Literals()\n      stdout <- Stdout()\n\n      truth <- true\n      letter <- 'A'\n      text <- \"hello\"\n      count <- 1_000\n      hexCount <- 0x1F\n      ratio <- 3.25\n      bits <- 0b1010\n      octets <- 0yDEADBEEF\n      shade <- #FF5500\n      day <- 2024-01-15\n      moment <- 2024-01-15T10:30:00Z\n      clockTime <- 10:30:00\n      span <- PT1H30M\n      short <- 500ms\n      price <- 25.99#GBP\n      distance <- 42.5km\n      density <- 300dpi\n      locale <- Locale(\"en_GB\")\n      release <- 1.2.3-0\n      address <- $?.store.book[0].title\n      pattern <- /[a-z]+/\n      names <- [\"Ada\", \"Grace\"]\n      ages <- {\"Ada\": 36, \"Grace\": 85}\n\n      stdout.println(`boolean ${truth}, character ${letter}, string ${text}`)\n      stdout.println(`integer ${count}, hexadecimal ${hexCount}, float ${ratio}`)\n      stdout.println(`bits ${bits}, bytes ${octets}, colour ${shade}`)\n      stdout.println(`date ${day}, datetime ${moment}, time ${clockTime}`)\n      stdout.println(`duration ${span}, millisecond ${short}, money ${price}`)\n      stdout.println(`dimension ${distance}, resolution ${density}, locale ${locale}`)\n      stdout.println(`version ${release}, path ${address}, regex ${pattern}`)\n      stdout.println(`list ${names}, dict ${ages}`)\n```\n\n```text\nboolean true, character A, string hello\ninteger 1000, hexadecimal 31, float 3.25\nbits 1010, bytes DEADBEEF, colour #FF5500\ndate 2024-01-15, datetime 2024-01-15T10:30:00Z, time 10:30:00\nduration PT1H30M, millisecond 500ms, money 25.99#GBP\ndimension 42.5km, resolution 300dpi, locale en_GB\nversion 1.2.3-0, path $?.store.book[0].title, regex [a-z]+\nlist [\"Ada\", \"Grace\"], dict {Ada=36, Grace=85}\n```\n\nThree of the forms surprise people from other languages. Money is written with the currency after the amount,\n`25.99#GBP`; a bare version such as `1.2.3` does not parse, because the literal always carries its build number\n(`1.2.3-0`); and a locale has no literal - it is made with `Locale(\"en_GB\")`. The values on the right of the table are\nthe ones the example above compiles.\n\n## Time\n\n| Type | What it is | Written as |\n|---|---|---|\n| `Time` | time of day | `10:30:00` |\n| `Date` | calendar date | `2024-01-15` |\n| `DateTime` | date and time with a zone | `2024-01-15T10:30:00Z` |\n| `Duration` | a span, ISO 8601 | `PT1H30M` |\n| `Millisecond` | a short span in milliseconds | `500ms` |\n| `SystemClock` | the system time source; the implementation of the `Clock` trait; a test supplies a fixed clock | `SystemClock()` |\n\n## Collections and containers\n\n| Type | What it is |\n|---|---|\n| `List of T` | ordered, indexable; `[1, 2, 3]`; `+=` adds |\n| `Dict of (K, V)` | key to value; `{\"a\": 1}`; iterating yields `DictEntry` |\n| `DictEntry of (K, V)` | one pair from a dictionary; `key()` and `value()` |\n| `PriorityQueue of T` | heap ordered by `<=>`, so `T` must be comparable |\n| `Iterator of T` | lazy sequence; `hasNext()` before `next()`; a stream source |\n| `Optional of T` | zero or one value; `get()` only in a checked block (*Optional and Result, in Depth*) |\n| `Result of (O, E)` | an ok value, an error value, both or neither (*Optional and Result, in Depth*) |\n\n## Input, output and the system\n\n| Type | What it is |\n|---|---|\n| `Stdout`, `Stderr` | `println` and `print`; accept anything with a `$` operator |\n| `Stdin` | standard input as lines; `hasNext()` and `next()`, and a stream source |\n| `TextFile` | set only when its path is absolute and names an existing file; opened for `input()` or `output()` in a `try` |\n| `FileSystem` | `cwd()` and `tmp()`, each a `FileSystemPath` |\n| `FileSystemPath` | a platform-independent path, with the file operations |\n| `JSON` | a JSON document; `JSON().parse(text)` gives a `Result of (JSON, String)`, and `$$` serialises any type |\n| `GetOpt` | command-line option parser |\n| `OS` | process id, `delay`, non-cryptographic random numbers |\n| `EnvVars` | environment variables, sanitised by default; `sensitiveGet` returns a `Sensitive` |\n| `Signals` | operating-system signal handlers |\n| `Exception` | the base of every exception, open for your own; `reason()` and `exitCode()` (*Errors and Exceptions*) |\n\n## Network, concurrency and security\n\n| Type | What it is |\n|---|---|\n| `TCP`, `UDP` | sockets, both made in a `try` from a `NetworkProperties` (*Networking: TCP and UDP*) |\n| `MutexLock of T` | mutual exclusion around a value, entered with a `MutexKey of T` (*Concurrency, Safely*) |\n| `Digest` | unkeyed `SHA256` and `SHA512`: integrity only |\n| `HMAC` | a keyed code over `Bytes`: integrity and authenticity |\n| `SecureRandom` | cryptographically secure random octets as `Bytes`, deliberately not a `Random` |\n| `Word64` | sixty-four bits whose `+ - *` wrap and whose comparisons are unsigned; `Integer` stays checked |\n| `Hasher` | builds a hash from any values with `+=` or `\\|`, never overflowing to unset; what every generated `#?` uses |\n| `InputSanitizer` | what the `sanitized` modifier uses; write `sanitized`, not a call (*A Web Service, Step by Step*) |\n\nWhen a type you expect from another language is missing from the tables, look for the operator before you look for a type:\n`a == b`, `a <=> b`, `$ a`, `#? a` and `target :=: source` stand where `equals`, `compareTo`, `toString`, `hashCode` and\n`clone` would (*Operators and Pragmatic Purity, in Full*), and `ek9 -h <Type>` prints the constructors, so there is never a\nneed to guess whether a type can be made from a `String`.\n","examples":["books/ek9-in-depth/ch96-types-at-a-glance/Literals.ek9"]}
{"book":"ek9-in-depth","bookTitle":"EK9 in Depth","chapter":"","title":"Where to go next","url":"https://ek9.io/books/ek9-in-depth/appendix-where-next.html","markdown":"# Where to go next\n\nThe book has taught you to write EK9. This appendix is about what to reach for once the program exists: finding a fault in a\nrunning program, finding where it is slow, writing the tests nobody wants to write, and finding out whether the tests you did\nwrite are any good. Every one of these is a command of the `ek9` binary today. The examples run against one small project, the\n`postage` function from *Quality Built In* with its six tests, and every block is output from a real run.\n\nThe graphical side of all this, the editor, the debugger's windows and the refactoring tools, is not here. It has its own\nbook, *The EK9 IDE and Refactoring Toolset*, a living web reference; the chapters of this volume stay at the command line.\n\n## The debugger and the journal\n\n`ek9 -cg file.ek9` compiles with debugging information, and `ek9 -d <port> file.ek9` runs the program with a debug agent\nlistening on that port, without waiting for a debugger to attach:\n\n```text\njava -Xmx512m -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:4450 -jar './.ek9/jvm/debug/AddressRecord.jar' -r book.quality.address::ShowAddress\n```\n\nThat line is what the compiler hands to the launcher for `ek9 -d 4450 AddressRecord.ek9`. Read it before you use the flag:\n`address=127.0.0.1:4450` means the agent listens on this machine only: a debug port runs whatever code it is sent, so\nit is never opened to the network.\n`suspend=n` means the program starts at once, so the port is for attaching to a program that is already running.\n\nThe debugger itself is a library behind three hosts: the IDE, `ek9 -dap`, which speaks the Debug Adapter Protocol so that an\neditor of your choice can debug an EK9 program, and `ek9 -mcp`, which gives an AI assistant the same session as tools. A run\ncan also be *journalled*, which records every change to one value you choose without stopping the program, then compares runs\nthat passed with runs that failed and writes the difference up as a report. `ek9 -h journal` is its reference, and it is\ndriven from the IDE or over MCP; the companion book has its workflow.\n\n## Profiling\n\nAdd a `p` to any test flag and the run is instrumented. `-tp` prints a hot-function summary after the coverage summary, `-t2p`\nwrites it as JSON for a tool to read, and `-t6p` writes the HTML report with a flame graph. On the six tests:\n\n```text\nProfiling: 1 functions profiled\n  postage                             Self: 4.108ms  Calls: 6\n```\n\nThe figure is the time spent in the function itself, and how many times it was called. Timings differ every run; the count\ndoes not. Profiling forces the unoptimised build so that each probe maps to a source line, which is the opposite of how a\npackaged program is built (`-O3`), so use it to find which function is hot and not to say how fast the release will be.\n\n## Tests nobody wants to write\n\n`-fuzztest` reads a source file's symbol table and writes `@Test` programs for the edge values of every function it finds. The\noutput has to go under a `dev/` folder, because a test outside one is E81015:\n\n```text\nEK9 Test Generation: analyzing postage.ek9\nSeed: 7, Max candidates: 200\nFound 0 types, 1 functions\nTests will be declared in module book.quality.postage.tests (source module is book.quality.postage) — emitting a references block\nGenerated 51 test candidates\nSurvivors: 51 / 51 (100%)\nConstants written to: dev/constants.ek9\nOutput written to: dev/generated.ek9\n```\n\nIt wrote 51 candidates, and a header that is worth reading in full. They are *scaffolding*: the generator wrote the calls and the\nedge values, and \"did NOT decide what the right answer is\". Each test asserts only that the call returns a set value, with a\ncomment marking where you must write the expected result from the requirement. The edge values come from the integer\nliterals in the file (the constants of `postage` give 249, 250 and 251 around the surcharge, for instance). The warning in the\nheader is the one from *Testing the Compiler Trusts*, stated by the tool: if you keep whatever assertion passes you have\nfrozen today's behaviour, defects included. Keep the useful candidates, set their expectations yourself, and delete the rest.\n\n## Do your tests notice?\n\nCoverage and variety measure what ran. Mutation testing asks a different question: if the code were slightly wrong, would a\ntest fail? `-fuzzmutate` writes one file per single-point change that still compiles, in a directory and a manifest:\n\n```text\nEK9 Mutation Testing: analyzing postage.ek9\nSeed: 7, Max candidates: 100\nGenerated 16 mutation candidates\nSurvivors: 16 / 16 (100%)\nOutput written to: mutations\n```\n\n\"Survivors\" here means the mutants *compile*; whether your tests catch them is the next step. The manifest lists each file, the\nkind of change, the line and the original and mutated text.\n\n<!-- recheck: -fuzzmutate with -test tests.ek9 is accepted but runs no kill-check and prints nothing more -->\nThe command-line help also lists a `-test` flag that is meant to run the kill-check for you; at the time of writing it is\naccepted and prints nothing further, so the check is a loop of your own. Copy each mutant\nover the source in a scratch project, run the tests with `-t0`, and note whether they failed. For the six tests of `postage`:\n\n```text\nmutation_000_boundary_L5.ek9   BOUNDARY  line 5   500 -> 499: survived\nmutation_001_boundary_L5.ek9   BOUNDARY  line 5   500 -> 501: survived\nmutation_002_boundary_L6.ek9   BOUNDARY  line 6   5000 -> 4999: survived\nmutation_003_boundary_L6.ek9   BOUNDARY  line 6   5000 -> 5001: survived\nmutation_004_boundary_L7.ek9   BOUNDARY  line 7   300 -> 299: killed\nmutation_005_boundary_L7.ek9   BOUNDARY  line 7   300 -> 301: killed\nmutation_006_boundary_L8.ek9   BOUNDARY  line 8   450 -> 449: killed\nmutation_007_boundary_L8.ek9   BOUNDARY  line 8   450 -> 451: killed\nmutation_008_boundary_L9.ek9   BOUNDARY  line 9   900 -> 899: killed\nmutation_009_boundary_L9.ek9   BOUNDARY  line 9   900 -> 901: killed\nmutation_010_boundary_L10.ek9  BOUNDARY  line 10  250 -> 249: killed\nmutation_011_boundary_L10.ek9  BOUNDARY  line 10  250 -> 251: killed\nmutation_012_cmp_flip_L20.ek9  CMP_FLIP  line 20  <= -> <: survived\nmutation_013_cmp_flip_L22.ek9  CMP_FLIP  line 22  > -> <: killed\nmutation_014_cmp_flip_L22.ek9  CMP_FLIP  line 22  > -> >=: survived\nmutation_015_arith_swap_L26.ek9 ARITH_SWAP line 26  + -> -: killed\n```\n\nEvery change to a price or to the surcharge was caught, because a test asserts each price. The survivors are the boundaries:\nthe limit between a letter and a parcel (500) and the limit above which a parcel is heavy (5000), neither of which any test\nuses, and the two comparison changes that move a weight across one of those limits, `<=` to `<` on line 20 and `>` to `>=`\non line 22. That project has full coverage\nand a modest HEX score (*Quality Built In*), and six of its sixteen mutants survive. The mutants that survive are the tests you\nstill owe, and unlike a variety figure they are specific: each names a line and a change.\n\n## Fuzzing the compiler\n\n`-fuzz` is for people who work on the compiler, and for anyone who wants to know how it is tested. It generates programs from\nthe grammar and mutates the corpus, feeds them to the compiler, and reports any that make the compiler itself crash. A one\nminute run:\n\n```text\nEK9 Grammar Fuzzer started. Duration: 1m Workers: 9\nCrash files will be saved to: ./fuzz-crashes\nTemplates loaded: 1254 (S2: 20%, S3: 20%, S5: 20%)\nTargeted files: 1122 (1818 mutations, S4: 20%)\n\nPASS: 0 crashes, 0 known, 398/442 errors, 31,964 programs in 1m 0s\nEK9     : EK9 running grammar-based fuzzer\n```\n\nA crash is saved under `fuzz-crashes/` as a file you can compile again, and a run that finds one exits with 15, so a build can\ngate on it. `-fuzz2` writes JSON and `-fuzz6` an HTML dashboard. It tests the compiler, not your program; for your program the\ntools above are the ones.\n\n## Asking the compiler\n\nThree commands answer most questions without leaving the terminal. `ek9 -h <keyword>` is the reference for a construct, a\nbuilt-in type or an error code, `ek9 -H` lists every keyword, and `ek9 -q <words>` searches a corpus of questions and answers\nthat carry compiled examples; `-qm` adds a comparison with another language. When you want the compiler to explain a\ndiagnostic at length, add `-E3` to the compile. The exit codes a script can rely on are in `ek9 -h`: 8 for a compile\nfailure, 11 for a failed test, 12 for coverage below the bar and 15 for a fuzz crash.\n\nFor the network types, the next chapter to reread is *Networking: TCP and UDP*; for packaging what you have built, *Packaging\nand Sharing Your Program*; for the places where the compiler stops you and why, *Quality Built In* and *The Payoffs: Liskov\nand Hoare*.\n","examples":[]}
