12 October 2026

Improving the Harness

Dog-Sled Racing (licensed CC BY-NC-ND by Traveller_40)Now that GenAI is all the rage, I will share more about it. Kent Beck says "nobody knows for sure, we can just explore and share what we found".

Here is a little trick I use to improve my AI workflow. Birgitta Böckeler defines harness as the support we give a coding agent to help it do its job, so harness engineering is all the work we do around that to make that possible. A part of the harness comes with your coding agent (i.e. inner harness - e.g. its system prompt), and there are parts which we add (i.e. outer harness - e.g. skills). The harness can contain feed-forward "guides" (all the markdown files) and feedback "sensors" (tests, linters and the like).

Learning From Past Conversations
While researching the different workflows people use with GenAI, I read an advice that from time to time, you should scan your agent conversations, check what the agent did wrong and then got right - either by itself or by your correction. Then update your guides to avoid this problem in the future. (Unfortunately, I cannot remember the source any more.) My first challenge was finding my past conversations. I started my GenAI journey with Codeium in September 2023, which became Windsurf which then became Devin. Where were my conversations? Windsurf was based on VSCode and I found the conversations in my home directory. They were in binary format which looked like protobuf and people were unable to decrypt them. Bummer. When I switched to Mistral (because of the CLOUD Act and I like Europe's GDPR way more ;-) the situation improved. Mistral VIBE stored its conversations as JSON lines in a my home directory ~/​.vibe/​logs/​session/​session_*/​messages.jsonl. And even if it had hidden them, I could have modified its source code. That is a reasons I like Open Source.

Chunking Conversations
I used context discipline, aka focused agents, and work with short conversations, often starting with a single user prompt. The largest of these JSON files were around 600 KB, with more than 100 lines agent reasoning and tool calling. Reading these large conversations overflowed my context and I had to split them into chunks, preserving lines, using a little Python script. I used a threshold of 60 KB for each chunk which works. Using chunks kept my context limited but the agent did overlook mistakes and their fixes than came much later in the conversation.

An agent loop processed the chunks of each conversation and wrote out an result markdown analysis.md file for each conversation. Here is a part of my Windows Batch script:
for /d %%d in (session_*) do (
  if not exist %%~dpd%%d\analysis.md (
    call vibe -p "Run @%~dp0search_process_improvements_prompt.md for folder %%~dpd%%d"
  )
)
And the prompt (search_process_improvements_prompt.md) contains:
  • Termination condition: If the folder contains an `analysis.md` its analysis is complete. Stop.
  • Context: The given folder contains a conversation between a human and answers from an agent.
  • Input: This conversation is split across smaller files named `chunk_*.jsonl`.
  • Task: Read each chunk and search for things that went wrong and that later got corrected, either by retry or by the user.
  • Output: Format the learnings as a short list suitable for documentation or rule files.
  • Then process the next chunked file, keep appending to `analysis.md` until all chunks are done.
After the agent looped for some time, I got a bunch of individual analysis.md files. A final agent call combined, grouped by issue and sorted the findings by number of occurrences, i.e. more frequent issues came first in the result. As expected from GenAI documents, the output was too much. For my TDD with Agentic AI experiments the analysis of 50 sessions showed around 200 issues in 14 categories:

No.CategoryOccurrences PriorityImpact
1 Line Endings 30+CriticalAgent Tooling
2 Platform Commands 20+CriticalAgent Tooling
3 File Editing Tools25+CriticalAgent Tooling
4 TDD Workflow 15+High Process Skills
5 File/Path Handling15+High Agent Tooling
6 Code Quality 15+High Code/Design Documents
7 String Escaping 10+High ?
8 Testing Practices 10+High Process Skills
9 Git Workflow 10+High Process Skills
10Skill Adherence 10+High ?
11Refactoring 10+High Process Skills
12Tool Usage 10+Medium Agent Tooling
13Error Handling 5+ Medium Code/Design Documents
14Documentation 10+Medium Code/Design Documents

Fixing Agent Tooling Problems
The results covered different topics. Some issues alerted me of tooling problems. At the time I used VIBE v2.9.6, an early version which lacked Windows support. Categories 1, 2, 3, 5 and 12 resulted from that. For example VIBE's search_replace tool struggled with Windows line endings. My source code had a CRLF instead of the expected LF at the end of each line. I changed my workflow to call dos2unix on all source files repeatedly. (Later a VIBE upgrade made this unnecessary. VIBE is actively maintained and delivers a new version at least every week.)

Conversation (licensed CC BY-NC by Todd Petit)Sidebar: Agents vs. Microsoft Windows
VIBE tried to call grep again and again. Some (many?) agents assume a Linux based environment when calling command line tools. Pi coding agent supported only Linux at the time I explored it. At first I did not notice, I use UnxUtils (GNU utilities for Win32) since many years, even long before MSYS2 or WSL were a thing. My Windows is "hybrid" anyway, e.g. I set a %HOME% variable, set HOME=%HOMEDRIVE%%HOMEPATH% which works great for Linux programs compiled for Windows. My batch scripts are a mess too, mixing CMD internals like for, MS-DOS/Windows32 utilities like xcopy, standard Unix-based shell commands like grep and tail and modern versions of my own commandline tool library.

VIBE failed at calling some Linux tool, it retried and got it right, slowing down my workflow. I downloaded VIBE's source code and pointed itself at it to analyse the issue with grep. (That is a reason I like Open Source.) In the end I installed Ripgrep rg to fix the problem, as VIBE calls it first. Now all code searches work, even better Ripgrep is much faster that plain grep. Win!

Fixing Development Process Problems
Categories 4, 8, 9 and 11 concerned the TDD process and how I wanted to use Git in the project. These added to the different agent SKILL.md files I used. While some of the findings were already in the skills - see category 10 - I added most as extra rules to my skills. Here is an example of the improved refactoring rules. I considered them obvious and skipped specifying them in the first place, but past conversation showed that the agent got it wrong and needed more guidance:
  • Use grep to find all usages of a method before refactoring.
  • When refactoring method signatures, update all call sites. Compile frequently.
  • Search for all occurrences of the old method across the entire codebase before committing.
  • When moving code, verify that the original has been removed, not just copied.
  • Remove obsolete files during cleanup.
Fixing Documentation Problems
The rules from the remaining categories 6, 13, 14 were missing in different knowledge documents about the project setup, programming conventions and design guidelines. These were project and language specific rules. Not everything listed was relevant and much was already documented. Still I got some good addition to my harness both the inner and outer ones.

Prompt Injection?
I used the above process on different projects. When there were enough new conversations, I re-ran the whole thing. The loop let my agent churn away for hours in the background. In the end I scanned the resulting document and applied all new rules which looked relevant. I did not care if the analysis missed anything, this was not about correctness, rather a performance improvement. One final problem I noticed was that during some runs the agent forgot its task (to find process improvements) and instead changed the code in the project referenced in the conversation. Snippets of code appeared like a shadow of the past. What a suitable reminder that our new friends? are indeterministic and untrustworthy.

28 September 2026

Finally Fizz Buzz Turing Machine

Now that our GenAI agents are doing all coding, what does remain for geek fun? I do not mean developing side projects or open source, I mean fiddling with code, tweaking it, exploring constructs like Only Exceptions for Flow Control. Such coding activities used to be practice or learning. What is their use now? At least they are entertaining (me). I use the tag Coding Fun to mark ideas of educational entertaining hobby coding.

Back to the Turing Machine
One of these ideas was to create Fizz Buzz on a Turing Machine (abbreviated TM) - you know, the thing with the tape of zeroes and ones. Last summer I created its building blocks, i.e. symbols, Tape, TuringMachine and TransitionTable classes. These parts built an Universal Turing Machine (abbreviated UTM), which ran any concrete TM. On top I added transition tables for the basic structures required by Fizz Bizz, e.g. numbers (encoded as binary) and operations to INC and compare them. Inspired (or biased) by assembly, I unknowingly recreated a Von Neumann architecture where some part of the tape contained the program code, specific symbols for each operation, and another part contained the working memory. Now I had a machine on top of a machine.

valves (licensed CC BY-NC-ND by thepismire)Arithmetic
The best part about "Entertainment Coding" is that you can stop whenever you want. I often stop when I have proven my idea. I pass on filling in all the details. And there are a lot of details to fill in for a Turing complete assembly - which I need for Fizz Bizz. The numbers are encoded as their bits. Moving the data cursor right or left one number needs only a few states and transitions. Increment's (INC) transition table, shown in the previous article, has around 8 lines. Decrement is the same. Comparing two numbers for being less-than or being equal-to needs 28 lines and duplicating a number to the next space on the right has already 34 lines. The number of state transitions grows with the number of cells involved (e.g. Which bit is this?), overflow (e.g. Do I have to add 1 to the bit because of the previous operation?) and number of operands (e.g. Do I have to move right to continue?). Adding or subtracting two numbers is the same flow, with more moving the read-write head and keeping the overflow. It is possible and much work, so skip it.

Flow Control
What about flow control? For Fizz Buzz I need two kinds of flow control:
  1. A conditional to check if a number is equal another number. If they are equal, the following code is run, else the code is skipped. Skipping next instructions is a jump forward towards the end of the "if body", defined by the symbol ';'. (Why use a semicolon? I do not know, probably I did too much Java in my life ;-) Luckily I only need to check if a number is equal to 0, which is much simpler than comparing to an arbitrary number.
  2. For looping - at the end of the loop - I need to check if a number is smaller than another number. This is like point 1 above. Then jump back to the beginning. This is a jump backwards to the start of the "loop body". I need a GOTO and a loop label as target to do this.
This is a minimalist design. It has no else branch, nested conditionals or nested loops. It models the required control flow for Fizz Buzz:
'L' ... start of the loop
   'i' ... current += 1

   'z' ... if (current % 15) == 0 then
      // write "FizzBuzz"
      'g' ... continue
   ';' ... end if

   // similar block for 3
   // similar block for 5

   // write current as string

   '<' ... if current < 100 then
      'g' ... continue
   ';' ... end if

'h' ... halt program
Because I miss else the body of each if must end the loop prematurely - in some programming languages called continue. Thus the last if checks the loop exit, i.e. the upper limit, e.g. 100. The last number must not be Fizz nor Buzz nor FizzBuzz.

Time for some low level details: Here is the transition table of GOTO:

Step state symbolnewStatenewSymboldirection
(1) Ip_SwitchRight 'g'Ip_Goto same L
(2) Ip_Goto 'P'same same L
(3) Ip_Goto 'h' Ip_GotoRightHalt'P'R
 Ip_GotoRightHalt'P'Ip_Goto 'h' L
 Ip_Goto 'd'Ip_GotoRightDup'P' R
 Ip_GotoRightDup 'P'Ip_Goto 'd' L
 Ip_Goto 'i'Ip_GotoRightInc'P' R
 Ip_GotoRightInc 'P'Ip_Goto 'i' L
 Ip_Goto 'r'Ip_GotoRightRightMove'P'R
 Ip_GotoRightRightMove'P'Ip_Goto'r' L
 Ip_Goto 'l'Ip_GotoRightLeftMove'P'R
 Ip_GotoRightLeftMove'P'Ip_Goto'l' L
 Ip_Goto '='Ip_GotoRightEqual'P'R
 Ip_GotoRightEqual'P'Ip_Goto '=' L
 Ip_Goto '<'Ip_GotoRightLess'P'R
 Ip_GotoRightLess'P'Ip_Goto '<' L
 Ip_Goto ';'Ip_GotoRightEqualEnd'P'R
 Ip_GotoRightEqualEnd'P'Ip_Goto';' L
(4) Ip_Goto 'L'Ip_Restart same R

Transition (1) begins the GOTO states. Transition (2) starts moving left and skips the instruction pointer. Transition (3) moves the instruction pointer along each and every skipped instruction. Whenever I add a new instruction I have to update conditional and loop code, which is boring. (4) Goto's state transitions finish when it sees the symbol 'L'. Then the instruction process restarts with state Ip_Restart by looking at the next instruction right of the instruction pointer.

The Whole "Language"
Till now I created the following symbols:

symbol memory meaning
'0'/'1'data a bit of a number.
'$' data separator of a number or memory slot - a "byte" if you like.
'C' data data Cursor marking the current number on its right.
'P' code instruction Pointer left of the next instruction.
'h' instructionhalt, stop the TM.
'l'/'r'instructionmove the cursor one number to the left or right.
'i' instructionincrement the current number by one and move cursor right.
'e' instructiondecrement the current number.
'd' instructionduplicate current number to the right.
'3' instructionwrite the digits of 3 into the current number.
'<' instructionjump to end of block if current is not < next number.
'=' instructionjump to end of block if current is not = next number.
'z' instructionjump to end of block if current number is not 0.
';' label mark the end of the (conditional) block.
'g' instructionjump backwards (moving 'P' left) until the label 'L'.
'L' label Loop label for goto (backwards) jump.

Apples in tarpits (licensed CC BY-NC-ND by Pay No Mind)Instruction '3' is special, as would be '5' and 15. Data values are on the tape and copied around. It might save me some hassle if I can write arbitrary numbers programmatically. Then d3ll%lz...;lll would be the code to check for multiplies of 3 - if I had '%'. All my programs (till now) will match the regular expression P[hdierl3=<z;gL]+C([01]{7}\\$)*.

I need modulo ('%'), which extends subtraction (which extends decrement). Modulo is hard, too complicated for me to write it as state transitions. I could write a macro, i.e. separate code that gets executed whenever the UTM reads a '%'. This would be like Microcode of modern CPUs. Or I could create subroutines. If I avoid nesting them, a single instruction pointer symbol, e.g. 'R', as return address would be sufficient. For example, when the UTM reads 's', it writes the 'R' instead of the 'P'. Then it searches right for 'S' which is the label to start the subroutine and executes until it reads 'r' for return. On 'r' the instruction pointer goes back to 'R'. Four new symbol 'srSR' (2 instructions, 1 label, 1 pointer). Regular program flow can never see 'S' or 'R' and I omit adding them to if or goto. The 's' might be inside a loop or conditional. The 's' and 'r' are gotos looking in specific directions for specific labels, nothing conceptionally new.

The "Actual" Program
I have enough of this. This is a Turing Tarpit, a (esoteric) programming language that is universal but impractical and difficult because it offers no support for common tasks. [...] Using such a language is a form of mathematical recreation. Yes I can finish Fizz Buzz, but it is no fun. To conclude, here is my final piece of code to create the numbers from 1 to 16 on the tape:
P
Lrdllldlil<lg;   // loop creating numbers
i                // fix last element
llllllllllllllll // go back all = "l" * limit
hC
0000001$         // from 1
0001111$         // to limit - 1
I hope you had fun following me on my quest. The whole TM, UTM and transition logic is on my Git. I now appreciate how high level assembly is.

15 September 2026

My Writing and GenAI

I follow my plan of focusing on fewer tasks. This puts a lot of pressure on my time. In addition I spent almost every evening of the last months exploring GenAI. My wife got sick of me talking about agents, tokens and the like. Besides my feelings about the change of our industry I did not write much. Having little time and less practise in writing made writing more unlikely - a vicious cycle. I had no idea where putting my thoughts would end up. It might become a rant. (Sidebar 1)

The Giant Bible of Mainz (licensed CC BY by Karen Neoh)Working With Text
What to look for? I use writing to structure my thoughts. This is rubber ducking, a practise of talking through a problem. In doing so, your brain structures the problem as part of communication. This often lets us find the solution to the problem. I learnt about this technique from The Pragmatic Programmers, a book I recommend since 2011. The idea itself is way older and based on Joseph Weizenbaum's ELIZA from 1966. (You can try ELIZA here.)

More than once the outcome of my writing was different than I had expected or planned. I partitioned and analysed the problem during writing and found better results. This is the benefit. I lose if AI writes the text for me. It will format my notes nicely and present something that looks reasonable but it will not end with opposing results. And even if it would, I would reject them because I am unprepared for opposing results. I need to go through the work of structure and analysis to find and accept a different outcome than I had anticipated. My writing needs to be slow and meandering and cumbersome.

When writing about technical topics, e.g. the latest Coding Fun, I have to structure the material linearly to make it possible to read for people who are unfamiliar with what I want to present. This makes me reflect on the topic from a distance, after I had been in the fine details all the time. This summary adds to my understanding of the material.

On LinkedIn is a group of people who claim that they put as much thought and effort into their AI generated articles - which would also mean they get the same benefits. I do not know, maybe they do. But Mathias Verraes disagrees. He claims to recognise AI-generated text because he read so much. The generated text contains the same cliches and seems to be uniform - for sure statistically averaged. These articles are boring which makes them unreadable. (Sidebar 2)

I do not write enough and miss practice. Getting started is difficult, collecting ideas takes time and I edit everything more than once. I guess Mathias will resent my writing. ;-) I struggle with articulation as English is not my first language. I could use GenAI to improve my articulation - it would keep my ideas and thoughts, at least according to the proponents of GenAI. But I reject it. I want to improve my articulation myself. Articulation is a skill, writing is a skill, and both need practise. (Sidebar 3)

I like writing by hand, or should I call it writing manually: I am creating something and showing the world. Using GenAI for my writing removes all these benefits: I am not structuring, expressing, and polishing my thoughts. I am not summarising known material. And I am not practising and improving my writing. Dylan Beattie phrased it in his GeeCON 2026 keynote: "If something is fun and you're learning - using AI brakes both."

What Makes A Person?
Another goal of my writing is to share my knowledge. Other than expressing myself, sharing is a marketing tool, at least part of developer branding. As GenAI disturbs my beloved coding, I need to rethink my business. What makes me successful since 15 years? Besides my technical expertise I believe I am successful because I am authentic. I teach what I know and have experience from past projects and always state up front when I have no clue. (Sidebar 4) I avoid marketing buzz words and stay away from promising anything. I demand perfection from others and even more from myself. I live what I preach. I have no idea what my clients buy when they hire me for the first time (when they do not know me yet). I believe they buy the promise of my reputation. All my work comes through personal recommendations. (Thank you so much my friends.) For sure a large part of my business depends on my contacts and personal, authentic connections. Being honest, admitting mistakes and taking responsibility for my actions are important to me. No generated text, regardless how well structured and nicely sounding, supports those.

News block (licensed CC BY-SA by Loco Steve)Generated Correspondence
In the early days of Chat-GPT I ran an inhouse Coderetreat for one of my clients. A local organiser sent an invitation to all developers. Instead of writing one or two sentences about the upcoming event, he generated a full page of text about being "delighted" to host such a "spectacular" event and more exaggerated terms. This is a common problem. Me friend Raimo writes about interacting with coworkers talking to us only through parrots which makes him frustrated or angry at times. I fail to understand why people would do that. (Sidebar 5) Particular in an corporate environment, nobody cares for style or typos in work emails. As time is money, long emails and chat messages are discouraged. The respect for our coworkers' time should stop us from creating (large amounts of) useless text. Please never send me AI generated text. I will never use AI for mails or personal messages.

I am a geek, spending my evenings alone, in a dark room filled with hardware and pizza boxes - at least kind of. And at the same time I like working with people. I value human connection. It makes much of my work meaningful and worthwhile. Human beings are social, everybody needs human connection somehow. To connect I need to express my feelings (like about accepting GenAI) and I want to be seen. AI is unable to express my feelings and it certainly can not make me seen. Connection is not happening if I do not expose myself.

My AI Writing Manifesto
After collecting notes and thoughts since May this year, structuring my thoughts and polishing then, I found clarity:
  • I structure and formulate my thoughts and ideas myself. AI does not support me in digesting and distilling content.
  • I summarise technical expertise myself. AI does not support me in finding deeper relations based on known material.
  • I author and polish my writing myself. AI does not support me in practising and improving my writing skill.
  • I keep a honest and authentic relation to my clients and peers. AI is neither.
  • I respect your time and keep all messages short. AI generates bloat.
  • I write all messages myself to express my feelings and to be seen. AI hides me.
  • All images I use are real images, unless marked as AI generated.


Footer
I was massively distracted while writing. I kept finding notes from the last five months on different aspects of this. The topic had been on my mind for some time. After finishing the outline I streamlined the text and moved my secondary thoughts into this section. While off-topic these thoughts were reasonable - I might expand on them later.

1) Blog Rants: I have not written any rant since I went independent. This is a good thing. I do not miss the corporate politics and hidden agendas.

2) Hate of Generated Text: In my social "bubble", there is a crusade against AI generated text. I can relate. The massive creation of AI slop is speeding up the Enshittification of the Internet. For example: This January I suffered from pneumonia. Staying in bed I searched the web for articles comparing AC generators. I planned to buy one powering tools in the garden. The web search showed promising results. But each page turned out to contain generated text of products with deep links into Amazon, and no real descriptions nor any comparison. Maybe due my weakened state, I was devastated. I recognised that the Internet was broken. That was not the web I had learnt to trust for its usefulness.

3) Practice and Mastery: I am a big fan of deliberate practise. I practice deliberately since many years and have talked about it in the past. I use that approach for all areas which I care for and where I want to improve. I want to achieve mastery (as a path not a state). Maybe this is folly: I am in a position of privilege which allows me to reflect on my skills and put aside time to practise, which is like play, unproductive. I am able to laugh about failed attempts and try again. I like the experience of the flow you get after reaching a certain level of skill. Having invested huge amounts of time into practise makes me respect the effort and skills of other people. Coming back to AI writing - I am unable to respect neither the author nor the work using AI because there is little effort and skill required.

4) Working with technologies I do not know is an interesting situation as a coach. I always confess in the first meeting with the client when I have no experience with certain technologies they are using. 12 years ago, I worked with a company using PHP. Back then, they used PHP 5, which had a bad reputation. I had never seen any PHP before. I struggled a lot with its dereference operator -> and always used the more common . instead. When pair programming I always mistyped it and one of my pairing partners designed a T-shirt for me saying "this -> is not this .". In the end I knew more about PHP than most developers I paired with because I knew what to expect from a language and how to google it. Another time I worked with C# which I had never touched before. That was even easier, as at the time, C# was "Java in Pascal case". ;-) After learning some programming languages, at least the main stream ones, all languages look the same.

5) Why generate bloated text? I am wondering which universal human need is met when people generate work emails with GenAI, making them many times larger than necessary. It is not efficiency, as the prompt takes longer than the pure message. It is not reputation, as everybody recognises the generated text. (Ha ha sequences of "it is not" are a sign of AI generated text. Fear not dear reader, I am able to author bad writing without any AI any day. ;-) People generate content for Wikipedia - which is vandalism and go on when asked about it. Which need is met by these actions? I will have to investigate. The best I know is "because I can" which is self-efficacy, an important need indeed.

21 April 2026

Accepting GenAI

Grief (licensed CC BY-NC-ND by Kerri Polizzi)My Blacklist of Technologies
When I started out as a Java developer, I wanted to know everything about Java. I wanted to know all libraries and all frameworks. What a silly idea. Clearly Java or software development in general was and still is way too vast to know everything. Beginning 2003, I started ignoring certain technologies. I maintained a black list of topics and libraries, e.g. I decided to ignore all Java web frameworks. Later I ignored EJBs and then I added the whole Spring ecosystem to this list. While I knew these things existed and I had a working knowledge for my day job, I would refuse to study them in my personal free time. There was nothing wrong with these technologies. I did not find them interesting. Using that approach, I successfully skipped all the rage about SOA and other hypes, and I am not looking back. ;-) Explicitly ignoring topics helped me to focus on the things which I liked and considered important.

Scary or Awesome or What
And then ChatGPT came out. (The Wikipedia link is probably unnecessary.) There was an extreme buzz around it, and because of that I wanted to ignore it. A few months later I worked with a group of interns at one of my clients. These young people were enthusiastic about AI - most of them paid for pro versions from their own money - and they encouraged me to look into it. And so I did. And I got frightened. I enjoyed every post that diminished LLMs as stochastic parrots. Let's face it, isn't it weird when a machine can have a conversation with you? I am full of awe, also in a scared way - I am unsure what the right word is to describe my feeling.

Since last year, all of my clients ask for workshops to improve their coding with the use of AI. Code assistants and agents - augmented coding - get better and better. And sometimes the results are surprising. In the end, it is the same if AI works for coding or not - the industry has already decided on its adoption. For some time, I tried to deny it. But after Dave Farley's study about developers using AI, there was more denying it. I had to accept that AI will take over coding. (Dave Farley's video is 12 minutes, without hype, and in the end he gives a clear direction to follow. You should watch it.)

Fear of Obsolescence
Software development is changing quickly, and many of our skills become worthless (says Kent Beck). I read somewhere that "every technological revolution has displaced skills that people spent years mastering" and that "the people that are really skilled, have a lot of room to fall." (says Bryan Seegmiller). Yes, I feel like that. Coding is more than my work (and my fun), it is my identity. I have been playing with code since more than 40 years now. During this time, I have even established habits to use coding for relaxation, and I like exploring topics around code. I do not mean development, I particularly mean coding. I am the Code Cop and I am obsessed with manipulating the textual structure, improving its readability, exploring symmetries, tweaking it, moving it around like clay, and so on. And now all this is going away and it is scaring the hell out of me.

How am I dealing with all of this?
A senior developer from one of my clients, struggling with AI adoption himself, asked me how I am dealing with all of this? I am not, or at least not well. I thought about moving into areas where AI is useless and uncommon (yet?). For example, a study showed that AI is less effective on COBOL and other legacy code. Lovely! I bought a bunch of COBOL courses, and planned to take them. I had several other ideas, too, none of them really helped me till now. The core goal of this post was to list a few resources which really helped me:
  • Maybe the first step is accepting the use of GenAI.

  • I highly recommend this podcast with Grady Booch about the third golden age of software engineering. Grady Booch's approach is historical and more systemic. He is calm, with good perspective. It is 80 minutes long, audio-only is enough. This is the first piece that helped me to a more positive attitude.

  • Kent Beck, who probably lost more to the rise of augmented coding than anybody, is lovely. In his conversation with Trisha Gee about Skills Developers Need to Have in an AI Future, they talk about developers losing confidence that they will be able to learn the next set of necessary skills. How true.

  • Grief - A statue in Oslo. in the rain (licensed CC BY by Todd Huffman)Embrace Change is the second principle of the Agile Manifesto. While I try to stay clear of processes and am okay whether we use waterfall or Scrum or whatever, I do care about the code, and I favour Embracing Change there, designing in a way that would allow changes. Keeping software soft. Recently I was reminded of that fact by a fellow technical coach. So let's embrace change, even if it is frightening right now.

  • Last month Kent Beck started a new podcast Still Burning where he has honest conversation about what it actually feels like to work in this moment - the fear, the uncertainty, the quiet disorientation of tools changing faster than understanding can follow.. The acknowledgement of these feelings, the disorientation, this is balm for my soul. I have always admired Kent Beck and the podcast setup is so grounded (actual fire, real smoke, Kent is coughing) and humble, it is already a classic.
What Next
These discussions helped me, and I hope they will help you, too. Am I done? I stay critical of using AI, its effects on me, my skills and the world in general. At the same time I try to board the AI train and follow along with the current. There are plenty opportunities to participate in AI experiments right now. Hopefully that will be enough to stay on the topic. My fear of missing out is real, I spend too much time with Generative AI. My wife already urges me to take a break from all this. It is exhausting. Everywhere it is just "AI", "AI", "AI".

19 November 2025

Getting Started with Refactoring

At this year's Global Day of Coderetreat (GDCR2025) our guest facilitator Ivett decided to ban AI tools. The result was a classic Coderetreat, like in the old days. It struck me in the retrospective that some participants said that they were unable to code by hand any more. They had a hard time working without their agents, and some ignored the constraint and kept using AI throughout the day. This is my empirical evidence that we lose the ability to code. (There is more evidence, recently by Anthropic how AI assistance (negatively) impacts the formation of coding skills.) Coding is dead anyway. Future "AI" developers might need more skills of the product owner, the architect, and the tech lead role. This is bad luck for junior developers, when they enter the market, as they are no tech leads (yet). Recognising that, a participant of the Coderetreat asked me how to learn (more) about refactoring. I believe that the basics are still important and share my answer here so it might benefit more.

win hill pike (licensed CC BY-NC-SA by Johnson Cameraface)Exercises and Books on Refactoring
Simon asked: "Do you know and can recommend any good exercises or books on refactoring." Certainly.
  1. To get started, I recommend the book Refactoring by Martin Fowler. Martin published a 2nd Edition using JavaScript examples and the original edition is for Java, depending on what suits you better. Refactoring has two parts: Code smells and refactoring techniques to handle them. Both are described in Fowler's book and also on his website. Refactoring Guru is also good in explaining code smells and their matching refactorings. Go study these.

  2. As for exercises - there are refactoring code katas. Emily Bache has many code katas available, including Gilded Rose, where the Readme often explains which specific skill the particular kata lets you practice. I maintain a small list of exercises here. Refactoring is a practical skill, which means you need to exercise it repeatedly, sometimes following the same steps. This is practice, and repetition is what makes it stick. Today, when using AI, you might skip the manual steps of refactorings at work, but you need to work the practical skill to master it.

  3. The third pillar of fluent refactoring is using IDE shortcuts. (Or maybe refactoring workflows or skill files, who knows.) You should investigate the IDE you use most often, whether it is IntelliJ IDEA, Eclipse, Visual Studio Code, etc. Figure out which refactorings are supported - maybe install plugins - and practice refactoring using the keyboard. Refactoring becomes powerful when you know the shortcuts, because that is where speed comes from and you are no longer distracted by mechanics. I collected flashcards to learn the shortcuts and a quick search dialogue for finding shortcuts.
If you prefer videos, Dave Farley shared a list of free learning resources about building refactoring skill, confidence, and shared language, including Emily Bache's guide to core refactorings and practical tutorials which you can work through.

Using C# and NUnit
You mention using C# with NUnit. The Java refactorings in the first edition of Fowler's book transfer directly to C#. When working in C#, ReSharper or JetBrains Rider are useful, they provide more refactoring menus than vanilla Microsoft Visual Studio. NUnit is like Java's JUnit 4, any older book with Java examples will map well. There is also a special edition of the Refactoring book for Ruby. Most techniques are language agnostic.

Learning Tips
I strongly recommend starting with simple code smells, i.e. the group of Bloaters and then the Couplers. Practise basic refactorings such as Extract Method, Extract Local Variable, etc. Most IDEs support them and they build a solid foundation. Keep it small in the beginning. There is no point changing complicated code when you lack the basics. You could repeat the same exercise more times and try different approaches. You can always make exercise harder - and people take too large steps in the beginning. Instead make the exercises easier and take smaller steps.

Try to find a learning partner. Studying any material and discussing it with someone else is awesome for learning. Verbalising learned materials makes it stick. Discussing it with someone else helps you make new connections between the material. Practising refactoring in pair programming, like working during a Coderetreat, is powerful. I used to meet people in coffee shops or online and we would refactor code together.

15 September 2025

Von Neumann Turing Machine

On my search for harder coding challenges, join me implementing Fizz Buzz using a Turing machine where I dive into Turing machines from a practical coding perspective using Java. In the previous part I finally understood Turing machines (TM) and created a Universal Turing Machine (UTM) using a Tape and TuringMachine classes. This is the second part.

Fizz Buzz
I want to implement Fizz Buzz but I have no idea how to start. A simple implementation in Java might be:
for (i = 1; i <= 100; i++) { // line 1
  if (i % 3*5 == 0)
    print("FizzBuzz");
  else if (i % 3 == 0)
    print("Fizz");
  else if (i % 5 == 0)
    print("Buzz");
  else
    print(i);
}
Fizz Buzz is an easy problem, still it needs several programming constructs: Looping or sequences, conditional logic, arithmetic with integers including division for the remainder, strings and some form of input and output. The input is the number of lines required, in the code above hardcoded to 100, and the display showing the result, e.g.
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
What is the end state when I miss a display? For a TM the input will be the number on the tape and the output will be the list of strings on the tape again.

MM Numbers (licensed CC BY-NC-ND by Michele C)Representing Numbers
I am overwhelmed. When working katas, exercises or new languages, I usually create the code bottom up, making things up on my way. Following that approach, I have to figure out individual operations first, then will I combine them into more powerful programs. For Fizz Buzz I first need to count from one to 100, incrementing by one. The smallest (binary) space to represent the number 100 needs seven bits which are seven cells on the tape containing a '0' or '1' followed by a separator '$', e.g. 100 would be 1100100$ on the tape. (To make my life easier, I assume the set of symbols contains arbitrary characters. After all each character is a sequence on bits anyway.) The separator helps because it avoids keeping track of positions inside the sequence of working with bits during some operations. (This is one of many design options. Another approach would be to store the position of each bit next to the bit on the tape.)

Incrementing Numbers
The first operation I need is INC (increment by 1). Increment, an x86 assembly op-code, adds 1 to an unsigned integer operand. (Now - when writing this - I see why I ended up where I ended up. My first idea for a building block was a CPU assembly operation on a sequence of bits. From there I was following the given direction...) If you never did any assembly, let me explain INC operating on a binary numbers. Let's assume a value, e.g. 78, binary 1001110. The increment adds 1,
01001110
+      1
--------
 1001111
Like adding regular (Arabic base 10) numbers, addition starts most left. The 1 adds to the 0 and we are done. In short, if there is a '0' bit, it becomes a '1' and that's it. So 78 becomes 79. Let's increment it again:
01001111
+      1
--------
 1001110
+     1  ... overflow from the first digit
--------
 1001100
+    1   ... overflow from the second digit and so on
--------
 1010000
which is 80. In short, if there is a '1' bit, it becomes a '0' and INC continues incrementing left with the overflow.

INC on the UTM
Working on the tape of the TM, the algorithm to increment the number right of the read/write head is:
  1. Move the read/write head right until the end of the number (i.e. until the '$') to do the increment.
  2. Work backwards, i.e. move left to increment.
  3. If there is a '0', then write a '1' which finishes increment - and start moving right to the end.
  4. If there is a '1', then write a '0' and continue incrementing left with the overflow bit.
  5. In the end move right until the '$' to leave the read/write head in a consistent state.
The last bit must not overflow. Increment's transition table is

Step state symbolnewStatenewSymboldirection
(1) Inc anyInc_MoveRightAndIncsameR
 Inc_MoveRightAndInc'0'Inc_MoveRightAndIncsameR
 Inc_MoveRightAndInc'1'Inc_MoveRightAndIncsameR
(2) Inc_MoveRightAndInc'$'Inc_IncToTheLeft sameL
(3) Inc_IncToTheLeft '0'Inc_DoneMoveRight '1' none
(4) Inc_IncToTheLeft '1'Inc_IncToTheLeft '0' L
(5) Inc_DoneMoveRight '0'Inc_DoneMoveRight sameR
 Inc_DoneMoveRight '1'Inc_DoneMoveRight sameR
(T) Inc_DoneMoveRight '$'Halt samenone

This table is a standalone test program a.k.a. a Turing machine. Line (T) stops after incrementing a given number. I can unit test the code comparing tapes, e.g.
@Test
void incZero() {
  transitions.addIncTo(table);
  createMachineWith("0000000$", Q.Inc, table);
  machine.loop();
  assertTapeEquals("0000001$");
}

@Test
void incOne() {
  transitions.addIncTo(table);
  createMachineWith("0000001$", Q.Inc, table);
  machine.loop();
  assertTapeEquals("0000010$");
}

@Test
void incToMax() {
  transitions.addIncTo(table);
  createMachineWith("0111111$", Q.Inc, table);
  machine.loop();
  assertTapeEquals("1000000$");
}
DEC (Decrement by 1) is the same with '0' and '1' switched. Now I know how to build individual operations.

More Operations
Next operation is DUP (duplicate a number). Things get cumbersome because the state of the current bit, i.e. if DUP is copying '0', '1' or '$' eight places to the right has to be encoded in the states. For example the transition table to duplicate a '0' is

state symbolnewState newSymboldirection
Dup '0'Dup_Move7RightAndWrite0 sameR
Dup_Move7RightAndWrite0anyDup_Move6RightAndWrite0 sameR
Dup_Move6RightAndWrite0anyDup_Move5RightAndWrite0 sameR
Dup_Move5RightAndWrite0anyDup_Move4RightAndWrite0 sameR
Dup_Move4RightAndWrite0anyDup_Move3RightAndWrite0 sameR
Dup_Move3RightAndWrite0anyDup_Move2RightAndWrite0 sameR
Dup_Move2RightAndWrite0anyDup_Move1RightAndWrite0 sameR
Dup_Move1RightAndWrite0anyDup_Write0AndMove7Back sameR
Dup_Write0AndMove7Back anyDup_Move7LeftAndStartAgain'0' none

There are 9 state transitions for each "bit" - to "remember" the bit - and additional 7 states to move left again and start over, giving a total of 34 states for my simplified transition table allowing shortcuts for any symbol etc.

I am still implementing line 1 in the code on top of the page:,Counting from one to 100, incrementing by one. To create a loop, I need to start with one (0000001$), duplicate it, increment the new number, and repeat while it is less than 100 or until it is 100. The instructions LESS and EQUAL are similar to DUP. The current symbol has to be "remembered" in the states, the tape has to move eight places right and the comparison with the symbol there determines the result of the operation, then the tape has to move seven places left again and restart the operation.

Dusty Bottle Neck (licensed CC BY-NC-ND by caramand)Combining Operations
I started with x86 operations and I follow the idea further. I dislike duplicating INC or other states so I create a lookup table - an area on the tape that would be holding the program, think Code segment from x86 architecture before x86-64. The read/write head will have to move between the code and the data (think Data segment) and I need markers for both positions. Let 'P' be the Instruction Pointer (usually called IP) and 'C' be a cursor marking the last position the read/write head had when working with data. Each operation will
  1. Move the instruction pointer to the next instruction by switching the letter of the operation with 'P'.
  2. Move the read/write head right to the cursor 'C'. There replace the cursor with the separator '$'.
  3. Perform the operation. Each operation must end with the read/write head positioned at a separator.
  4. Set the new cursor position.
  5. Move the read/write head back to the instruction pointer
  6. and start over.
Storing the program and the data in the same place, i.e. the tape, makes this a Von Neumann architecture. When the UTM is processing instructions in the left side of the tape, it cannot work with data, which is on the right side of the data and vice versa. The term "von Neumann architecture" refers to any stored-program computer in which an instruction fetch and a data operation cannot occur at the same time (since they share a common bus) says Wikipedia.

INC as Instruction
Increment's extended, full transition table is

Step state symbolnewState newSymboldirection
(1) Ip_SwitchRight 'i'Ip_SwitchLeftInc 'P' L
 Ip_SwitchLeftInc 'P'Code_Inc 'i' none
(2) Code_Inc 'C'Inc '$' R
 Code_Inc anysame sameR
(3) Inc anyInc_MoveRightAndIncsameR
 Inc_MoveRightAndInc'0'Inc_MoveRightAndIncsameR
 Inc_MoveRightAndInc'1'Inc_MoveRightAndIncsameR
 Inc_MoveRightAndInc'$'Inc_IncToTheLeft sameL
 Inc_IncToTheLeft '0'DoneMoveRight '1' none
 Inc_IncToTheLeft '1'Inc_IncToTheLeft '0' L
 DoneMoveRight '0'DoneMoveRight sameR
 DoneMoveRight '1'DoneMoveRight sameR
(4) DoneMoveRight '$'Ip_Restart 'C' none
(6) Ip_Restart 'P'Ip_SwitchRight sameR
(5) Ip_Restart anysame sameL

and its test
@Test
void inc() {
  createMachineWith("PihC0000000$", Q.Ip_Restart, transitions.create());
  machine.loop();
  assertTapeEquals("ihP$0000001C");
}
Letters 'i' and 'h' represent operations INC and HALT. After execution the instruction pointer moved two places to the right and the data cursor moved one number entry to the right.

Other Instructions
The extension of the partial transition tables of DUP, LESS, EQUAL and operations to move the cursor left and right as instructions 'd', '<', '=', 'l' and 'r' is the same. States DoneMoveRight and Ip_Restart are generic and used by most of these instructions. See the full transition table here.

This concludes the second part of my Turing Machine exploration. I spent too much time formatting transition tables. Now I have a machine on top of a machine. I made the problem easier by adding another level of indirection, an application of the Fundamental theorem of software engineering. ;-) Stay tuned for part three.

5 August 2025

Universal Turing Machine

Turing Machine in Bletchley Park (licensed CC BY-NC-ND by Douglas Hoyt)The more I practice, the more I explore extreme situations. I have tried to go faster. Other times I Programmed with Nothing. Maybe it is the difficulty of only using low level constructs that makes this group of coding constraints appealing to me - which makes coding in assembly still interesting to some people, too. Then I tried to create Fizz Buzz using a Turing machine. I guess I lacked the purity of Computer Science university exercises. I will dive into Turing machines from a practical coding perspective using Java here.

Turing Machine
What is a Turing machine (TM)? First the TM is a though experiment. It was not meant to be practical. It is "the thing with the tape where a read-write head is able to read a zero or a one, write a zero or a one, erase the value, and move left or right." It is supposed to be Turing complete, which means it is equivalent to all programming languages today. That was my understanding of a TM when I started. But that understanding was impractical. Is a TM a program or a set of programs or a programming language? How can it be a specific program and Turing complete at the same time? And how could I implement anything like that?

Basic (Java) Building Blocks
First I need the building blocks. There is a set of symbols, maybe only 0 or 1 (a bit) or maybe a character to make things easier. So an empty marker interface Symbol should do. (The interface is optional, I like to make the symbol different from plain Object. I could use a char as well.) Then there is the tape which can be read and written to. The Tape class represents the tape as a data structure, such as an array or a list. Each cell of the tape holds a symbol.
class Tape<SYM extends Symbol> {

  private Map<Integer, SYM> cells = new TreeMap<>();
  private SYM defaultSymbol;
  private int headPosition = 0;

  Tape(List<SYM> symbols, SYM defaultValue) {
    for (int i = 0; i < symbols.size(); i++) {
      this.cells.put(i, symbols.get(i));
    }
    this.defaultSymbol = defaultValue;
  }

  SYM read() {
    return cells.getOrDefault(headPosition, defaultSymbol);
  }

  void write(SYM symbol) {
    cells.put(headPosition, symbol);
  }

  void moveHead(Direction direction) {
    switch (direction) {
    case LEFT:
      headPosition--;
      break;
    case NONE:
      break;
    case RIGHT:
      headPosition++;
      break;
    default:
      throw new IllegalArgumentException(direction.name());
    }
  }
}
The tape could be infinite, and I chose a Map for each symbol by its position. The default symbol is used for tape positions that have not been written to. The constructor accepts the initial content of the tape as the starting state of the machine. Now to the Turing machine:
class TuringMachine<SYM extends Symbol> {

  private Tape<SYM> tape;
  private State state;

  TuringMachine(Tape<SYM> tape, State initialState) {
    this.tape = tape;
    this.state = initialState;
  }

  private void setState(State state) {
    this.state = state;
  }

  private SYM read() {
    return tape.read();
  }

  private void write(SYM symbol) {
    tape.write(symbol);
  }

  private void move(Direction direction) {
    tape.moveHead(direction);
  }

  void loop() {
    while (!state.isTerminal()) {
      act();
    }
  }

  // ...
Following the description of a Turing machine, it has a state which can change. It can read the symbol currently present on the tape at the position of its read/write head. It can write a new symbol on the tape at the position of its read/write head, replacing the symbol that was previously there. And it can move its read/write head one position to the left or right along the tape. The machine runs as long as its state is not final. In each step (method act shown below) the machine reads the symbol present in the tape's cell, and based on the current state and the read symbol, it determines the next state and the symbol to write on the tape, then it moves the head left or right by one cell.
class TuringMachine<SYM extends Symbol> {

  // ...

  private void act() {
    SYM symbol = read();

    // transition to nextState determines
    // symbolToWrite and directionToMove

    setState(nextState);
    write(symbolToWrite);
    move(directionToMove);
  }

}
Of course this was not my initial code. I reached it by refactoring, cleaning up and structuring the code again and again. If this is a Turing machine, where is the actual program? The Tape and TuringMachine classes form a Universal Turing Machine (UTM). The UTM can simulate the behaviour of any Turing machine. It takes the description of an arbitrary Turing machine as input and mimics its operation on a given input string. Aha! My infrastructure can run an arbitrary Turing machine which makes each TM an individual program and the UTM the interpreter. Maybe I should have read the whole article on Wikipedia first.

Turing machine (licensed CC BY by Maria Keays)State Transitions
The actual program of a Turing machine is the set of its states and possible state transitions. It is a state machine, i.e. a graph of state nodes, and each edge between two states contains additional data: The Symbol symbolToWrite and the Direction directionToMove. In text, the easiest way to define this state machine is with a transition table of State state, Symbol symbol, State newState, Symbol newSymbol, Direction direction which is a TransitionTableRow in my TransitionTable implementation. (The whole transition logic is too much code to show here, the working solution is on my Git.) As I will create many transitions, I add defaults to the tables, e.g. state == null applies to all states, symbol == null applies to all symbols and newState == null or newSymbol == null does not change the current state or symbol. I want to avoid defining more table rows than strictly necessary.

A Simple Example
Now is the perfect time for an example. We want to set all bits of a binary number, e.g. 011010. The symbols are the bits 0 and 1 and a marker for the end of the input,
enum Bit implements Symbol {
  _0, _1, END_OF_TAPE
}
Starting at the left-most / highest bit. The transitions are
  • If the machine is running and the current bit is 0, then keep running, write a 1 and move right.
  • If the machine is running and the current bit is 1, then keep running, write a 1 and move right.
  • If the machine is running and the input has ended, then stop running (halt).
This is a simple machine and there are only two states: running and stopped,
enum S implements State {
  RUNNING, HALT;

  @Override
  public boolean isTerminal() { return this == HALT; }
}
and the whole things runs in this test,
class SimpleExampleTest {

  @Test
  void replaces0With1() {
    S initialState = S.RUNNING;
    var _011010 = Arrays.asList(_0, _1, _1, _0, _1, _0, END_OF_TAPE);
    var tape = new Tape<>(_011010, END_OF_TAPE);

    TransitionTable transitions = new TransitionTable().
        row(S.RUNNING, _0, null, _1, Direction.RIGHT).
        row(S.RUNNING, _1, null, null, Direction.RIGHT).
        row(S.RUNNING, END_OF_TAPE, S.HALT, null, Direction.NONE);

    var machine = new TuringMachine<>(tape, transitions, initialState);

    machine.loop();

    var expected_111111 = Arrays.asList(_1, _1, _1, _1, _1, _1, END_OF_TAPE);
    var actualResult = tape.getCells();
    assertEquals(expected_111111, actualResult);
  }
}
Now I know what a Turing machine is and how it is supposed to work. Using the Constructive Approach I created an UTM (TuringMachine.java) and an instance of a TM (in SimpleExampleTest.java). Now I can play around and see what is possible using only state transitions... I encourage you to do the same, clone my fizzbuzz-turing-machine repository and play around with the code in the universal package. This concludes the first part - the foundation if you like - of me implementing Fizz Buzz using a Turing machine. Continue with part 2.

7 July 2025

Only Exceptions for Control Flow

Where It Started
At technical unconferences I like to start (and conclude) the day with some fun coding. After all, writing code is (still, in June 2025,) at the heart of software development. During SoCraTes Linz 2024 I proposed the first session to be a "Coding Fun session: Only use exceptions for control flow." I explained that it would be impractical but fun ;-) Using exceptions like that was an anti pattern but I wanted to see what would be possible.

Coding Fun: Only Exceptions for Control Flow
I start the session with a few slides: Control flow is is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. And the idea of the session is to only use exceptions for changing the control flow. This is a constraint, an artificial addition to a coding exercise, to make it more focused or challenging. To force us to use exceptions for control flow I need to take away all other options:
  • Not using if, while or for, the ternary operator or similar language constructs. (This is the same as the constraint Cyclomatic Complexity One.)
  • Not using any array or (Java) stream operations like map, filter, etc. (These functions are a way to deal with Cyclomatic Complexity One.)
  • Not using lookup arrays of functions. For example a map with the keys true and false and functions as values is an if-else statement. (These lookups are another way to deal with Cyclomatic Complexity One.)
  • Not using modulo, signum, minimum and maximum Math functions as well as various String translate and replace functions. (These are unrelated to Cyclomatic Complexity One, but offer ways to work around in the specified task further down.)
control room in former refinery (licensed CC BY-NC-ND by Michal Jancek)Word of Warning
This is an exercise, even more it is an "inverted" exercise because it wants us to do things we usually avoid doing. And for good reason, using exceptions this way is an anti pattern. It is basically a goto statement, not a structured break or continue style go to, but a real nasty one where we can jump across multiple stack frames. It makes code hard to understand. Often performance is bad due to the cost of creating exceptions. Don't do this in your project. Keep in mind that we are just playing...

Assignment
As a task let us create a ROT-13 "Encryption", also known as Caesar-Chiffre. Our requirements are:
  1. Write a function encode to encode a message using ROT-13.
  2. Each letter is replaced with one 13 added in the alphabet.
  3. At the end of the alphabet, it continues at the beginning.
  4. Characters other than letters are not encoded.
  5. Lowercase letters are first changed to uppercase letters.
  6. Umlauts are letter combinations for encoding, e.g. "Ä" becomes "AE" before encoding and so on.
  7. Bonus: Make rotation configurable. Now it is 13.
These are plenty of requirements. In a usual session we manage to finish item 4) which shows all the relevant parts. If we have more time we can of course do more.

Try it Yourself
Below I will show Java code of the most common solution. After you see it, you will not be able to un-see it. If you want to explore the constraint and the exercise on your own, then stop reading now! I encourage you to do that. Best way is to work with difficult constraints is to code a little bit and then step back and verify if all rules still apply.

Hands On!
I run this session as "interactive demo", which means I let participants decide what to do next, or at least I let them propose what to do next and I wait until a proposition is aligned with my plan. I make sure we stay focused on the main goal of the exercise. The whole coding takes 30 to 40 minutes. Further more I (demand to) use TDD and try to make the code readable (as possible). How do I start? I start with a (simple) failing test of course:
public class Rot13Test {

  @Test
  public void empty() {
    assertEquals("", encode(""));
  }

}
To keep things simple I add the production code (that is the function encode) at the top of the test class:
public class Rot13Test {

  public String encode(String message) {
    return "";
  }
The first test established the method with the required signature, see requirement #1. Now I am able to replace letters with one 13 added in the alphabet. A suitable test case is "A" becomes "N", i.e. assertEquals("N", encode("A")). The first challenge is how to check if there are characters in the message? I cannot loop or map them. How about:
public class Rot13Test {

  public String encode(String message) {
    try {
      message.charAt(0);
      return "N";
    } catch (StringIndexOutOfBoundsException empty) {
      return "";
    }
  }
Ok. Next I choose to go for more letters. I could also do that at the end, it depends what people say during the workshop... A suitable test case is "AA" becomes "NN".
public class Rot13Test {

  public String encode(String message) {
    try {
      char first = message.charAt(0);
      String remaining = message.substring(1);
      return encodeChar(first) + encode(remaining);
    } catch (StringIndexOutOfBoundsException empty) {
      return "";
    }
  }

  private String encodeChar(char c) {
    return "N";
  }
The recursion ends when the message is empty. Back to requirement #2. My next test case is "B" becomes "M" and I only need to modify the method encodeChar():
public class Rot13Test {
  ...

  private String encodeChar(char c) {
    int encoded = c + 13;
    return Character.toString((char) encoded);
  }
This works for the letters "A" to "M" (which becomes "Z"). Nice. Requirement #3 deals with letters "N" to "Z", so
public class Rot13Test {
  ...

  private String encodeChar(char c) {
    int encoded = c + 13;
    try {
      // if encoded <= 'Z' then jump
      int tmp = 1 / (encoded / ('Z' + 1));
      encoded -= 26;
    } catch (ArithmeticException smaller) {
      // leave encoded alone
    }
    return Character.toString((char) encoded);
  }
I will explain how that works: If encoded is less or equal to "Z" the logic is already correct. How can I create an exception if a number is less than 'Z' + 1? If encoded is smaller than this limit, the integer division will be zero which will result in a division by zero, which in Java causes an ArithmeticException. If encoded is larger than "Z", the result of the division will be 1, so dividing by it is allowed and the code continues. Now the algorithm works for all letters.

The Sluice Gate (licensed CC BY-NC-ND by Ib Aarmo)Requirement #4 tells us to leave special characters alone. Which are these? A quick look at the 7 bit ASCII table,
 !"#$%&'()*+,-./0123456789:;<=>?
@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_
`abcdefghijklmnopqrstuvwxyz{|}~
shows the special characters. There are three ranges which I need to handle. (At the moment there are only two ranges, and I know that lowercase letters will be handled later.) I add a test for several special characters below, i.e. assertEquals("!/?@", encode("!/?@")) and later one above i.e. assertEquals("[_`{~", encode("[_`{~")), always using the first and last character of each range.
public class Rot13Test {
  ...

  private String encodeChar(char c) {
    int encoded = c;
    try {
      skipIfBelow(encoded, 'A');
      skipIfBelow('Z', encoded);
      encoded += 13;

      skipIfBelow(encoded, 'Z' + 1);
      encoded -= 26;
    } catch (ArithmeticException smaller) {
      // leave encoded alone
    }
    return Character.toString((char) encoded);
  }

  private void skipIfBelow(int codePoint, int limit) {
    int tmp = 1 / (codePoint / limit);
  }
By extracting a helper method skipIfBelow() I can check against the limits of the two ranges: Below and above. The basic algorithm is complete. Requirement #5 is more of the same, adding a toUppercase:
public class Rot13Test {
  ...

  private int toUppercase(int codePoint) {
    try {
      skipIfBelow(codePoint, 'a');
      skipIfBelow('z', codePoint);

      return codePoint - 'a' + 'A';

    } catch (ArithmeticException skipped) {
      // leave char alone
      return codePoint;
    }
  }
Control Flow "Library"
I said I try to make the code more readable. This can be done with custom exceptions and extracting the flow control logic into separate "library" functions like skipIfBelow(). During a different run of the session I ended up with
public class Rot13Test {
  ...

  static class SmallerThan extends Exception {
    public SmallerThan(Throwable cause) {
      super(cause);
    }
  }

  private void testIfSmaller(int codePoint, int limit)
               throws SmallerThan {
    try {
      int tmp = 1 / (codePoint / limit);
    } catch (ArithmeticException e) {
      throw new SmallerThan(e);
    }
  }

  static class LargerThan extends Exception {
    public LargerThan(Throwable cause) {
      super(cause);
    }
  }

  private void testIfLarger(int codePoint, int limit)
               throws LargerThan {
    try {
      testIfSmaller(limit, codePoint);
    } catch (SmallerThan e) {
      throw new LargerThan(e);
    }
  }

  static class ReplacedUmlaut extends Exception {
    public final String replacement;

    public ReplacedUmlaut(String replacement) {
      this.replacement = replacement;
    }
  }

  private void replaceUmlaut(int codePoint, int umlaut,
                             String replacement)
               throws ReplacedUmlaut {
    try {
      testIfSmallerThan(codePoint, umlaut);
      testIfLargerThan(codePoint, umlaut);
      throw new ReplacedUmlaut(replacement);
    } catch (SmallerThan | LargerThan notUmlaut) {
    }
  }
This allows me to distinguish different cases in the catch clause, which becomes a switch statement.

Closing Circle
This code is not like the code you see every day and it was definitely not the code you should write, but all participants agreed that they had a lot of fun. Several people said that I had screwed their mind and my long time peer Bernhard Woditschka said that he liked how it forced him to think outside of the box. This is probably because I am exploring negative aspects, i.e. concepts we usually try to avoid. Samuel Ytterbrink agreed saying "I think this session was like balm for the soul, nothing so freeing as being ordered to do something you are not supposed to do."

Using only exceptions for control flow, like naming all identifiers randomly, focuses on unwanted qualities of code, sharpens our awareness and (hopefully) raises our dislike of them. Ant it is a fun exercise, too. Stay tuned for my next Coding Fun session: No Composition Only Inheritance ;-)

25 June 2025

Patching Io Addons

This project is getting out of hand. I just wanted to use Regular Expressions in Io. This is the forth part of me trying different extensions of Io. First I installed addons without native code, then I compiled native code of addons and in the third part I:
  • Checked package.json and build.io for hints about needed third party libraries and headers.
  • Found ported libraries for Windows in GnuWin32, e.g. ReadLine.
  • Compiled Io addons with dependencies.
  • Fixed the undefined reference to 'IoState_registerProtoWithFunc_' error, which occurs using addons created for older versions of Io.
  • Worked around conflicting headers included by IoObject.h or IoState.h.
  • Finally compiled with dependencies on the native code of another addon.
On the way I added minor fixes to several addons, see my (forked) Io repositories and today I cover addons which needed more extensive modifications.

patch (licensed CC BY-NC-ND by Natasha Wheatland)JSON Parsing
Io has "half" JSON support, most objects provide an asJson() method to represent the contained data in JSON. Some addons (like Docio) require Sequence.parseJson() but omit a specific dependency for that and my Io (iobin-​win32-​current.zip) misses this method. These addons are for a newer version of Io, which has not been released (yet?). Writing a JSON parser is a nice exercise and there is already a JSON parser for Io. It is neither an addon nor an Eerie package. Preparing some arbitrary Io code as addon means moving the existing files into the proper folder structure, and adding the files needed to run as addon (i.e. proto and depends files). I even added a test. My Io JSON addon can be cloned directly into the addons folder %IO_HOME%\​lib\​io\​addons.

Missing Io Core Functions
I started changing addon source code to include the JSON parser addon, at the same time I wanted to keep my changes as little as possible. The Io Guide said that if you have a .iorc file in your home folder, it will be eval'ed before the interactive prompt starts.. In my %HOMEDRIVE%%HOMEPATH%\.iorc I added all definitions of missing Io core functions:
false isFalse := method( true )
true isFalse := method( false )

// load parseJson
Sequence hasSlot("parseJson") ifFalse(
    Json
)

false asJson := "false"
true asJson := "true"
nil asJson := "null"
This made me ask myself, what else was added to Io since my Windows binary was built in 2013? I cloned Io and compared the proper tag with master. There were many changes and I filtered out formatting and comments. The final result was a short list of additions and modifications like
  • Addon and AddonLoader extensions to use Eerie.
  • Core tildeExpandsTo() using UserProfile instead of HOME on Windows.
  • Sequence power() and powerEquals().
  • TestRunner run() returning the number of errors.
Docio
With JSON support and Markdown working, I can run Docio. Docio is the documentation generator for Eerie packages. It extracts tagged comments from C and Io code and generates Markdown and HTML documentation like this. To make Docio work, I had to work around several issues:
  1. Docio's repository name is lowercase. To install it as addon the folder name has to be uppercase, as for Kano:
    > cd "%IO_HOME%\lib\io\addons"
    > git clone git@github.com:IoLanguage/docio.git Docio
  2. Docio does not depend on native code, and it has Markdown as its sole dependency.
    > echo Markdown > Docio\depends
    > echo Docio > Docio\protos
  3. Docio loads Eerie eagerly in the first line of Docio.io. It uses Eerie to query its template path. I lack Eerie and the eager loading fails, so I remove that. With Eerie out of the picture, I always have to provide the full path to the template (%IO_HOME%\lib\io\addons\Docio\template). Now I can initialise Docio with io -e "Docio println". Success.
  4. Docio has a starter script in bin/docio which needs a Windows version, i.e. a bin/docio.bat which calls the original starter script,
    io "%IO_HOME%\lib\io\addons\Docio\bin\docio" %*
  5. With the starter script Docio is available as a command line tool. One thing to know is that its help is wrong. It says
    docio package=/path/to/package [template=/path/to/template]
    while it really needs two dashes for each option,
    docio --package=/path/to/package [--template=/path/to/template]
    Both paths need to be absolute, otherwise documentation files appear in strange places.
  6. There is a syntax error in DocsExtractor.io line 65 and following.
  7. Copying of binary resources, i.e. fonts, corrupts the files. You will have to copy them manually. This is because Io's low level C code does fails to set the binary flag when opening files. On Windows the C library functions consider text files to be finished on the first byte 0x1A. I am unable to fix that right now.
After fixing all that, Docio provides help, even inside the Io REPL, which comes handy:
Io> Docio printDocFor("ReadLine")
Binding to GNU readline.
Docio will generate the documentation for any package on the fly which has a package.json with a name field. Bundled addons miss that file, and I create empty ones containing each addon's name for addons where I want to generate documentation. Here is my own Docio with all the fixes.

Socket
Finally I am going for the Socket addon. I was scared of Socket, some sources stated that Io socket support has always been tricky. Socket depends on libevent 2.0.x, an event notification library. Surprisingly autogen.sh, configure and make install compile and link libevent without any problems. Now I have some libevent_*.dll files. This is way too easy.

But of course Socket's C code does not compile. The header sys/​queue.h is not available on Windows. Fortunately libevent comes with its own compat/​sys/​queue.h. Some header files, e.g. IoEvConnection.h, IoEvHttpServer.h and several others need the conditional include:
#include "Socket.h"
#if !defined(_WIN32) || defined(__CYGWIN__)
#include <sys/queue.h>
#else
#include <compat/sys/queue.h>
#endif
#include <event.h>
Further UnixPath.c fails compilation, and I drop it from the list of files to compile. Even if it would compile, it would not work as indicated by the error returned from IoUnixPath for defined(_WIN32) || defined(__CYGWIN__): Sorry, no Unix Domain sockets on Windows MSCRT.

Linking the compiled files produces an undefined reference to 'GetNetworkParams@8', which is part of the Windows GetNetworkParams interface in iphlpapi.dll, as listed on build.io together with ws2_32. It seems that after my exploration of building addons with native dependencies like ReadLine or Markdown, compiling Socket as difficult than that. Here are the important pieces of the steps:
> ...
> cd source
> gcc -fPIC -D _NO_OLDNAMES -D IO_WINSOCK_COMPAT -c ...
> gcc -liovmall -lbasekit -levent -liphlpapi -lws2_32 ^
      -shared -Wl,--out-implib,libIoSocket.dll.a ^
      ... -o libIoSocket.dll
> ...
My fork of Socket contains the required fixes for Windows.

Using the Socket addon on current Ubuntu
In my product development Coderetreat template, I have GitHub actions to verify the sample code. Based on Sandro's installation instructions I first install the required dependencies:
sudo apt-get install libpcre3-dev libevent-dev
(This might be unecessary as GitHub's Ubuntu image has both of them installed.) The current branch of libevent is 2.1.x and the none of the older 2.0.x versions do compile due to wrong dependencies. At the same time, the Linux version of Io contains Socket but needs libevent 2.0.5 specifically. I have no idea if that is the way to fix these kind of issues, but it works, so I link the installed version (2.1.7) as the required (2.0.5) one.
ls -la /usr/lib/x86_64-linux-gnu/libevent*.so.*
sudo ln -s /usr/lib/x86_64-linux-gnu/libevent-2.1.so.7.0.1 /usr/lib/x86_64-linux-gnu/libevent-2.0.so.5
(I leave the ls is the action to show the current version when the GitHub runner changes and there is a newer version of libevent.) After that I download the "latest" version of Io and install it:
wget -q http://iobin.suspended-chord.info/linux/iobin-linux-x64-deb-current.zip
unzip -qq iobin-linux-x64-deb-current.zip
sudo dpkg -i IoLanguage-2013.11.04-Linux-x64.deb
sudo ldconfig
io --version
The Linux version of Io comes with almost all addons pre-compiled, and there is no need for any compilation. Success. Because this version is without Eerie, custom addons have to be installed manually into the System installPrefix folder, e.g. adding Docio
git clone https://github.com/codecop/Docio.git
io -e "System installPrefix println"
sudo mv Docio /usr/local/lib/io/addons/
io -e "Docio println"
Now the runner is ready to execute some tests which is usually done with io ./tests/correctness/run.io. The full GitHub action for Io is here.

Alaska, Frontier Land (licensed CC BY-NC-ND by Clickrbee)Random Facts about Addons
During my exploration I learned more things about Io's addon structure:
  • The protos file does not need to contain the name of the "main" prototype, which is also the name of the addon, and often it does not. I put the name of all (exported) prototypes there to simplify my scripts. Then package.json, the Eerie manifest, does contain all prototypes.
  • In the beginning I though depends was some kind of manifest, listing dependencies. But it is only needed for dependencies of native code, so AddonLoader loads dependent addons before they are used in native code. For non native addons, Io will load whatever is needed when parsing any unknown type name. Till now the only addon I have seen which needs that feature is Regex.
  • When an addon is loaded all its files are evaluated. Only then is it registered as active. This can lead to addon initialisation loops. The initialisation order seems to be by file name. Some addons with complex inter dependencies - like Socket - prefix Io files with A_0, A_1 and so on to ensure ordered initialisation. (This is a bit annoying for tooling as the prototype name usually equals the file name in Io.)
Summary: My Feelings Towards Io
While Io is dead since more than ten years, working with it feels bleeding edge, even more it is outside the frontier. You are at your own, there is no help. Nobody is coming to save you. The latest article I found was written in 2019. There are less than ten (!) active blog posts: Blame it on Io (2006), Io language on Windows (2014), Io Basics (2015) and Io Programming Language (2019) - to list the best ones. There are a handful of Stack Overflow questions and a few repositories on GitHub - which are sometimes incompatible with the "latest" Io. ChatGPT understands the language but fantasises the libraries, so no help from AI neither. I am used to modern languages with a rich ecosystem, e.g. Java, C#, Python and this is an unfamiliar feeling. At the same time it is a refreshing puzzle. Maybe I will come back for a vacation in uncharted territory.