<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Jordan Lord]]></title><description><![CDATA[Jordan Lord]]></description><link>http://jordanlord.co.uk</link><generator>metalsmith-feed</generator><lastBuildDate>Mon, 20 Apr 2026 06:55:15 GMT</lastBuildDate><atom:link href="http://jordanlord.co.uk/rss.xml" rel="self" type="application/rss+xml"/><author><![CDATA[Jordan Lord]]></author><item><title><![CDATA[Growth engineering one pager]]></title><description><![CDATA[<p>This one pager is for implementing a growth engineering process in your team.
Originally I wrote this at Footium after reading <em>Hacking Growth</em> by Sean Ellis.
All citations reference pages in the book. Below is the generalised version so
you can share, adapt, and use it.</p>
<hr>
<h2 id="problem">Problem</h2>
<p>Many organisations operate in product mode, optimising for execution and
delivery instead of learning. Delivery cadence often has a slow feedback loop,
and engineering and marketing work in silos <em>[p. 34]</em>. Teams may not run typical
Agile, and their sprints may become task batches inside a larger delivery cycle,
which means they ship without fast validation. They may now have meetings that
involve the whole team, but still not operate as a truly cross-functional team.
Individual experiments can be encouraging, but the real challenge is scaling
that experimentation process across the company and making it a consistent
cross-functional habit.</p>
<h2 id="solution">Solution</h2>
<p>The shift is from input-driven delivery to outcome-driven growth. A growth
engineering operating model uses a single, weekly growth cycle that prioritises
experiments against clear metrics such as activation, retention, and revenue,
and then scales what works.</p>
<ul>
<li><strong>Growth meeting</strong>: A weekly growth meeting happens on a fixed day each week.
The main focus of the team switches from sprints to weekly growth cycles.</li>
<li><strong>Product delivery moves to longer planning cycles</strong>: Typical sprint rituals
align to the broader product delivery cycle, creating 4+ week long cycles.</li>
<li><strong>Standup</strong>: Standup remains the same format, but is unblocker focused.</li>
<li><strong>Focus on outcomes</strong>: All work ties to target metrics; decisions are made on
expected impact and measured results.</li>
<li><strong>Deploy to prod</strong>: To facilitate weekly experiment turnaround, deploy small
changes via production. Keep larger product delivery cycles deploying
upstream.</li>
</ul>
<h2 id="experiment-cycle">Experiment Cycle</h2>
<p>All experiments move through the following process:</p>
<p><code>Analyse -&gt; Ideate -&gt; Prioritise -&gt; Test</code></p>
<p>The experiment starts with a written idea that lives in the idea backlog. Ideas
are prioritised using the ICE framework. Ideas are written and prioritised
async. Ideas are tested and analysed in a growth cycle.</p>
<h2 id="the-idea-p-120">The Idea <em>[p. 120]</em></h2>
<p>Ideas are logged in the idea backlog and have the following form:</p>
<ul>
<li>Name</li>
<li>Description (like an executive summary, who, what, when, where, why, how)</li>
<li>Hypothesis (no broad strokes)</li>
<li>Metrics to be measured (most should measure more than one)</li>
</ul>
<h2 id="prioritise-p-124">Prioritise <em>[p. 124]</em></h2>
<p>Prioritise the idea backlog asynchronously using the ICE framework:</p>
<ul>
<li>Impact (out of 10)</li>
<li>Confidence (out of 10)</li>
<li>Ease (out of 10)</li>
<li>Average (out of 10)</li>
</ul>
<h2 id="roles">Roles</h2>
<p>A growth team consists of the following roles. Everyone contributes to the idea
backlog.</p>
<ul>
<li>Growth lead <em>[p. 38]</em><ul>
<li>Part manager, part product owner, part scientist</li>
<li>Chooses the core focus area and objectives for the team to work on</li>
<li>Ensures the metrics are appropriate for the growth goals established</li>
</ul>
</li>
<li>Product manager <em>[p. 39]</em><ul>
<li>The CEO of the product</li>
<li>Oversees how features and designs are brought to life</li>
<li>Responsible for breaking down silos between engineers and marketing</li>
</ul>
</li>
<li>Engineers <em>[p. 40]</em><ul>
<li>Writes the code for product features that the team experiments on</li>
<li>Should be involved in the ideation process, not just task delivery</li>
</ul>
</li>
<li>Marketing <em>[p. 40]</em><ul>
<li>Required in a growth team for optimal results</li>
<li>Cross-pollinates their experience with engineering</li>
</ul>
</li>
<li>Data analyst <em>[p. 41]</em><ul>
<li>Ensures that experiments are well statistically designed and rigorous</li>
<li>Ensures user data and analytics are accessible through the analytics
database</li>
<li>Mines for deep insight in the data</li>
</ul>
</li>
</ul>
<h2 id="growth-meeting-p-134">Growth meeting <em>[p. 134]</em></h2>
<p>The growth meeting is a weekly meeting that happens at a fixed time each week.
It is run by the growth lead and kept on time to schedule. Everything covered
in the growth meeting is planned and decided ahead of time. What is decided in
the growth meeting is which experiments are going to be run this cycle, based
on prior prioritisation, and who is going to own each one.</p>
<ul>
<li>15 mins: metrics review and update focus area</li>
<li>10 mins: review last week&#39;s testing activity</li>
<li>15 mins: key lessons learned from analysed experiments</li>
<li>15 mins: select growth tests for current cycle and assign owners</li>
<li>5 mins: check growth of idea pipeline</li>
</ul>
<h2 id="the-transition-week">The Transition Week</h2>
<p>The first growth meeting should be used to loop everyone into the process and
explain how it is going to work <em>[p. 114]</em>. The following week, team members take
time to percolate ideas for what experiments to run in their first growth
cycle, adding ideas to the idea backlog <em>[p. 116]</em>.</p>
<p>Before starting the first experiment, it is a requirement to have the &quot;Aha&quot;
moment defined, data tracking in place, the fundamental growth equation
defined, and the goal defined.</p>
<p>The &quot;Aha&quot; moment <em>[p. 63, 84]</em> is the moment at which the user truly experiences
the core value of the product, the instant at which the product clicks for
them. For Dropbox, for example, it was when files had been synced across
devices and the user realised they could access them from anywhere.</p>
<p>The fundamental growth equation <em>[p. 91, 116]</em> is the simplest way to express
what drives a company&#39;s growth. It describes the company&#39;s core metrics and how
they interact with each other to drive growth. For example:</p>
<pre><code class="hljs">amount <span class="hljs-operator">of</span> growth = <span class="hljs-built_in">number</span> <span class="hljs-operator">of</span> installs
                 * <span class="hljs-built_in">number</span> <span class="hljs-operator">of</span> monthly active users
                 * <span class="hljs-built_in">number</span> <span class="hljs-operator">of</span> purchasers
                 * <span class="hljs-built_in">average</span> order size
                 * <span class="hljs-keyword">repeat</span> purchase rate</code></pre>

<p>The goal should be a single clear target, adapted to the organisation. For
example: 3000 paid monthly active users by the end of the year.</p>
]]></description><link>http://jordanlord.co.uk/blog/growth-engineering</link><guid isPermaLink="true">http://jordanlord.co.uk/blog/growth-engineering</guid><dc:creator><![CDATA[Jordan Lord]]></dc:creator><pubDate>Sun, 19 Apr 2026 00:00:00 GMT</pubDate></item><item><title><![CDATA[3 constraints before I build anything]]></title><description><![CDATA[<p>These are the 3 constraints that I use before I start building anything. I&#39;m a
believer in constraints as an enabler for creativity. Constraints help us
collapse the search space, and figure out innovative solutions to problems.</p>
<p>I&#39;ve been a builder for 10 years, and I&#39;ve built products that went nowhere
because they were either too complex or had no identity. These are the
constraints that I landed on after making those mistakes.</p>
<h2 id="one-page-or-it-doesnt-get-built">One page or it doesn&#39;t get built</h2>
<p><em>This constraint limits complexity and ambiguity.</em></p>
<p>Write a one pager for all of your ideas. Your one pager captures your north
star. It&#39;s non-negotiable, precise, ambitious, and lean. Once your one pager is
written, it is applied to all different types of communication. Share it as a
memo for investors, contributors, team members, friends, or family. Working
collaboratively on a product, there will always be contention points and
conflict, it can sometimes be difficult to know what battles to pick. If it&#39;s
not in the one pager, then it&#39;s either not worth fighting over, or the one pager
ought to be amended to include the thing. Not only is a one pager useful for
communication, it&#39;s useful for organising your own thoughts. If you can&#39;t fill
one page, don&#39;t fill the gaps with fluff, it means you&#39;re not ready to build.
First research, plan, prototype, then write the one pager again. Iterate. If it
requires more than one page, it&#39;s too complex, don&#39;t build it.</p>
<h2 id="the-core-tech-must-be-separable-from-the-product">The core tech must be separable from the product</h2>
<p><em>This constraint limits you to ideas that have real leverage and originality.</em></p>
<p>Develop a core piece of technology that supports your product and is not the
product itself. The core tech is a method, skill, tool, or even product that
supports what you&#39;re doing today but must survive without it. It&#39;s a type of
reusable IP. Why? Separating the core tech forces you to think beyond the
product that you&#39;re building. Products pivot in direction all the time, while
your core tech is constant and compounding. Compounding efforts have non-linear
gains over longer time horizons. Linus Torvalds developed git to improve the
Linux kernel development workflow. HashiCorp has HCL (HashiCorp Configuration
Language). Google has Kubernetes. But you don&#39;t need big tech resources to build
core tech, it could be a library that you extract from your codebase, or even a
methodology that you refine and commit to. Your core tech is your long term
commitment. It is independent of your product&#39;s direction. However, it must be
aligned with you or your company&#39;s long term vision. If your idea doesn&#39;t enable
core tech, then it isn&#39;t high enough leverage.</p>
<h2 id="one-defining-constraint-must-shape-the-product">One defining constraint must shape the product</h2>
<p><em>This constraint limits feature creep and forces identity.</em></p>
<p>Define your own constraint that is front and centre to your product. That means
the user sees and interacts with it all the time. It is obvious and it is what
gives your product identity. A good constraint gives your product a <em>feel</em>, it
permeates through all parts of the user experience. Minecraft is built entirely
from blocks. IKEA is flat-pack, self-assembly furniture. The constraint that you
choose limits scope by reducing your decision space, enabling you to concentrate
on the problems that really make the difference. If you don&#39;t choose a
constraint, or choose a bad constraint, you will build a bloated product that
will try to do everything. The design of your product will &quot;fall out&quot; of a
well-designed constraint. Like in your product, your constraint must be front
and centre in your one pager.</p>
<h2 id="closing-rule">Closing Rule</h2>
<p>When it comes to deciding what to build, if it fails any of these constraints,
then I don&#39;t build it.</p>
]]></description><link>http://jordanlord.co.uk/blog/3-constraints</link><guid isPermaLink="true">http://jordanlord.co.uk/blog/3-constraints</guid><dc:creator><![CDATA[Jordan Lord]]></dc:creator><pubDate>Tue, 07 Apr 2026 00:00:00 GMT</pubDate></item><item><title><![CDATA[6502 vs ZX Spectrum - A Graphics Experiment You Didn’t Expect]]></title><description><![CDATA[<h1 id="introduction">Introduction</h1>
<p>Okay so this might seem like a bit of a strange article. But trust me. I&#39;ve had
this burning idea recently to combine retro computer components to create
something a bit different. In this case, it&#39;s an emulation of a ZX Spectrum
display wired up with a 6502 processor. What makes this strange is that the ZX
Spectrum uses a Z80 processor, not a 6502. This will be part of a series of
articles where I&#39;ll combine retro and modern technology together in weird and
wonderful ways to create experiments. There is a lot of support for the 6502
processor thanks to the worldwide popularity of systems like the Commodore 64
and the Nintendo Entertainment System.</p>
<p>There is something special about the ZX Spectrum. It was released in the UK in
1983 for £125, taking the domestic home computer market by storm. It almost
instantly took off as a kind of <em>game console of its day</em>, birthing the likes
Manic Miner, Knight Lore and Atic Atac. Being an incredibly cheap machine of its
day, a lot of corners were cut. One corner most notable was its graphics
capability.</p>
<p>The graphics of the ZX Spectrum consist of a 256x192 bitmapped screen, with
8x8 pixel attribute blocks. Now, the most striking thing here is that each
attribute blocks could only have two colours. Those attribute blocks were fixed
to a grid. This was unlike other machines at the time, which had support for
more than two colours and even native sprites. In a way, it was like the ZX
Spectrum was actually monochrome, with a sprinkle of colour added to its
monochromatic display to give the illusion of colour. The result - a breadth of
games that had an unusual, unpolished, but undoubtedly unique ZX Spectrum
look to it.</p>
<h1 id="how-does-it-work">How does it work?</h1>
<p>The display itself is memory mapped into two main sections. The pixel data is
written from addresses 0x4000 to 0x57FF. The attribute data written from 0x5800
to 0x5AFF. This meant that the pixel data has 6144 bytes, while each byte of the
attribute corresponded to its respective 8x8 block.</p>
<h1 id="pixel-data">Pixel Data</h1>
<p>Let&#39;s look at the pixel data specifically for now. It&#39;s a 256 pixel width (32
columns), with 192 pixels height (24 rows). That is further broken down into 3
areas. Each area is 8 rows and 32 columns, conveniently totaling 2048 bytes
each. Something to note about areas, each line in the 8 rows are interleaved. So
if setting the first line of your block is done at address 0x4000, the second
line is set at 0x4100, the third at 0x4200.</p>
<p>For demonstration sake, let&#39;s set the first 256 bytes to 0xFF, from address
0x4000 to 0x40FF. This will show the interleaved nature of the areas.</p>
<textarea class="hljs logiclogue-6502-asm" data-ram-id="example-1" style="width: 100%; height: 200px;">
init:
    ; Store the pixel address in zero page for indirect addressing
    LDA #$00
    STA $00
    LDA #$40
    STA $01
    ; Store the attribute address in zero page for indirect addressing
    LDA #$00
    STA $02
    LDA #$58
    STA $03
    ; Counter
    LDY #$00
loop:
    ; Set the pixel byte at address 0x4000 + Y
    LDA #$FF
    STA ($00),Y
    ; Set the attribute byte as green at 0x5400 + Y
    LDA #%00000100
    STA ($02),Y
    ; Ending the program
    INY
    CPY #$00
    BNE loop
    JMP loop
</textarea>

<p><canvas class="u-full-width logiclogue-zx-screen" data-ram-id="example-1" width="256" height="192" style="image-rendering: pixelated"></canvas></p>
<h1 id="attribute-data">Attribute Data</h1>
<p>The attribute data is what defines an 8x8 block&#39;s colour. The attribute block is
broken town into two components, the least significant 3-bits which are used for
storing the &#39;ink&#39;, the next least significant 3-bits for the &#39;paper&#39;. Then the
7th most significant bit for whether the colours are bright or not. Finally the
most significant bit is for the &#39;flash&#39;. The &#39;paper&#39; dictates how the 0 bits are
coloured, the &#39;ink&#39; dictates how the 1 bits are coloured.</p>
<table>
<thead>
<tr>
<th>bit 8</th>
<th>bit 7</th>
<th>bit 6-4</th>
<th>bit 3-1</th>
</tr>
</thead>
<tbody><tr>
<td>flash</td>
<td>bright</td>
<td>paper</td>
<td>ink</td>
</tr>
</tbody></table>
<p>The ZX Spectrum used a GRB colour scheme instead of a RGB one. Looking at each
3-bit colour, here is the table by bit breakdown.</p>
<table>
<thead>
<tr>
<th>G</th>
<th>R</th>
<th>B</th>
<th>#n</th>
<th>Colour</th>
</tr>
</thead>
<tbody><tr>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>Black</td>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>Blue</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>0</td>
<td>2</td>
<td>Red</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>1</td>
<td>3</td>
<td>Magenta</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>0</td>
<td>4</td>
<td>Green</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>1</td>
<td>5</td>
<td>Cyan</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>0</td>
<td>6</td>
<td>Yellow</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>7</td>
<td>White</td>
</tr>
</tbody></table>
<p>The example below shows each block incremented one at a time. So the first
attribute block would be binary <code>%00000000</code> (black paper, black ink),
<code>%00000001</code> (black paper, blue ink) and so on.</p>
<textarea class="hljs logiclogue-6502-asm" data-ram-id="example-2" style="width: 100%; height: 200px;">
init:
    JMP loop
set_attributes:
    LDA #$00
    STA $00
    LDA #$58
    STA $01
    LDY #$00
loop_set_attributes:
    TYA
    STA ($00),Y
    INY
    BNE loop_set_attributes
    RTS
draw_char:
    ; Load bitmap address into zero space
    LDA current_letter_pos
    STA $02
    LDA #$40
    STA $03
    ; Letter counter
    LDY #$00
    ; Load letter_a address into memory
    LDA #<letter_a
    STA $04
    LDA #>letter_a
    STA $05
draw_char_line:
    ; Load the byte line
    LDA ($04),Y
    ; Write byte line to bitmap
    LDX #$00
    STA ($02,X)
    ; Increment significant bit of address
    INC $03
    ; Increment counter
    INY
    ; Check to see whether counter has written all 8 lines
    CPY #$08
    BNE draw_char_line
    RTS
current_letter_pos:
    .byte $00
draw_letters:
    JSR draw_char
    INC current_letter_pos
    CMP current_letter_pos
    BNE draw_letters
    RTS
loop:
    JSR set_attributes
    JSR draw_letters
    LDA #$00
    STA $00
    LDA #$01
    STA $01
    JSR draw_char
    JMP loop
letter_a:
    ; Character 'A'
    .byte %00111100  ; Line 1:   00111100
    .byte %01100110  ; Line 2:   01100110
    .byte %01100110  ; Line 3:   01100110
    .byte %01111110  ; Line 4:   01111110
    .byte %01100110  ; Line 5:   01100110
    .byte %01100110  ; Line 6:   01100110
    .byte %01100110  ; Line 7:   01100110
    .byte %00000000  ; Line 8:   00000000
</textarea>

<p><canvas class="u-full-width logiclogue-zx-screen" data-ram-id="example-2" width="256" height="192" style="image-rendering: pixelated"></canvas></p>
<h1 id="useful-functions">Useful functions</h1>
<p>Let&#39;s try a more interesting example. Let&#39;s say we want to draw a pixel at the
mouse cursor. We&#39;re going to memory map the mouse X and Y positions relative to
the screen to addresses 0x3FFE and 0x3FFF respectively.</p>
<p>In order to draw the mouse position on the screen, we have to calculate a few
different things. We have to calculate the row, column, line and area that we&#39;d
like to draw onto. As well as calculating the individual byte itself.</p>
<p>The row is calculated by taking the mouse y position, masking it against
<code>00111000</code> and bit-shifting twice to the left.</p>
<pre><code class="hljs"><span class="hljs-label">mouse_row:</span>
    <span class="hljs-preprocessor">.byte</span> $<span class="hljs-number">00</span>
<span class="hljs-label">update_mouse_row:</span>
    LDA mouse_record_y
    <span class="hljs-keyword">AND</span> <span class="hljs-preprocessor">#%00111000</span>
    ASL
    ASL
    STA mouse_row
    RTS</code></pre>

<p>To get the column, we take the mouse x position and bit-shift right three times.
<code>abcdefgh</code> -&gt; <code>000abcde</code>.</p>
<pre><code class="hljs"><span class="hljs-label">mouse_column:</span>
    <span class="hljs-preprocessor">.byte</span> $<span class="hljs-number">00</span>
<span class="hljs-label">update_mouse_column:</span>
    LDA mouse_record_x
    <span class="hljs-keyword">ROR</span>
    <span class="hljs-keyword">CLC</span>
    <span class="hljs-keyword">ROR</span>
    <span class="hljs-keyword">CLC</span>
    <span class="hljs-keyword">ROR</span>
    STA mouse_column
    RTS</code></pre>

<p>For the line, we&#39;re going to mask the first 3 bits. <code>abcdefgh</code> -&gt; <code>00000fgh</code>.</p>
<pre><code class="hljs"><span class="hljs-label">mouse_line:</span>
    <span class="hljs-preprocessor">.byte</span> $<span class="hljs-number">00</span>
<span class="hljs-label">update_mouse_line:</span>
    LDA mouse_record_y
    <span class="hljs-keyword">AND</span> <span class="hljs-preprocessor">#%00000111</span>
    STA mouse_line
    RTS</code></pre>

<p>To calculate the area, take the most significant 2 bits. In this example, we
just bit-shift three times to make it easier to calculate the final address
where we&#39;re going to draw to the screen.</p>
<pre><code class="hljs"><span class="hljs-label">mouse_area:</span>
    <span class="hljs-preprocessor">.byte</span> $<span class="hljs-number">00</span>
<span class="hljs-label">update_mouse_area:</span>
    LDA mouse_record_y
    <span class="hljs-keyword">AND</span> <span class="hljs-preprocessor">#%11000000</span>
    <span class="hljs-keyword">ROR</span>
    <span class="hljs-keyword">ROR</span>
    <span class="hljs-keyword">ROR</span>
    STA mouse_area
    RTS</code></pre>

<p>Having the row, column and area is only good enough to draw to a specific byte
on the screen. However, we also want to draw to a specific pixel. To achieve
this we have to bit-shift a single pixel right n number of times. We calculate n
by masking the least significant 3 bits from the mouse&#39;s x position.</p>
<pre><code class="hljs"><span class="hljs-label">mouse_byte:</span>
    <span class="hljs-preprocessor">.byte</span> %<span class="hljs-number">10000000</span>
<span class="hljs-label">update_mouse_byte:</span>
    LDA mouse_record_x
    <span class="hljs-keyword">AND</span> <span class="hljs-preprocessor">#%00000111</span>
    TAX
    INX
    <span class="hljs-keyword">SEC</span>
    LDA <span class="hljs-preprocessor">#%00000000</span>
<span class="hljs-label">loop_update_mouse_byte:</span>
    <span class="hljs-keyword">ROR</span>
    DEX
    BNE loop_update_mouse_byte
    STA mouse_byte
    RTS</code></pre>

<p>Finally to draw, we have to calculate the address, then write the byte to that
address in memory in order to draw to the screen.  Fortunately, the address is
two bytes, so the calculation can be broken down into two separate ones.</p>
<p>Let&#39;s calculate the offsets. For the least significant byte of the offset we do
<code>column + row</code>, simple!</p>
<pre><code class="hljs"><span class="hljs-label">LDA</span> mouse_column
    <span class="hljs-keyword">ADC </span>mouse_row
    STA draw_pixel_offset</code></pre>

<p>For the most significant byte of the offset, we do <code>line + area</code>. Also simple!
Although, figuring this out by hand is usually quite tedious.</p>
<pre><code class="hljs"><span class="hljs-label">LDA</span> mouse_line
    <span class="hljs-keyword">ADC </span>mouse_area
    STA draw_pixel_offset + <span class="hljs-number">1</span></code></pre>

<p>Then finally you just add the bitmap address (<code>0x4000</code>) to the offset to get the
bitmap address you&#39;re actually going to write to.</p>
<p>We&#39;re not going to stop there, we also want the attribute offset so that we can
write the background colour too. Fortunately, that&#39;s also relatively simple.
I&#39;m going to leave the assembly below for demonstration. Basically, it involving
bit masking and bit-shifting to achieve the desired final address offset. the
assembly below makes it look a lot more complex than it actually is.</p>
<pre><code class="hljs"><span class="hljs-label">attribute_offset:</span>
    .word $<span class="hljs-number">0000</span>
<span class="hljs-label">update_attribute_offset_from_mouse:</span>
    LDA mouse_record_x
    <span class="hljs-keyword">AND</span> <span class="hljs-preprocessor">#%11111000</span>
    <span class="hljs-keyword">ROR</span>
    <span class="hljs-keyword">ROR</span>
    <span class="hljs-keyword">ROR</span>
    STA attribute_offset
    LDA mouse_record_y
    <span class="hljs-keyword">AND</span> <span class="hljs-preprocessor">#%00111000</span>
    ASL
    ASL
    ORA attribute_offset
    STA attribute_offset
    LDA mouse_record_y
    <span class="hljs-keyword">AND</span> <span class="hljs-preprocessor">#%11000000</span>
    <span class="hljs-keyword">ROR</span>
    <span class="hljs-keyword">ROR</span>
    <span class="hljs-keyword">ROR</span>
    <span class="hljs-keyword">ROR</span>
    <span class="hljs-keyword">ROR</span>
    <span class="hljs-keyword">ROR</span>
    STA attribute_offset + <span class="hljs-number">1</span>
    RTS</code></pre>

<textarea class="hljs logiclogue-6502-asm" data-ram-id="example-3" style="width: 100%; height: 200px;">
bitmap = $4000
attributes = $5800
last_attributes = $5B00
mouse_x = $3FFE
mouse_y = $3FFF
init:
    JSR set_attributes
    JMP loop
current_attribute_address:
    .word attributes
set_attributes:
    ; Store the attribute address in zp
    LDA current_attribute_address
    STA $00
    LDA current_attribute_address + 1
    STA $01
    LDX #$00
    LDA #%00000100
    STA ($00,X)
    ; +1 to the current address
    CLC
    LDA #$01
    ADC current_attribute_address
    STA current_attribute_address
    LDA #$00
    ADC current_attribute_address + 1
    STA current_attribute_address + 1
    ; Check whether the address is at the end
    CLC
    LDA $01
    CMP #>last_attributes
    BNE set_attributes
    RTS
draw_pixel_offset:
    .word $0000
update_pixel_offset:
    CLC
    LDA mouse_column
    ADC mouse_row
    STA draw_pixel_offset
    CLC
    LDA mouse_line
    ADC mouse_area
    STA draw_pixel_offset + 1
    ; Debug info
    ;LDA mouse_line
    ;STA bitmap + 0x100
    ;LDA mouse_record_y
    ;STA bitmap + 0x200
    ;LDA draw_pixel_offset
    ;STA bitmap + 0x300
    ;LDA draw_pixel_offset + 1
    ;STA bitmap + 0x400
    ;LDA draw_pixel_byte
    ;STA bitmap + 0x500
    RTS
draw_pixel_byte:
    .byte %11111111
update_pixel_byte:
    LDA mouse_byte
    STA draw_pixel_byte
draw_pixel:
    CLC
    LDA draw_pixel_offset
    ADC #<bitmap
    STA $00
    LDA draw_pixel_offset + 1
    ADC #>bitmap
    STA $01
    LDX #$00
    LDA ($00,X)
    ORA draw_pixel_byte
    STA ($00,X)
    RTS
attribute_offset:
    .word $0000
update_attribute_offset_from_mouse:
    LDA mouse_record_x
    AND #%11111000
    ROR
    ROR
    ROR
    STA attribute_offset
    LDA mouse_record_y
    AND #%00111000
    ASL
    ASL
    ORA attribute_offset
    STA attribute_offset
    LDA mouse_record_y
    AND #%11000000
    ROR
    ROR
    ROR
    ROR
    ROR
    ROR
    STA attribute_offset + 1
    RTS
draw_attribute:
    CLC
    LDA #<attributes
    ADC attribute_offset
    STA $00
    LDA #>attributes
    ADC attribute_offset + 1
    STA $01
    LDA #%00010100
    LDX #$00
    STA ($00,X)
    RTS
mouse_column:
    .byte $00
update_mouse_column:
    LDA mouse_record_x
    ROR
    CLC
    ROR
    CLC
    ROR
    STA mouse_column
    RTS
mouse_line:
    .byte $00
update_mouse_line:
    LDA mouse_record_y
    AND #%00000111
    STA mouse_line
    RTS
mouse_row:
    .byte $00
update_mouse_row:
    LDA mouse_record_y
    AND #%00111000
    ASL
    ASL
    STA mouse_row
    RTS
mouse_area:
    .byte $00
update_mouse_area:
    LDA mouse_record_y
    AND #%11000000
    ROR
    ROR
    ROR
    STA mouse_area
    RTS
mouse_record_x:
    .byte $00
mouse_record_y:
    .byte $00
update_mouse_record:
    LDA mouse_x
    STA mouse_record_x
    LDA mouse_y
    STA mouse_record_y
    RTS
mouse_byte:
    .byte %10000000
update_mouse_byte:
    LDA mouse_record_x
    AND #%00000111
    TAX
    INX
    SEC
    LDA #%00000000
loop_update_mouse_byte:
    ROR
    DEX
    BNE loop_update_mouse_byte
    STA mouse_byte
    RTS
loop:
    JSR update_mouse_record
    JSR update_mouse_column
    JSR update_mouse_line
    JSR update_mouse_row
    JSR update_mouse_area
    JSR update_mouse_byte
    JSR update_pixel_offset
    JSR update_pixel_byte
    JSR update_attribute_offset_from_mouse
    JSR draw_pixel
    JSR draw_attribute
    JMP loop
</textarea>

<p><canvas class="u-full-width logiclogue-zx-screen" data-ram-id="example-3" width="256" height="192" style="image-rendering: pixelated"></canvas></p>
<p>I think that just about wraps it up. The article started by introducing the ZX
Spectrum, a little bit of history, then moved onto describing the memory layout
of the ZX Spectrum&#39;s display. Finally, we finished with an example of how pixel
and attribute coordinates can be calculated by using a virtual memory mapped
mouse for an example. There are more subtleties involved with the ZX Spectrum&#39;s
graphics that I&#39;ve decided not to go into in this article. In future articles
I&#39;ll be exploring more in-depth graphics programming with 8-bit computers! While
also tying that with more modern technology. Happy hacking!</p>
<textarea class="hljs logiclogue-6502-asm" data-ram-id="example-n" style="width: 100%; height: 200px;">
init:
    JMP loop
set_attributes:
    LDY #$00
    STY $00
    LDX #$58
    STX $01
loop_set_attributes:
    LDA #%00001111
    STA ($00),Y
    INY
    BNE loop_set_attributes
    INC $01
    LDA #$5B
    CMP $01
    BNE loop_set_attributes
    RTS
; (byte pos, byte char), byte *screen_location
draw_char:
    LDA $00
    STA $02
    LDA #$40
    STA $03
    LDY #$00
    ; Load CharMap address into memory
    LDA #<CharMap
    STA $04
    LDA #>CharMap
    STA $05
    ; (char * 8) + CharMap
    LDA $01
    ASL
    ASL
    ASL
    ADC $04
    STA $04
draw_char_line:
    LDA ($04),Y
    LDX #$00
    STA ($02,X)
    INC $03
    INY
    CPY #$08
    BNE draw_char_line
    RTS
loop:
    JSR set_attributes
    LDA #$00
    STA $00
    LDA #$00
    STA $01
    JSR draw_char
    LDA #$01
    STA $00
    LDA #$01
    STA $01
    JSR draw_char
    LDA #$02
    STA $00
    LDA #$02
    STA $01
    JSR draw_char
    JMP loop
CharMap:
    ; Character 'A'
    .byte %00111100  ; Line 1:   00111100
    .byte %01100110  ; Line 2:   01100110
    .byte %01100110  ; Line 3:   01100110
    .byte %01111110  ; Line 4:   01111110
    .byte %01100110  ; Line 5:   01100110
    .byte %01100110  ; Line 6:   01100110
    .byte %01100110  ; Line 7:   01100110
    .byte %00000000  ; Line 8:   00000000
    ; Character 'B'
    .byte %01111100  ; Line 1:   01111100
    .byte %01100110  ; Line 2:   01100110
    .byte %01100110  ; Line 3:   01100110
    .byte %01111100  ; Line 4:   01111100
    .byte %01100110  ; Line 5:   01100110
    .byte %01100110  ; Line 6:   01100110
    .byte %01111100  ; Line 7:   01111100
    .byte %00000000  ; Line 8:   00000000
    ; Character 'C'
    .byte %00111100  ; Line 1:   00111100
    .byte %01100110  ; Line 2:   01100110
    .byte %01100000  ; Line 3:   01100000
    .byte %01100000  ; Line 4:   01100000
    .byte %01100000  ; Line 5:   01100000
    .byte %01100110  ; Line 6:   01100110
    .byte %00111100  ; Line 7:   00111100
    .byte %00000000  ; Line 8:   00000000
</textarea>

<p><canvas class="u-full-width logiclogue-zx-screen" data-ram-id="example-n" width="256" height="192" style="image-rendering: pixelated"></canvas></p>
<h1 id="references-and-acknowledgements">References and Acknowledgements</h1>
<ul>
<li><a href="https://www.npmjs.com/package/6502-emulator">jywlewis&#39; 6502 Emulator</a></li>
<li><a href="https://www.npmjs.com/package/jsasm6502">kktos&#39; 6502 Assembler</a></li>
</ul>
]]></description><link>http://jordanlord.co.uk/blog/6502-part-1-zx-spectrum-experiment</link><guid isPermaLink="true">http://jordanlord.co.uk/blog/6502-part-1-zx-spectrum-experiment</guid><dc:creator><![CDATA[Jordan Lord]]></dc:creator><pubDate>Mon, 03 Feb 2025 00:00:00 GMT</pubDate></item><item><title><![CDATA[Object-oriented Programming in C]]></title><description><![CDATA[<p>Implementing object-orientation in C is a fantastic way to understand how
object-oriented code works at the low level. Of course C++ exists to solve this
very problem. However, C++ arguably has its own problems. Top programmers, <a href="http://harmful.cat-v.org/software/c++/linus">such
as Linus Torvalds</a>, have spoken out
about how C++ is a &quot;horrible language&quot;. It&#39;s easy to fall into the argument of
whether C++ is an incredibly powerful programming language, or whether it leads
to bad code. Quite frankly, I&#39;m not qualified to say. The whole point of this
article is to demonstrate object-orientation in C. So we will avoid the flame
wars, for now.</p>
<h2 id="objects">Objects</h2>
<p>Objects are the key data structures in object-oriented programming. C has the
<code>struct</code> data type to create, what basically are, objects.</p>
<p>Here is an example:</p>
<pre><code class="hljs"><span class="hljs-comment">// Declaration</span>
typedef struct RectangleTag Rectangle;

struct RectangleTag {
    <span class="hljs-built_in">float</span> <span class="hljs-variable">width</span>;
    <span class="hljs-built_in">float</span> <span class="hljs-variable">height</span>;
};

<span class="hljs-comment">// Instantiation</span>
Rectangle <span class="hljs-built_in">rect</span>;

<span class="hljs-built_in">rect</span>.<span class="hljs-variable">width</span> = <span class="hljs-number">4</span>;
<span class="hljs-built_in">rect</span>.<span class="hljs-variable">height</span> = <span class="hljs-number">2</span>;</code></pre>

<p>As you can see, this behaves very similar to an object in other object-oriented
programming languages, such as Java. Let&#39;s just call it an object, for ease of
understanding. However, there are a few problems. For it to be object-oriented,
we&#39;ll need methods that are assigned to the object. Let&#39;s start by creating a
&quot;constructor&quot; function.</p>
<h2 id="constructors-and-destructors">Constructors and Destructors</h2>
<p>A constructor is a type of function that is specifically used to create an
object. In Java and many other object-oriented programming languages, you invoke
the constructor with the <code>new</code> keyword. In the previous example, we created an
object that was allocated to the stack. This isn&#39;t helpful. The details aren&#39;t
important as to why, for now. Instead we are going to allocate the object on the
heap. Then a pointer to that object will be returned from the constructor
function. The C standard library has a function for allocating memory on the
heap; it&#39;s called <code>malloc</code>.</p>
<p>Here is an example of a constructor function for <code>Rectangle</code>:</p>
<pre><code class="hljs"><span class="hljs-preprocessor">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;stdlib.h&gt;</span></span>

<span class="hljs-comment">// Constructor</span>
<span class="hljs-function">Rectangle *<span class="hljs-title">Rectangle_new</span><span class="hljs-params">(<span class="hljs-keyword">float</span> width, <span class="hljs-keyword">float</span> height)</span>
</span>{
    <span class="hljs-comment">// Allocate memory to object</span>
    Rectangle *self = <span class="hljs-built_in">malloc</span>(<span class="hljs-keyword">sizeof</span>(Rectangle));

    <span class="hljs-comment">// Default parameters</span>
    self-&gt;width = width;
    self-&gt;height = height;

    <span class="hljs-comment">// Return pointer to object</span>
    <span class="hljs-keyword">return</span> self;
}</code></pre>

<p>Creating an instance of <code>Rectangle</code> using the constructor function:</p>
<pre><code class="hljs">Rectangle *rect = Rectangle_new(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>);</code></pre>

<p>When you&#39;re allocating memory on the heap, it isn&#39;t deallocated when you go out
of function scope, like it does for objects allocated on the stack. Therefore, a
&quot;destructor&quot; function has to be created, in order to deallocate the object. The
C standard library has a function for cleaning up memory allocated on the heap;
it&#39;s called <code>free</code>. As shown below:</p>
<pre><code class="hljs"><span class="hljs-preprocessor">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;stdlib.h&gt;</span></span>

<span class="hljs-comment">// Destructor</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Rectangle_destroy</span><span class="hljs-params">(Rectangle *self)</span>
</span>{
    <span class="hljs-comment">// Free the memory</span>
    <span class="hljs-built_in">free</span>(self);
}</code></pre>

<p>Although it may seem pointless to have a destructor function if <code>free</code> is just
going to be called, it is important to have a destructor function because
objects may need to clear up more objects that are on that object, if that makes
sense?</p>
<h2 id="methods">Methods</h2>
<p>Methods are very important to object-oriented programming. In Java and many
other object-oriented languages, methods associated with an object reference the
object with the <code>this</code> keyword. In C++, the object&#39;s properties are all in the
method&#39;s scope. In C, we are going to take the Java approach as it is easiest to
implement. A slight tweak: we&#39;ll use <code>self</code> instead of <code>this</code>, since <code>this</code> is a
reserved keyword in C++, which may harm cross compatibility.</p>
<p>To do this, our function&#39;s first parameter will take a pointer to its object.
Below is a sample method for calculating the <code>Rectangle</code>&#39;s area.</p>
<pre><code class="hljs"><span class="hljs-keyword">float</span> Rectangle_get_area(Rectangle *<span class="hljs-keyword">self</span>)
{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>-&gt;width * <span class="hljs-keyword">self</span>-&gt;height;
}</code></pre>

<p>This is used as below. The <code>area</code> variable should be equal to <code>4</code>.</p>
<pre><code class="hljs">Rectangle *rect = Rectangle_new(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>);

<span class="hljs-keyword">float</span> area = Rectangle_get_area(rect);</code></pre>

<p>Just for reference, here is an example of a method for calculating the
perimeter.</p>
<pre><code class="hljs"><span class="hljs-keyword">float</span> Rectangle_get_perimeter(Rectangle *<span class="hljs-keyword">self</span>)
{
    <span class="hljs-keyword">return</span> (<span class="hljs-keyword">self</span>-&gt;width * <span class="hljs-number">2</span>) + (<span class="hljs-keyword">self</span>-&gt;height * <span class="hljs-number">2</span>);
}</code></pre>

<p>There are a few issues with this. The main issue is it is not polymorphic. We
don&#39;t have a method that can be called for all <code>Shape</code>s to calculate that
<code>Shape</code>&#39;s area. On another <code>Shape</code>, the <code>width</code> and <code>height</code> properties may not
exist; the method would fall over when it was called with a <code>Shape</code>.</p>
<h2 id="dynamic-methods">Dynamic Methods</h2>
<p>There are a few issues with our previous method of implementing methods. There
is no method dispatching. No way to decide what method to call depending on the
type of object. We have to do that manually. However, polymorphism is achievable
in C. We must use function pointers on the <code>struct</code>s themselves.</p>
<p>Let&#39;s redeclare our <code>Rectangle</code> <code>struct</code> to have the methods declared on the
<code>struct</code> itself:</p>
<pre><code class="hljs"><span class="hljs-keyword">typedef</span> <span class="hljs-keyword">struct</span> RectangleTag Rectangle;

<span class="hljs-keyword">struct</span> RectangleTag {
    <span class="hljs-keyword">float</span> width;
    <span class="hljs-keyword">float</span> height;

    <span class="hljs-keyword">float</span> (*get_width)(Rectange *<span class="hljs-keyword">self</span>);
    <span class="hljs-keyword">float</span> (*get_perimeter)(Rectange *<span class="hljs-keyword">self</span>);
};</code></pre>

<p>Then the <code>Rectangle</code> constructor has to be updated to assign the static function
(defined earlier) to the <code>*get_width</code> and <code>*get_perimeter</code> function pointers.</p>
<pre><code class="hljs"><span class="hljs-comment">// Constructor</span>
Rectangle *Rectangle_new(<span class="hljs-literal">void</span>)
{
    <span class="hljs-comment">// Allocate memory</span>
    Rectangle *<span class="hljs-built_in">self</span> = malloc(sizeof(Rectangle));

    <span class="hljs-comment">// Default parameters</span>
    <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>width = <span class="hljs-number">2</span>;
    <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>height = <span class="hljs-number">2</span>;

    <span class="hljs-comment">// Methods</span>
    <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>get_width = Rectange_get_width;
    <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>get_perimeter = Rectange_get_perimeter;

    <span class="hljs-keyword">return</span> <span class="hljs-built_in">self</span>;
}</code></pre>

<p>Now the methods can be called dynamically from the object itself.</p>
<pre><code class="hljs">Rectangle *<span class="hljs-built_in">rect</span> = Rectangle_new(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>);

<span class="hljs-built_in">float</span> area = <span class="hljs-built_in">rect</span>-&gt;get_area(<span class="hljs-built_in">rect</span>);</code></pre>

<p>In this example, <code>rect-&gt;get_area(rect)</code> would return <code>4</code>.</p>
<h2 id="inheritance">Inheritance</h2>
<p>In C, it&#39;s pretty simple to do object composition, where one object is
referenced from inside of another. But how to do we do <code>struct</code>-based
inheritance? There isn&#39;t a built in way to do it in C.</p>
<p>Let&#39;s say we want to have a <code>Cube</code> <code>struct</code> that extends the <code>Rectangle</code>
<code>struct</code>, adding the <code>depth</code> property. It&#39;s not possible to do that with
<code>struct</code>s. We could do this:</p>
<pre><code class="hljs"><span class="hljs-keyword">typedef</span> <span class="hljs-keyword">struct</span> RectangleTag Rectangle;

<span class="hljs-keyword">struct</span> RectangleTag {
    <span class="hljs-keyword">float</span> width;
    <span class="hljs-keyword">float</span> height;
};

<span class="hljs-keyword">typedef</span> <span class="hljs-keyword">struct</span> CubeTag Cube;

<span class="hljs-keyword">struct</span> CubeTag {
    <span class="hljs-keyword">float</span> width;
    <span class="hljs-keyword">float</span> height;
    <span class="hljs-keyword">float</span> depth;
};</code></pre>

<p>However, it&#39;s not a good idea to copy to properties over. In addition, you can&#39;t
tell that <code>Cube</code> is actually inheriting from <code>Rectangle</code>.</p>
<p>We are going to solve this problem with macros. Consider this example:</p>
<pre><code class="hljs"><span class="hljs-preprocessor">#<span class="hljs-keyword">define</span> RECTANGLE_PROPS\</span>
    <span class="hljs-keyword">float</span> width;\
    <span class="hljs-keyword">float</span> height;

typedef <span class="hljs-keyword">struct</span> RectangleTag Rectangle;

<span class="hljs-keyword">struct</span> RectangleTag {
    RECTANGLE_PROPS
};

<span class="hljs-preprocessor">#<span class="hljs-keyword">define</span> CUBE_PROPS\</span>
    RECTANGLE_PROPS\
    <span class="hljs-keyword">float</span> depth;

typedef <span class="hljs-keyword">struct</span> CubeTag Cube;

<span class="hljs-keyword">struct</span> CubeTag {
    CUBE_PROPS
};</code></pre>

<p>Here <code>Cube</code> is inheriting from <code>Rectangle</code> using macros and adding the <code>depth</code>
property. Although it&#39;s a little messy, it&#39;s clear that <code>Cube</code> is inheriting
from <code>Rectangle</code>. All that needs to be created is constructors for each
<code>struct</code>.</p>
<p>Sometimes you want to call the parent <code>struct</code>&#39;s constructor. This is done with
the <code>super</code> method in Java. However, in C, if we call the <code>Rectangle_new</code>
function to create a new <code>Cube</code>. It&#39;s going to only allocate enough memory for
the <code>Rectangle</code>. The <code>depth</code> property won&#39;t be allocated. This can cause a
segmentation fault. I like to solve this problem by creating an <code>apply</code> method.
This behaves like a constructor but doesn&#39;t allocate any memory. It just takes a
pointer to the object and assigns its properties appropriately. In fact, the
constructor will call its respective <code>apply</code> method.</p>
<pre><code class="hljs"><span class="hljs-keyword">void</span> Rectangle_apply(Rectangle *self, <span class="hljs-built_in">float</span> <span class="hljs-variable">width</span>, <span class="hljs-built_in">float</span> <span class="hljs-variable">height</span>)
{
    self-&gt;<span class="hljs-variable">width</span> = <span class="hljs-variable">width</span>;
    self-&gt;<span class="hljs-variable">height</span> = <span class="hljs-variable">height</span>;
}

Rectangle *Rectangle_new(<span class="hljs-built_in">float</span> <span class="hljs-variable">width</span>, <span class="hljs-built_in">float</span> <span class="hljs-variable">height</span>)
{
    Rectangle *self = malloc(sizeof(Rectangle));

    Rectangle_apply(self, <span class="hljs-variable">width</span>, <span class="hljs-variable">height</span>);

    <span class="hljs-keyword">return</span> self;
}

<span class="hljs-keyword">void</span> Cube_apply(Cube *self, <span class="hljs-built_in">float</span> <span class="hljs-variable">width</span>, <span class="hljs-built_in">float</span> <span class="hljs-variable">height</span>, <span class="hljs-built_in">float</span> depth)
{
    Rectangle_apply((<span class="hljs-keyword">void</span> *)self, <span class="hljs-variable">width</span>, <span class="hljs-variable">height</span>);

    self-&gt;depth = depth;
}

Cube *Cube_new(<span class="hljs-built_in">float</span> <span class="hljs-variable">width</span>, <span class="hljs-built_in">float</span> <span class="hljs-variable">height</span>, <span class="hljs-built_in">float</span> depth)
{
    Cube *self = malloc(sizeof(Cube));

    Cube_apply(self, <span class="hljs-variable">width</span>, <span class="hljs-variable">height</span>, depth);

    <span class="hljs-keyword">return</span> self;
}</code></pre>

<p>Yes, the function pointers could have been added onto the <code>Rectangle</code> and <code>Cube</code>
<code>struct</code>s. However, the power of that, and proper implementation, you are about
to be shown.</p>
<h2 id="polymorphism">Polymorphism</h2>
<p>Polymorphism is a massive aspect of object-oriented programming. It is possible
to use polymorphism in C, even though inheritance isn&#39;t natively supported. It&#39;s
achieved by having <code>struct</code>s with the same memory layout and using casts to cast
a child <code>struct</code> to its parent <code>struct</code>.</p>
<p>Let&#39;s implement an &quot;abstract class&quot; or &quot;interface&quot;, as they&#39;re called in other
languages. An &quot;interface&quot; is a type of class that isn&#39;t implemented by itself,
but rather by its child classes. In C, interfaces can be thought of as a
template for all child <code>struct</code>s to conform to.</p>
<p>A good example of this, using the previous example of <code>Rectangle</code>, is to create
a <code>Shape</code> which is going to behave as our interface.</p>
<pre><code class="hljs"><span class="hljs-preprocessor">#define SHAPE_PROPS(self_t)\</span>
    <span class="hljs-keyword">float</span> (*get_area)(self_t *<span class="hljs-keyword">self</span>);\
    <span class="hljs-keyword">float</span> (*get_perimeter)(self_t *<span class="hljs-keyword">self</span>);

<span class="hljs-keyword">typedef</span> <span class="hljs-keyword">struct</span> ShapeTag Shape;

<span class="hljs-keyword">struct</span> ShapeTag {
    SHAPE_PROPS(Shape)
};</code></pre>

<p>As you can see, the <code>Shape</code> has the <code>get_area</code> and <code>get_perimeter</code> methods. But
it doesn&#39;t actually implement, like we would do with a constructor. It&#39;s
important that the macro used for an interface is a macro function. This way,
the type can be passed into the function. Allowing for inheritance of methods.</p>
<p>Now let&#39;s create a <code>Rectangle</code> which is going to inherit from this <code>Shape</code>
&quot;interface&quot;.</p>
<pre><code class="hljs"><span class="hljs-id">#define</span> <span class="hljs-function">RECTANGLE_PROPS</span>(self_t)\
    <span class="hljs-function">SHAPE_PROPS</span>(self_t)\
    <span class="hljs-attribute">float</span> <span class="hljs-attribute">width</span>;\
    <span class="hljs-attribute">float</span> <span class="hljs-attribute">height</span>;

typedef struct RectangleTag Rectangle;

struct RectangleTag {
    <span class="hljs-function">RECTANGLE_PROPS</span>(Rectangle)
};</code></pre>

<p>Then the <code>Rectangle</code> constructor must be created, as demonstrated earlier.</p>
<pre><code class="hljs">void Rectangle_apply(Rectangle *<span class="hljs-keyword">self</span>, <span class="hljs-keyword">float</span> width, <span class="hljs-keyword">float</span> height)
{
    <span class="hljs-keyword">self</span>-&gt;get_area = Rectangle_get_area;
    <span class="hljs-keyword">self</span>-&gt;get_perimeter = Rectangle_get_perimeter;

    <span class="hljs-keyword">self</span>-&gt;width = width;
    <span class="hljs-keyword">self</span>-&gt;height = height;
}

Rectangle *Rectangle_new(<span class="hljs-keyword">float</span> width, <span class="hljs-keyword">float</span> height)
{
    Rectangle *<span class="hljs-keyword">self</span> = malloc(<span class="hljs-keyword">sizeof</span>(Rectangle));

    Rectangle_apply(<span class="hljs-keyword">self</span>, width, height);

    <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>;
}</code></pre>

<p>For demonstration purposes, we&#39;re going to create a <code>Circle</code> which will also
conform to the <code>Shape</code> interface.</p>
<pre><code class="hljs"><span class="hljs-preprocessor">#define CIRCLE_PROPS(self_t)\</span>
    SHAPE_PROPS(self_t)\
    <span class="hljs-keyword">float</span> radius;

<span class="hljs-keyword">typedef</span> <span class="hljs-keyword">struct</span> CircleTag Circle;

<span class="hljs-keyword">struct</span> CircleTag {
    <span class="hljs-built_in">CIRCLE_PROPS</span>(Circle)
};</code></pre>

<p>Then the circle&#39;s <code>get_area</code> and <code>get_permieter</code> methods.</p>
<pre><code class="hljs"><span class="hljs-preprocessor">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;math.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">float</span> <span class="hljs-title">Circle_get_area</span><span class="hljs-params">(Circle *self)</span>
</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function">M_PI * <span class="hljs-title">pow</span><span class="hljs-params">(self-&gt;radius, <span class="hljs-number">2</span>)</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">float</span> <span class="hljs-title">Circle_get_perimeter</span><span class="hljs-params">(Circle *self)</span>
</span>{
    <span class="hljs-keyword">float</span> diameter = self-&gt;radius * <span class="hljs-number">2</span>;

    <span class="hljs-keyword">return</span> M_PI * diameter;
}</code></pre>

<p>And finally the constructor:</p>
<pre><code class="hljs">void Circle_apply(Circle *<span class="hljs-keyword">self</span>, <span class="hljs-keyword">float</span> width, <span class="hljs-keyword">float</span> height)
{
    <span class="hljs-keyword">self</span>-&gt;get_area = Circle_get_area;
    <span class="hljs-keyword">self</span>-&gt;get_perimeter = Circle_get_perimeter;

    <span class="hljs-keyword">self</span>-&gt;width = width;
    <span class="hljs-keyword">self</span>-&gt;height = height;
}

Circle *Circle_new(<span class="hljs-keyword">float</span> width, <span class="hljs-keyword">float</span> height)
{
    Circle *<span class="hljs-keyword">self</span> = malloc(<span class="hljs-keyword">sizeof</span>(Circle));

    Circle_apply(<span class="hljs-keyword">self</span>, width, height);

    <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>;
}</code></pre>

<p>Now let&#39;s create a method which prints the area of any <code>Shape</code> to the console.
Thanks to polymorphism and inheritance, this is easy.</p>
<pre><code class="hljs"><span class="hljs-keyword">void</span> print_area(Shape *<span class="hljs-built_in">shape</span>)
{
    <span class="hljs-built_in">float</span> area = <span class="hljs-built_in">shape</span>-&gt;get_area(<span class="hljs-built_in">shape</span>);

    printf(<span class="hljs-string">"Area: %f\n"</span>, area);
}</code></pre>

<p>This method can be called with any type that implements the <code>Shape</code> interface.
This is the power of polymorphism. Now let&#39;s actually call <code>print_area</code>. Make
sure to cast your types, otherwise the compiler will warn you.</p>
<pre><code class="hljs">Rectangle *rect = Rectangle_new(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>);
Circle *circle = Circle_new(<span class="hljs-number">3</span>);

print_area((<span class="hljs-keyword">void</span> *)rect); <span class="hljs-comment">// Prints "Area: 4.000000"</span>
print_area((<span class="hljs-keyword">void</span> *)circle); <span class="hljs-comment">// Prints "Area: 28.274334"</span></code></pre>

<p>Dynamic dispatching in action, in C! What more could anyone want?</p>
<h2 id="dependency-injection">Dependency Injection</h2>
<p>Dependency injection is key to decoupling. Test driven development normally
isn&#39;t easy in C, with everything depending on concretions. However, using the
techniques we have just learnt, it&#39;s very easy.</p>
<p>Let&#39;s say we had an interface which specified a canvas for a game. It&#39;s job is
to draw players. It&#39;s most likely not practical, but good for demonstration
purposes.</p>
<pre><code class="hljs"><span class="hljs-preprocessor">#define CANVAS_PROPS(self_t)\</span>
    <span class="hljs-keyword">void</span> clear_screen(self_t *<span class="hljs-keyword">self</span>);\
    <span class="hljs-keyword">void</span> draw_player(self_t *<span class="hljs-keyword">self</span>, Player *player);\
    <span class="hljs-keyword">void</span> clear_player(self_t *<span class="hljs-keyword">self</span>, Player *player);\
    <span class="hljs-keyword">void</span> update_score(self_t *<span class="hljs-keyword">self</span>, Score *score);

<span class="hljs-keyword">typedef</span> <span class="hljs-keyword">struct</span> CanvasTag Canvas;

<span class="hljs-keyword">struct</span> CanvasTag {
    <span class="hljs-built_in">CANVAS_PROPS</span>(Canvas)
};</code></pre>

<p>Now this canvas can be implemented however we want. We could implement it to
draw the game like <a href="https://en.wikipedia.org/wiki/NetHack">NetHack</a> does. Or
perhaps draw it in 3D, as long as we&#39;re using the correct library.</p>
<p>We&#39;ve got our <code>Game</code> <code>struct</code>. Let&#39;s inject <code>Canvas</code> into the constructor
of <code>Game</code>.</p>
<pre><code class="hljs"><span class="hljs-preprocessor">#define GAME_PROPS(self_t)\</span>
    Canvas *canvas;\
    <span class="hljs-comment">// Other methods and properties can go here</span>

<span class="hljs-keyword">typedef</span> <span class="hljs-keyword">struct</span> GameTag Game;

<span class="hljs-keyword">struct</span> GameTag {
    GAME_PROPS(Game)
};

<span class="hljs-keyword">void</span> Game_apply(Game *<span class="hljs-keyword">self</span>, Canvas *canvas)
{
    <span class="hljs-keyword">self</span>-&gt;canvas = canvas;
    <span class="hljs-comment">// Assign other properties and methods here</span>
}

<span class="hljs-comment">// Constructor</span>
Game *Game_new(Canvas *canvas)
{
    Game *<span class="hljs-keyword">self</span> = malloc(<span class="hljs-keyword">sizeof</span>(Game));

    Game_apply(<span class="hljs-keyword">self</span>, canvas);

    <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>;
}</code></pre>

<p>In any <code>Game</code> method, <code>self-&gt;canvas-&gt;method_name(...)</code> can be called. Yet, it
doesn&#39;t matter how <code>Canvas</code> is implemented, as long as we pass a <code>Canvas</code>
derived object that does implement <code>Canvas</code>. It doesn&#39;t affect our code in
<code>Game</code>. It also makes <code>Game</code> much easier to unit test. This is because mocked
objects of <code>Canvas</code>, instead of proper implementations, can be injected into
<code>Game</code>. That is beyond the scope of this article.</p>
<h2 id="classes">Classes</h2>
<p>Time for a more complete example.</p>
<p>You may have thought earlier, with regards to the destroy method, that it could
be attached to each object. This is an interesting idea. It would mean that all
<code>struct</code>s, that are meant to be classes, should derive from an interface stating
the destroy method. The beauty of this pattern is that you can modify it however
you want. We could even create a <code>clone</code> method which clones the object! Let&#39;s
do that.</p>
<pre><code class="hljs">// <span class="hljs-class"><span class="hljs-keyword">Class</span>.<span class="hljs-title">h</span></span><span class="hljs-preprocessor">
#define CLASS_PROPS(self_t)\</span>
    void (*destroy)(self_t *<span class="hljs-variable">self</span>);\
    self_t *(*clone)(self_t *<span class="hljs-variable">self</span>);

typedef struct ClassTag <span class="hljs-class"><span class="hljs-keyword">Class</span>;</span>

struct ClassTag {
    CLASS_PROPS(<span class="hljs-class"><span class="hljs-keyword">Class</span>)</span>
};</code></pre>

<p>That way all of our classes can inherit. They must implement destroy. I&#39;m going
to show the <code>Rectangle</code> example from earlier. First we&#39;ll have to redeclare
<code>Shape</code>. But this time, we are going to state that <code>Shape</code> has coordinates. So
it will have a property for <code>Coords</code>.</p>
<pre><code class="hljs"><span class="hljs-comment">// Shape.h</span>
<span class="hljs-preprocessor">#define SHAPE_PROPS(self_t)\</span>
    CLASS_PROPS(self_t)\
    Coords *coords;\
    <span class="hljs-keyword">float</span> (*get_area)(self_t *<span class="hljs-keyword">self</span>);\
    <span class="hljs-keyword">float</span> (*get_perimeter)(self_t *<span class="hljs-keyword">self</span>);

<span class="hljs-keyword">typedef</span> <span class="hljs-keyword">struct</span> ShapeTag Shape;

<span class="hljs-keyword">struct</span> ShapeTag {
    SHAPE_PROPS(Shape)
};</code></pre>

<p>Then redeclare <code>Rectangle</code>.</p>
<pre><code class="hljs"><span class="hljs-comment">// Rectangle.h</span>
<span class="hljs-id">#define</span> <span class="hljs-function">RECTANGLE_PROPS</span>(self_t)\
    <span class="hljs-function">SHAPE_PROPS</span>(self_t)\
    <span class="hljs-attribute">float</span> <span class="hljs-attribute">width</span>;\
    <span class="hljs-attribute">float</span> <span class="hljs-attribute">height</span>;

typedef struct RectangleTag Rectangle;

struct RectangleTag {
    <span class="hljs-function">RECTANGLE_PROPS</span>(Rectangle)
};

Rectangle *<span class="hljs-function">Rectangle_new</span>(Coords *coords, <span class="hljs-attribute">float</span> <span class="hljs-attribute">width</span>, <span class="hljs-attribute">float</span> <span class="hljs-attribute">height</span>);
void <span class="hljs-function">Rectangle_apply</span>(
    Rectangle *self, Coords *coords, <span class="hljs-attribute">float</span> <span class="hljs-attribute">width</span>, <span class="hljs-attribute">float</span> <span class="hljs-attribute">height</span>);
void <span class="hljs-function">Rectangle_destroy</span>(Rectangle *self);
Rectangle *<span class="hljs-function">Rectangle_clone</span>(Rectangle *self);
<span class="hljs-attribute">float</span> <span class="hljs-function">Rectangle_get_area</span>(Rectangle *self);
<span class="hljs-attribute">float</span> <span class="hljs-function">Rectangle_get_perimeter</span>(Rectangle *self);</code></pre>

<p>Finally reimplement <code>Rectangle</code>.</p>
<pre><code class="hljs"><span class="hljs-comment">// Rectangle.c</span>
<span class="hljs-variable">#include</span> &lt;stdlib<span class="hljs-built_in">.</span>h&gt;
<span class="hljs-variable">#include</span> <span class="hljs-string">"Class.h"</span>
<span class="hljs-variable">#include</span> <span class="hljs-string">"Shape.h"</span>
<span class="hljs-variable">#include</span> <span class="hljs-string">"Rectangle.h"</span>

Rectangle *Rectangle_new(Coords *coords, float width, float height)
{
    Rectangle *<span class="hljs-built_in">self</span> = malloc(sizeof(Rectangle));

    Rectangle_apply(<span class="hljs-built_in">self</span>, coords, width, height);

    <span class="hljs-keyword">return</span> <span class="hljs-built_in">self</span>;
}

<span class="hljs-literal">void</span> Rectangle_apply(Rectangle *<span class="hljs-built_in">self</span>, Coords *coords, float width, float height)
{
    <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>width = width;
    <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>height = height;
    <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>coords = coords;

    <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>get_area = Rectangle_get_area;
    <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>get_perimeter = Rectangle_get_perimeter;
    <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>clone = Rectangle_clone;
    <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>destroy = Rectangle_destroy;
}

<span class="hljs-literal">void</span> Rectangle_destroy(Rectangle *<span class="hljs-built_in">self</span>)
{
    <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>coords<span class="hljs-subst">-&gt;</span>destroy(<span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>coords);

    free(<span class="hljs-built_in">self</span>);
}

Rectangle *Rectangle_clone(Rectangle *<span class="hljs-built_in">self</span>)
{
    Rectangle *clone = malloc(sizeof(Rectangle));

    Coords *coords_clone = <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>coords<span class="hljs-subst">-&gt;</span>clone(<span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>coords);

    <span class="hljs-keyword">return</span> Rectangle_new(coords_clone, <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>width, <span class="hljs-built_in">self</span><span class="hljs-subst">-&gt;</span>height);
}

<span class="hljs-comment">// Definition of `Rectangle_get_area` and `Rectangle_get_perimeter` here</span></code></pre>

<p>Then creating an instance of <code>Rectangle</code> and destroying it, you know it&#39;s going
to work. It&#39;s pretty self explanatory how <code>Coords</code> would work, so I&#39;m not going
to go into the implementation of it.</p>
<pre><code class="hljs"><span class="hljs-comment">// main.c</span>
<span class="hljs-preprocessor">#<span class="hljs-keyword">include</span> <span class="hljs-string">"Rectangle.h"</span></span>
<span class="hljs-preprocessor">#<span class="hljs-keyword">include</span> <span class="hljs-string">"Coords.h"</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    Coords *coords = Coords_new(<span class="hljs-number">15</span>, <span class="hljs-number">10</span>);
    Rectangle *rect = Rectangle_new(coords, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>);
    Rectangle *rect_2 = rect-&gt;clone(rect);

    <span class="hljs-keyword">float</span> area = rect_2-&gt;get_area(rect);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%f\n"</span>, area); <span class="hljs-comment">// Will print 4</span>

    rect-&gt;destroy(rect); <span class="hljs-comment">// Will call `coords-&gt;destroy`</span>
    rect_2-&gt;destroy(rect); <span class="hljs-comment">// Do the same as above but to rect_2 object</span>

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>

<h2 id="conclusion">Conclusion</h2>
<p>It&#39;s a fantastic exercise implementing object-orientation in C. It better helps
you understand polymorphism with regards to memory management. It better helps
you understand destructors. It better helps you understand constructors. It also
better helps you understand where the <code>this</code> object comes from. With C being low
level, it shows how object-oriented code works at the low level.</p>
<p>There are many drawbacks to this style though. For one, it takes a lot of boiler
plate, just to create a simple class. In addition, C++ has all of these
features, and more, with &quot;nice&quot;, or rather quick, easily written syntax. Maybe
this is one of the issues with C++ the fact that it has too much.</p>
<p>I have written this <a href="https://github.com/logiclogue/connect-four"><code>connect-four</code>
program</a>, which is a simple
command-line program using the principles stated in this article. It also is
totally developed using test-driven development. That&#39;s something that this
paradigm allows.</p>
<p>Anyway, I&#39;d like to think that implementing object-oriented programming, in C
even if it isn&#39;t that practical, is a great way to get a better understanding of
object-oriented code. It certainly was the case for me.</p>
]]></description><link>http://jordanlord.co.uk/blog/object-oriented-programming-in-c</link><guid isPermaLink="true">http://jordanlord.co.uk/blog/object-oriented-programming-in-c</guid><dc:creator><![CDATA[Jordan Lord]]></dc:creator><pubDate>Mon, 01 May 2017 00:00:00 GMT</pubDate></item></channel></rss>