<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tom Horvat on Medium]]></title>
        <description><![CDATA[Stories by Tom Horvat on Medium]]></description>
        <link>https://medium.com/@horvat.tom?source=rss-8340c3529505------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-8_bcu5mnPxf6qKGJoryEg.jpeg</url>
            <title>Stories by Tom Horvat on Medium</title>
            <link>https://medium.com/@horvat.tom?source=rss-8340c3529505------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 22:47:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@horvat.tom/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Make illegal states unrepresentable, until you have to explain them]]></title>
            <link>https://medium.com/@horvat.tom/make-illegal-states-unrepresentable-until-you-cant-b7f10261f7e9?source=rss-8340c3529505------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7f10261f7e9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[type-safety]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Tom Horvat]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 17:04:34 GMT</pubDate>
            <atom:updated>2026-08-30T20:30:19.528Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to decide which constraints belong in your types and which belong in your validator.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p3ht9upB8RhWq1no.png" /></figure><h3>A config file with eight things wrong with it</h3><p>A config file lands with eight things wrong with it. Your loader is built by the book, every constraint in the type system, so it stops on the first one and throws. The person who wrote the config fixes that, re-uploads, and meets the second. Six more after that.</p><p>Fail fast, fail loud. Your loader did both, eight times, one at a time.</p><p><strong>“Make illegal states unrepresentable” optimizes for <em>preventing</em> bad states, but some systems have to <em>explain</em> them, and those two goals pull your type design in opposite directions.</strong></p><h3>Every principle has a range</h3><p><a href="https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/">Parse, don’t validate</a>. Make illegal states unrepresentable. Encode your invariants in the type system, and once a value exists it is valid by construction. Push the mess to the boundary and let the core trust what it is handed. A NonEmptyList can&#39;t be empty. A sealed Payment can&#39;t be Cash and Card at once. Whole categories of defensive checks disappear, and the bugs that hid in them go too.</p><p>Fail fast, fail loud has its own time and place. Early on, when the shape of the thing is still moving and you are the only person who will ever read the error, stopping at the first problem is the cheapest feedback there is. You read the trace, you fix it, you move on.</p><p>It stops fitting the moment the values are entered by someone else and have to agree with each other. From their side, submitting is one step. Fail fast answers it eight separate times, and never once says how many are left.</p><h3>The requirement that breaks it</h3><p>Take for example the loader I’ve been building in Kotlin. It reads campaign configs: a date window, a target segment, a discount, localized copy per market. It has one hard rule: when a config is invalid, it must report <strong>every</strong> violation in a single pass, each as a stable (code, path) pair, rather than failing on the first one it finds. The result type is literally shaped for it:</p><pre>data class ValidationError(<br>    val code: ValidationCode,<br>    val path: String,<br>    val message: String? = null,<br>)<br><br>sealed interface ValidationResult {<br>    data object Valid : ValidationResult<br>    data class Invalid(val errors: List&lt;ValidationError&gt;) : ValidationResult<br>}</pre><p>That requirement hits a wall:</p><blockquote><strong><em>Unrepresentable means fail-fast, by construction.</em></strong></blockquote><p>If you cannot <em>construct</em> the invalid value, you cannot <em>hold</em> it, and if you can’t hold it you can’t inspect it for all eight of its faults. A type that refuses the first mistake has, in the same motion, made the other seven unreportable in the same pass. The very property that makes “unrepresentable” safe, that the value never comes into being, is the property that makes accumulating errors impossible.</p><p>So an error-accumulating validator is not a failure to apply the principle. It’s a requirement the principle cannot express.</p><h3>The split</h3><p>The resolution is to stop treating “type-level” versus “runtime check” as a purity contest and treat it as a routing decision. Every constraint goes to one of two places, by a rule you can state in one line:</p><blockquote><strong><em>Forbid by construction what is total and local. Forbid by validator what is contextual or user-facing.</em></strong></blockquote><p>Routing this way also gives each layer a job it can actually do. The input form stops you typing letters into a number field. The type system stops you writing down a shape that has no meaning. The validator answers the only question left, which is whether a well-formed config makes sense as a whole. That last one is the only guarantee of the three: the form is one input path among several, and the validator has to hold whether the config arrived through your UI, a file, or somebody’s script.</p><p>The two halves of the rule overlap, and the overlap is deliberate. A bounds check on a single field is total and local, so the first half claims it. If that bound is something a person has to be told about, the second half takes it anyway. When both apply, reporting wins.</p><h4>Forbid by construction: total and local</h4><p>When a constraint is about a <em>single field</em> or a <em>closed set of shapes</em>, the type system is exactly right, and you should use it. Case in point, the discount is a sealed hierarchy:</p><pre>@Serializable<br>@JsonClassDiscriminator(&quot;type&quot;)<br>sealed interface Discount {<br>    @Serializable<br>    @SerialName(&quot;PERCENTAGE&quot;)<br>    data class Percentage(val percent: UInt, /* ... */) : Discount<br><br>    @Serializable<br>    @SerialName(&quot;FIXED&quot;)<br>    data class Fixed(val amountMinor: Long, val currency: String, /* ... */) : Discount<br>}</pre><p>A currency (a FIXED concept) on a PERCENTAGE discount is not something the validator rejects. It is something you <em>cannot write down</em>. There is no validation rule for it, because there is no invalid state to catch. This is the principle working perfectly, and I lean on it hard: whenever a shape has disjoint fields keyed by a discriminator, it becomes a sealed hierarchy, precisely so that mismatched combinations never exist.</p><h4>Forbid by validator: contextual or user-facing</h4><p>The other place is for constraints that <em>no local type can hold</em>, or that must be <em>reported</em> rather than <em>prevented</em>. Two flavors:</p><p><strong>Contextual (cross-entity) constraints.</strong> A localized copy entry names a market, but it’s only valid if that market is actually covered <em>by the audience segment this campaign targets</em>. That’s a fact about three entities at once (the copy entry, the campaign that holds it, and the segment it targets). No field type on the copy entry can encode “a market that exists somewhere else in the graph.” So it’s a validator rule, running inside the accumulator where add appends to the error list and index is a prebuilt lookup:</p><pre>val markets = index.marketIdsBySegment[campaign.segmentId]<br>if (markets != null) {<br>    campaign.copy.forEach {<br>        if (it.marketId !in markets)<br>            add(<br>                ValidationError(<br>                    ValidationCode.UNTARGETED_COPY_MARKET,<br>                    &quot;campaign[${campaign.id}].copy[${it.marketId}]&quot;<br>                )<br>            )<br>    }<br>}</pre><p><strong>Deliberately permissive fields.</strong> Some fields are left <em>looser than the domain allows</em>, on purpose, so the violation has a name. Percentage.percent is a UInt, and the type happily permits 120u. The domain caps it at 100, but instead of reaching for a <a href="https://kotlinlang.org/docs/inline-classes.html">Percent value class</a>, I let the value exist and let a validator rule name it:</p><pre>if (discount is Discount.Percentage &amp;&amp; discount.percent &gt; 100u)<br>    add(<br>        ValidationError(<br>            ValidationCode.DISCOUNT_OUT_OF_RANGE,<br>            &quot;campaign[${campaign.id}].discount.percent&quot;<br>        )<br>    )</pre><p>The permissiveness is the point. A value that can exist can be pointed at, and a value that can be pointed at can produce DISCOUNT_OUT_OF_RANGE at path campaign[...].discount.percent, which the form can render next to the offending field. An unconstructable value can&#39;t be pointed at; it can only crash the decoder.</p><h3>What the split buys you</h3><p>This produces a clean two-phase ingestion:</p><ol><li><strong>Decode</strong>: structural only. <a href="https://github.com/Kotlin/kotlinx.serialization">kotlinx.serialization</a> against a strict codec: unknown keys rejected, no lenient coercion, no special float values. This phase answers “is this the right <em>shape</em>?”</li><li><strong>Validate</strong>: semantic, accumulating. The validation rules run over the decoded graph and collect every (code, path). This phase answers &quot;does this shape make <em>sense</em>?&quot;</li></ol><p>Each phase has exactly one job, and the payoffs compound:</p><ul><li><strong>The types stay simple.</strong> Flat data classes, no wrapper types, no hand-written invariants buried in init {} blocks. That matters extra here because these same types <em>are</em> the wire format. Every constructor you&#39;d add for safety is a serialization edge case you&#39;d owe forever.</li><li><strong>Errors become a product surface.</strong> Each ValidationCode plus its path is enough to drive field-level highlighting in the form. The validator isn&#39;t a gate that says &quot;no&quot;; it&#39;s a function that says &quot;here are all eight things to fix, and where each one is.&quot;</li></ul><p>That last part is not a figure of speech. Here is that eight-mistake config, uploaded on 14 April against a segment covering de-DE, en-GB, en-US and es-ES:</p><pre>{<br>  &quot;id&quot;: &quot;promo-spring&quot;,<br>  &quot;window&quot;: { &quot;start&quot;: &quot;2026-04-01&quot;, &quot;end&quot;: &quot;2026-03-25&quot; },<br>  &quot;segmentId&quot;: &quot;seg-eu-shoppers&quot;,<br>  &quot;discount&quot;: { &quot;type&quot;: &quot;PERCENTAGE&quot;, &quot;percent&quot;: 120 },<br>  &quot;copy&quot;: [<br>    { &quot;marketId&quot;: &quot;fr-FR&quot;, &quot;headline&quot;: &quot;Offre de printemps&quot; },<br>    { &quot;marketId&quot;: &quot;en-GB&quot;, &quot;headline&quot;: &quot;Spring offer&quot; },<br>    { &quot;marketId&quot;: &quot;en-GB&quot;, &quot;headline&quot;: &quot;Spring sale&quot; },<br>    { &quot;marketId&quot;: &quot;en-US&quot;, &quot;headline&quot;: &quot;&quot; }<br>  ]<br>}</pre><p>And here is what comes back:</p><pre>WINDOW_ENDS_BEFORE_START   campaign[promo-spring].window<br>WINDOW_ALREADY_ELAPSED     campaign[promo-spring].window<br>DISCOUNT_OUT_OF_RANGE      campaign[promo-spring].discount.percent<br>UNTARGETED_COPY_MARKET     campaign[promo-spring].copy[fr-FR]<br>MISSING_COPY_FOR_MARKET    campaign[promo-spring].copy[de-DE]<br>MISSING_COPY_FOR_MARKET    campaign[promo-spring].copy[es-ES]<br>DUPLICATE_COPY_MARKET      campaign[promo-spring].copy[en-GB]<br>EMPTY_COPY_HEADLINE        campaign[promo-spring].copy[en-US].headline</pre><p>One upload, one pass, eight rows. Note that the code alone isn’t the identity: MISSING_COPY_FOR_MARKET shows up twice, and two different rules land on .window. The pair is what points at a field, which is why the pair is what the validator returns.</p><h3>The cost, honestly</h3><p>This isn’t free, and pretending otherwise would undercut the point.</p><p>The core now trusts a type that <em>can</em> hold a semantically-invalid value in the window between decode and validate. percent really can be 120u in a decoded Campaign object. So you need one piece of discipline: <strong>nothing downstream of validation runs on an</strong> Invalid <strong>result.</strong> The validate() call is the gate; past it, the graph is trusted (and the config is frozen once the campaign goes live, so it can&#39;t drift back into invalidity).</p><p>The other cost is judgment: the rule doesn’t apply itself. Forbid by validator only when the constraint is contextual or must be reported. If a constraint is total, local, <em>and</em> you never need to accumulate, if one violation is genuinely catastrophic to even hold in memory, then reach for the sealed type or the value class. Don’t make something permissive just because you can. Make it permissive when the error needs a name.</p><h3>So where’s the line?</h3><p>“Make illegal states unrepresentable” is not wrong. It’s a tool with a blast radius. Applied to a total, local constraint, it deletes bugs for free. Applied to a constraint your users need <em>explained</em>, it turns an eight-item fix-it list into eight round-trips.</p><p>Both ideas are correct at once: some states should be unrepresentable, and some error sets must be reported whole. The skill is not picking a side. It’s knowing which constraint belongs on which side of the decode/validate line.</p><p><em>Originally published at </em><a href="https://underdroid.hashnode.dev/make-illegal-states-unrepresentable-until-you-have-to-explain-them"><em>https://underdroid.hashnode.dev</em></a><em> on August 30, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7f10261f7e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proto DataStore for Configuration, Room for Entities: Choosing the Right Cache Medium]]></title>
            <link>https://medium.com/@horvat.tom/proto-datastore-for-configuration-room-for-entities-choosing-the-right-cache-medium-ef1891c3707e?source=rss-8340c3529505------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef1891c3707e</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Tom Horvat]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 20:04:58 GMT</pubDate>
            <atom:updated>2026-04-07T20:04:58.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ejf0SGA7rGekNhS06gokvw.png" /></figure><h4>Why ‘local cache’ isn’t one thing, and how matching your persistence layer to your data shape keeps your storage coherent</h4><p>There’s a reflexive tendency in Android development to pick one persistence library and apply it everywhere. You chose Room, so everything goes in Room. You liked DataStore, so now your user preferences, your entity data, and your API cache metadata all live there. It’s not laziness — it’s the reasonable conclusion of “learn the tool well and use it consistently.”</p><p>The problem is that persistence libraries are not general-purpose storage. Each one makes strong assumptions about the <em>shape</em> of the data it handles best, and when your data’s shape doesn’t match those assumptions, you pay in complexity, ceremony, and brittleness. Matching your persistence medium to your data shape isn’t a micro-optimization — it’s a design decision that determines whether your storage layer is coherent or a collection of workarounds.</p><p>This article examines that decision through a concrete lens: proto DataStore for scalar configuration state, Room for relational entity data. Not because these tools happen to be available, but because the <em>nature</em> of each data type demands different guarantees.</p><h3>The Setup</h3><p>Consider a lottery app that caches data from a remote backend. Two kinds of data need to be persisted locally:</p><ol><li>A total applicant count — a single integer representing how many applicants are currently registered in the system. Used to drive draw logic and display aggregate statistics on startup.</li><li>Applicant records — structured records with nested relationships: personal details, a profile picture, submitted application entries, and eligibility status. Queried by ID and assembled into domain models.</li></ol><p>These two look like they could share infrastructure. Both are “local data.” Both are “cache.” But their characteristics diverge sharply once you push past that surface similarity.</p><h3>The Applicant Count: Schema-Evolving Configuration</h3><p>The count is an integer. It has one field. Its primary behavioral requirement is: survive app restarts, survive process death, and be readable before the database is warm. It doesn’t need to be queried. It doesn’t join with anything. It changes infrequently — only when the backend processes new registrations or closes an application window.</p><p>In proto DataStore, this becomes a three-line schema:</p><pre>syntax = &quot;proto3&quot;;<br><br>message Cache {<br>  int32 applicant_count = 1;<br>}</pre><p>And a serializer that bridges the proto format to DataStore’s Serializer&lt;T&gt; interface:</p><pre>object CacheSerializer : Serializer&lt;Cache&gt; {<br>    override val defaultValue: Cache = Cache.getDefaultInstance()<br><br>    override suspend fun readFrom(input: InputStream): Cache {<br>        try {<br>            return Cache.parseFrom(input)<br>        } catch (exception: InvalidProtocolBufferException) {<br>            throw CorruptionException(&quot;&quot;, exception)<br>        }<br>    }<br><br>    override suspend fun writeTo(t: Cache, output: OutputStream) = t.writeTo(output)<br>}</pre><p>Reading the count looks like this:</p><pre>override fun getApplicantCount() = toResultStateFlow {<br>    context.cacheDataStore.data.map { cache -&gt; cache.applicantCount }.first()<br>}</pre><p>No DAO. No table. No query planner. Just a typed read from a file that the DataStore runtime serializes and deserializes.</p><p>What you’re getting from DataStore here isn’t persistence-in-general — it’s a specific set of guarantees that are uniquely appropriate for this kind of data:</p><p>Transactional writes. updateData is atomic. There&#39;s no partial write state. For a single scalar you may not care today, but if Cache grows to hold several configuration fields (the current draw phase, a registration deadline timestamp, a backend API version), the atomicity guarantee means observers never see a half-updated configuration.</p><p>Flow-native reads. cacheDataStore.data is a Flow&lt;Cache&gt;. If the count updates at runtime — say, when a registration window closes and the backend emits a final tally — every collector sees the new value automatically. This isn&#39;t just convenient — it&#39;s architecturally honest. Configuration state <em>is</em> observable, and a persistence layer that models it as such eliminates the boilerplate of invalidation and re-query.</p><p>No schema migration ceremony. When you add a field to Cache, proto3&#39;s binary encoding handles forward and backward compatibility automatically. Field 1 (applicant_count) remains field 1. New consumers can read old files; old consumers can read new files and ignore unknown fields. For configuration data that evolves alongside app updates, this is the right default.</p><p>What you’re <em>not</em> getting is equally important: no indexing, no relational queries, no joins, no partial reads of large datasets. For a single integer, that’s not a missing feature — it’s appropriate minimalism.</p><h3>Applicant Records: Relational Data That Needs to Be Queried</h3><p>Applicant data has a fundamentally different shape. A full applicant record isn’t a scalar — it’s a graph:</p><pre>data class Profile(<br>    @Embedded val applicant: Applicant,<br>    @Relation(parentColumn = &quot;applicantId&quot;, entityColumn = &quot;applicantId&quot;)<br>    val profilePicture: ProfilePicture,<br>    @Relation(parentColumn = &quot;applicantId&quot;, entityColumn = &quot;applicantId&quot;)<br>    val applications: List&lt;Application&gt;,<br>    @Relation(parentColumn = &quot;applicantId&quot;, entityColumn = &quot;applicantId&quot;)<br>    val eligibility: Eligibility,<br>)</pre><p>Four related entities, assembled by ID: personal details, a profile photo, one or more submitted application records, and an eligibility record that tracks draw history and disqualification status. The data isn’t just stored; it’s <em>queried</em>, filtered by draw round, and assembled from normalized tables.</p><p>Room’s @Transaction annotation guarantees that getProfileById assembles the full applicant record atomically — applicant, profilePicture, applications, and eligibility are fetched in one consistent snapshot, not four separate reads that could interleave with concurrent writes. For relational data with dependent rows, this is a meaningful correctness guarantee, not just a performance hint. An applicant mid-update should never appear partially modified to a reader.</p><p>Room also handles write fan-out. When an applicant record is fetched from the backend, its components are saved across separate DAO operations, each targeting a different table:</p><pre>private suspend fun cacheRemoteApplicant(details: ApplicantDetails) {<br>    supervisorScope {<br>        val saveOperations: List&lt;Pair&lt;String, suspend () -&gt; Unit&gt;&gt; = listOf(<br>            &quot;applicant&quot;      to { local.saveApplicant(details.applicant) },<br>            &quot;profilePicture&quot; to { local.saveProfilePicture(details.profilePicture) },<br>            &quot;applications&quot;   to { local.saveApplications(details.applications) },<br>            &quot;eligibility&quot;    to { local.saveEligibility(details.eligibility) },<br>        )<br><br>        saveOperations.forEach { (name, action) -&gt;<br>            launch(dispatchers.io) {<br>                try { action() }<br>                catch (e: Exception) { Timber.e(e, &quot;Error caching $name&quot;) }<br>            }<br>        }<br>    }<br>}</pre><p>This is only expressible cleanly because Room operates at the table level, not the file level. You can write to Applicant, ProfilePicture, and Application independently, in parallel, without corrupting each other&#39;s data. DataStore — operating on a single serialized file — would require serializing these writes, giving up the parallelism, or batching everything into one atomic blob, giving up the normalized structure.</p><h3>What the Split Actually Encodes</h3><p>Using two persistence mechanisms here isn’t tooling diversity for its own sake. Each choice encodes a specific data contract:</p><p><strong>Proto DataStore (Cache)</strong></p><ul><li>Structure: flat, scalar</li><li>Access: whole-object read/write</li><li>Schema evolution: proto3 binary compatibility</li><li>Writes: atomic per-message</li><li>Reads: full object or nothing</li><li>Concurrency: single-writer guaranteed</li></ul><p><strong>Room (Applicant.Profile)</strong></p><ul><li>Structure: relational, nested</li><li>Access: query by ID, partial assembly</li><li>Schema evolution: SQL migrations</li><li>Writes: per-table, transactional</li><li>Reads: partial projections possible</li><li>Concurrency: multi-table parallel writes</li></ul><p>When the data fits the left column, DataStore wins. When it fits the right, Room wins. Forcing either into the wrong column means fighting the tool’s assumptions instead of leveraging them</p><h3>The Pattern Worth Generalizing</h3><p>The underlying principle is: persistence mechanism selection is a question about data shape, not familiarity. Ask these three questions before reaching for your default:</p><ol><li>Is the data flat or relational? Flat config belongs in DataStore or SharedPreferences; anything with foreign keys belongs in a relational store.</li><li>Is it queried or retrieved whole? DataStore is all-or-nothing per message. If you need WHERE clauses, Room is the right tool.</li><li>How does it evolve? Proto3’s schema compatibility is low-friction for configuration. SQL migrations are more powerful but require explicit version management — appropriate for structured entity data, overkill for a count field.</li></ol><p>This isn’t an argument for proliferating persistence libraries. It’s an argument for recognizing that “local cache” isn’t one thing, and that the abstraction level at which you think about it — “I need to store this” — is too coarse to make the right architectural choice.</p><p>A single-field proto message and a multi-table Room schema can coexist in the same codebase not as a sign of indecision, but as an honest acknowledgment that the data they store is genuinely different — and that treating it as the same thing would mean compromising one or both.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef1891c3707e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-Referential Generics in Kotlin: When Type Safety Requires Talking to Yourself]]></title>
            <link>https://medium.com/@horvat.tom/self-referential-generics-in-kotlin-when-type-safety-requires-talking-to-yourself-ec096cbd84cc?source=rss-8340c3529505------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec096cbd84cc</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Tom Horvat]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 21:50:39 GMT</pubDate>
            <atom:updated>2026-04-01T21:50:39.246Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to bridge ViewModel type erasure using reified parameters and sealed classes.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOBKr8p2OPwRIw6JY3PUuQ.png" /></figure><p>Kotlin’s type system is expressive enough to let you write code that is simultaneously statically typed, runtime validated, and ergonomic at the call site. That combination usually requires some machinery — and understanding <em>why</em> the machinery exists, rather than just how to copy it, is the difference between architecture and cargo-culting.</p><p>For reference, we will use the <a href="https://github.com/Tom-Horvat/RandomPokemon">RandomPokemon</a> repo.</p><p>The BaseViewModel in this codebase is a clean example of a pattern where self-referential generics, reified type parameters, and a sealed class hierarchy solve a real problem at a boundary where compile-time types naturally blur.</p><p>An implementation like this enforces a single, standardized way to consume use case output that makes type mismatches observable before they reach production.</p><h3>The Problem at the UI/Domain Boundary</h3><p>ViewModels sit at a boundary between two distinct <em>type</em> worlds. The domain layer produces ResultState — a sealed class that carries either a message, an error, or a payload typed as Any?:</p><pre>sealed class ResultState {<br>    data class Running(val message: String? = null) : ResultState()<br>    data class Error(val error: Throwable? = null) : ResultState()<br>    data class Complete&lt;out O&gt;(val data: O?) : ResultState()<br>}</pre><p>The UseCase&lt;in O&gt; abstraction wraps this in a StateFlow&lt;ResultState?&gt;, where O is the expected output type:</p><pre>abstract class UseCase&lt;in O&gt;(private val logger: Logger? = null) {<br>    <br>    abstract val name: String    <br>    private val _state = MutableStateFlow&lt;ResultState?&gt;(null)<br>    val state: StateFlow&lt;ResultState?&gt; = _state<br><br>    protected fun running(message: String? = null) {<br>        logger?.d(&quot;Running $name: $message&quot;)<br>        _state.value = ResultState.Running(message = message)<br>    }<br><br>    protected fun Throwable?.update() {<br>        logger?.e(this ?: Throwable(), &quot;Error in $name&quot;)<br>        _state.value = ResultState.Error(error = this)<br>    }<br><br>    protected fun O?.update() {<br>        logger?.d(&quot;Completed $name: $this&quot;)<br>        _state.value = ResultState.Complete&lt;O&gt;(data = this)<br>    }<br>    // ...<br>}</pre><p>The variance declarations here are intentional and worth noting: Complete&lt;out O&gt; is covariant because ResultState <em>produces</em> values of type O (you read .data out of it), while UseCase&lt;in O&gt; is contravariant because a use case <em>consumes</em> O to update its state (via protected fun O?.update()) — it never hands O back to a caller. If you try to implement this pattern and swap the variance annotations, the compiler will tell you exactly where the flow of data breaks.</p><p>Notice that O is a contravariant input type parameter (used only in protected fun O?.update()), but the exposed StateFlow is typed to ResultState? — the O is erased at the boundary. By the time the ViewModel receives useCase.state, it has no compile-time knowledge of what type is inside ResultState.Complete.</p><p>This is inherent to the architecture. Use cases communicate via a shared ResultState channel, which must be typed to the sealed class rather than each use case&#39;s specific output type. You can&#39;t parameterize StateFlow over a generic that varies per use case if the ViewModel holds multiple use cases simultaneously.</p><p>So, where do you recover type safety, and at what cost?</p><h3>The ViewModel’s Generic Parameter</h3><p>BaseViewModel is generic over its own state model:</p><pre>open class BaseViewModel&lt;M : ViewModelState&gt;(initialState: M) : ViewModel(), KoinComponent {<br>    private val _state: MutableStateFlow&lt;M&gt; = MutableStateFlow(initialState)<br>    val state: StateFlow&lt;M&gt; = _state.asStateFlow()<br><br>    protected fun updateState(transform: (M) -&gt; M) {<br>        _state.update(transform)<br>    }<br>}</pre><p>The M : ViewModelState bound means the ViewModel&#39;s <em>own</em> state (the UI state model) is typed. This is the self-referential part: HomeViewModel extends BaseViewModel&lt;HomeState&gt;, binding M to HomeState. The updateState lambda then gives subclasses a type-safe transformation — transform: (HomeState) -&gt; HomeState — rather than an untyped mutation.</p><p>This is a well-understood pattern. The interesting part is how collectUseCase operates across <em>both</em> generic contexts — and what it enforces.</p><h3>Two Generics, One Function</h3><pre>protected inline fun &lt;reified O&gt; UseCase&lt;O&gt;.collectUseCase(<br>    crossinline onRunning: (String?) -&gt; Unit = {},<br>    crossinline onError: (Throwable?) -&gt; Unit = { e -&gt; onUseCaseError(e) },<br>    crossinline onDone: suspend (O?) -&gt; Unit = {}<br>) = viewModelScope.launch {<br>    this@collectUseCase.state.collect {<br>        it?.let {<br>            it.parse&lt;O&gt;(<br>                onError = { e -&gt; onError(e) },<br>                onRunning = { m -&gt; onRunning(m) },<br>            ) { result -&gt; onDone(result) }<br>        }<br>    }<br>}</pre><p>This extension function on UseCase&lt;O&gt; is declared <em>inside</em> BaseViewModel&lt;M&gt;. It introduces its own generic parameter O (reified), independent of the class-level M. The function has access to viewModelScope (from the enclosing BaseViewModel context) while O is the expected output type of the specific use case being collected.</p><p>The call site looks like this:</p><pre>getPokemon.collectUseCase&lt;PokemonDetails&gt;(<br>    onRunning = { updateState { it.copy(loading = true) } },<br>    onError   = { e -&gt; updateState { it.copy(error = e) } }<br>) { details -&gt; updateState { it.copy(pokemon = details) } }</pre><p>The compiler infers O = PokemonDetails from the reified type parameter. Inside onDone, result is PokemonDetails? — statically typed. No cast at the call site.</p><p>The type recovery happens inside ResultState.parse&lt;O&gt;:</p><pre>inline fun &lt;reified O&gt; parse(<br>    onRunning: (String?) -&gt; Unit = {},<br>    onError: (Throwable?) -&gt; Unit = {},<br>    onComplete: (O?) -&gt; Unit = {},<br>) {<br>    when (this) {<br>        is Running -&gt; onRunning(this.message)<br>        is Error   -&gt; onError(this.error)<br>        is Complete&lt;*&gt; -&gt; this.data?.let {<br>            it.takeIf { it is O }<br>                ?.let { result -&gt; onComplete(result as O?) }<br>                ?: run { onError(IllegalArgumentException(<br>                    &quot;Expected output of type ${O::class.simpleName}; got ${data?.let { data::class.simpleName }}&quot;<br>                )) }<br>        } ?: run { onComplete(null) }<br>    }<br>}</pre><p>The Complete&lt;*&gt; star projection in the when branch is not stylistic — it&#39;s required by the JVM&#39;s type erasure. Writing is Complete&lt;O&gt; is illegal at runtime because the generic parameter is erased; the JVM only sees Complete, not Complete&lt;PokemonDetails&gt;. The star projection is an honest acknowledgment of that: &quot;I know this is a Complete, but I can&#39;t assert what it contains yet.&quot; The payload type is recovered one step later, inside the branch, where takeIf { it is O } uses the reified type token to perform the actual check. This two-step dance — structural match via star projection, then type recovery via reification — is the idiomatic Kotlin solution to the erasure problem at sealed class boundaries.</p><p>If the data is the expected type, the cast is safe, and onComplete receives a typed value. If not, the mismatch is routed to onError as an IllegalArgumentException with a diagnostic message naming both the expected and actual type.</p><h3>A Single Entry Point as a Standard</h3><p>Before examining the type mechanics in detail, it’s worth stepping back and recognizing what collectUseCase is doing at the team level: it is the <em>only</em> sanctioned way to consume a use case in this codebase.</p><p>That’s not a coincidence, and it’s not just ergonomics. Every developer writing a new ViewModel hits the same function, receives the same structure, and is guided towards the same three concerns: what happens while loading, what happens on failure, and what happens on success. There is no alternative path — no way to collect { state -&gt; ... } raw ResultState directly in a ViewModel without bypassing the base class entirely or going through the ceremony of exposing the use case state for collection within a viewModelScope.launch block. This <em>meta-contract</em> is strictly a team-level decision, and is by no means religiously enforced. Rather, it is the teams&#39; agreed-upon convention aimed at readability, convenience, and standardization across potential verticals.</p><p>This matters for code review and maintenance in a way that documentation never can. You can write a coding standard that says “always handle the running and error states.” You can also write collectUseCase, which makes not handling them an active decision that requires extra effort. The default onError implementation is:</p><pre>crossinline onError: (Throwable?) -&gt; Unit = { e -&gt; onUseCaseError(e) }</pre><p>onUseCaseError logs the throwable. A developer who forgets to pass an onError handler doesn&#39;t silently swallow failures — the fallback ensures breakage is still observed, just in logcat rather than the UI. Omitting error handling is now a deliberate downgrade, not an oversight.</p><p>The explicit type annotation at the call site — collectUseCase&lt;PokemonDetails&gt; — is also load-bearing as communication. It&#39;s documentation that can&#39;t become stale: whoever reads this call knows exactly what the ViewModel expects this use case to produce, without navigating to the use case&#39;s definition. It turns a consumption pattern into a declaration of intent.</p><h3>What “Reified as a Bridge” Means in Practice</h3><p>Reified type parameters exist specifically to recover type information that is erased at runtime. Kotlin erases generic types — a List&lt;String&gt; and a List&lt;Int&gt; are the same List at runtime. Reification retains the type token, making O::class and is O valid at runtime in inline functions.</p><p>The pattern here uses reification to bridge two type worlds:</p><ul><li><strong>Compile-time world:</strong> UseCase&lt;PokemonDetails&gt; — the use case is typed to its output.</li><li><strong>Runtime world:</strong> StateFlow&lt;ResultState?&gt; — type information is erased at the shared channel level.</li><li><strong>Recovery point:</strong> parse&lt;O&gt;() — reification reconstructs the type token at the collection site.</li></ul><p>This bridge appears at the UI/domain boundary because that’s where the erasure is intentional. The ResultState channel <em>should</em> be untyped at the ViewModel level — you want to collect multiple use cases with different output types through a single mechanism. Reification lets you express &quot;I expect this to be of type O&quot; at the point where you actually consume the value, without forcing every use case through a differently-typed channel.</p><h3>The Path of Breakage</h3><p>This is where the pattern earns most of its justification, and it’s worth being precise about.</p><p>Consider what happens without parse&lt;O&gt;(). The raw alternative at the ViewModel collection site would look something like:</p><pre>useCase.state.collect { state -&gt;<br>    when (state) {<br>        is ResultState.Complete&lt;*&gt; -&gt; {<br>            val data = state.data as? PokemonDetails  // as? cast<br>            if (data != null) updateState { it.copy(pokemon = data) }<br>        }<br>        // ...<br>    }<br>}</pre><p>The as? cast is the failure mode. If state.data is actually a PokemonDto — because a mapping step was accidentally skipped somewhere in the call chain — the cast returns null silently. The UI receives a copy(pokemon = null). Nothing renders. There is no error. No log. No stack trace. A developer debugging this sees a blank screen and starts at square one.</p><p>The parse&lt;O&gt;() approach routes that same mismatch differently:</p><pre>it.takeIf { it is O }<br>    ?.let { result -&gt; onComplete(result as O?) }<br>    ?: run { onError(IllegalArgumentException(<br>        &quot;Expected output of type ${O::class.simpleName}; got ${data?.let { data::class.simpleName }}&quot;<br>    )) }</pre><p>The same scenario — PokemonDto where PokemonDetails was expected — now produces an IllegalArgumentException with the message: <em>&quot;Expected output of type PokemonDetails; got PokemonDto.&quot;</em> That exception is passed to onError, which routes it to the ViewModel&#39;s error state, which renders an error in the UI.</p><p>The difference in diagnosability is significant. In QA or during local testing, a visible error with a type name in the message points immediately to the mapping layer. The developer knows which use case is involved (they called getPokemon.collectUseCase&lt;PokemonDetails&gt;), what was expected (PokemonDetails), and what was actually received (PokemonDto). The breakage surface is named, localized, and actionable before the code ever reaches a release branch.</p><p>This is the pattern’s core value proposition: <strong>type mismatches that would silently corrupt state instead generate observable, diagnosable failures during development.</strong> The system doesn’t prevent the upstream bug — a wrong mapping is still a wrong mapping — but it ensures the downstream symptom is never a mystery. There’s a clear and consistent path from breakage to identification.</p><p>It also means the pattern scales with the codebase. As more use cases are added, each one follows the same contract. A refactor that changes GetPokemon to return PokemonSummary instead of PokemonDetails doesn&#39;t silently break the ViewModel — it loudly breaks at runtime the first time the use case is collected, with a message that names exactly what changed. The type annotation at the call site becomes a lightweight contract test.</p><h3>The Residual Cost</h3><p>Naming these benefits doesn’t erase the genuine trade-offs.</p><p><strong>The type check remains runtime, not compile-time.</strong> The compiler cannot catch a mismatch between UseCase&lt;PokemonDto&gt; emitting into collectUseCase&lt;PokemonDetails&gt;. The type guard catches it, but during testing, not during compilation. If your test coverage of the happy-path data flow is thin, the mismatch can reach a release build.</p><p><strong>The </strong>inline<strong> declaration has a direct impact on unit testing.</strong> Because collectUseCase is inline, MockK and Mockito cannot mock or spy on it at the function level — you can&#39;t assert &quot;was collectUseCase called with the right type.&quot; In practice, this turns out to be a non-issue, and arguably a nudge in the right direction: you test the ViewModel by emitting ResultState values from a fake UseCase.state flow and asserting on the resulting ViewModel.state. Since state is a plain StateFlow&lt;ResultState?&gt;, wiring a test double is straightforward — every { useCase.state } returns MutableStateFlow(ResultState.Complete(pokemonDetails)) — and testing the output rather than the wiring is a more meaningful assertion anyway. The one place this becomes relevant is verifying error routing: emitting a ResultState.Complete containing the wrong type (e.g., PokemonDto instead of PokemonDetails) in a test will confirm that onError is invoked with the IllegalArgumentException, giving you a concrete test for the contract the pattern promises.</p><p><strong>Inline functions with crossinline lambdas have constraints.</strong> The crossinline onDone parameter cannot use non-local returns or call suspend functions directly without explicit suspend on the lambda type. The signature accounts for this — onDone: suspend (O?) -&gt; Unit — but it&#39;s a constraint the caller must be aware of.</p><p><strong>Three simultaneous generic contexts add cognitive load.</strong> A HomeViewModel calling getPokemon.collectUseCase&lt;PokemonDetails&gt; is in BaseViewModel&lt;HomeState&gt; (class generic), calling an extension on UseCase&lt;PokemonDetails&gt; (receiver generic), with its own reified O = PokemonDetails (function generic). That&#39;s a lot to hold at once for someone unfamiliar with the pattern.</p><p>These costs are real. They’re also bounded: the cognitive overhead is paid once when learning the pattern, the compile-time limitation is mitigated by the runtime guard, and the crossinline constraints are surfaced immediately by the compiler when you try to violate them.</p><h3>When This Pattern Earns Its Complexity</h3><p>The pattern is justified when all three of the following are true:</p><ol><li>You have a shared communication channel that must erase type information (a StateFlow&lt;SealedBase?&gt;).</li><li>Consumers need typed access to the payload on the other side (arguably the most important constraint).</li><li>Silent type failures are unacceptable — mismatches should be observable and diagnosable (Also, just good practice).</li></ol><p>If your use cases emit a different sealed class per output type, you don’t need this — the types are preserved all the way to the consumer. If as?-with-null is an acceptable failure mode, you don&#39;t need the runtime guard. If the team is small enough that shared conventions can be maintained by proximity, the enforced entry point is just overhead.</p><p>But if you’re building a ViewModel layer that will be extended by multiple developers across a growing feature set — where the distance between “use case author” and “ViewModel author” creates risk — the combination of a single enforced collection mechanism + explicit type declaration + diagnostic failure routing is a structural answer to a coordination problem. It turns what could be a verbal convention (“always annotate the expected type,” “always handle errors”) into something the codebase enforces on its own.</p><p>Type safety through a type-erased channel isn’t a contradiction. It’s a deliberate choice about where to bear the cost of erasure, made in favor of visibility over silence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec096cbd84cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lean Caching]]></title>
            <link>https://medium.com/@horvat.tom/lean-caching-3c9df00575e1?source=rss-8340c3529505------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c9df00575e1</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Tom Horvat]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 04:35:11 GMT</pubDate>
            <atom:updated>2026-03-26T04:48:52.624Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Custom NetworkBoundResource in Kotlin</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zr2iqZZ3PSUcovkC" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Orchestrating data between a remote API and a local database is a foundational problem in mobile development. While the industry consensus rightly leans toward the <strong>Single Source of Truth</strong> pattern, the implementation often degrades into massive, fragile repository classes littered with boilerplate try-catch blocks and manual thread switching.</p><p>Solving this does not require a heavy, third-party state-management library. A clean, generic networkBoundResource built with Kotlin Flows and Coroutines is highly effective, provided you leverage Kotlin&#39;s advanced language features correctly.</p><p>Let me explain by demonstrating this pattern in my <a href="https://github.com/Tom-Horvat/RandomPokemon">RandomPokemon</a> project. By focusing on reified generics, inline functions, and <strong>structured concurrency</strong>, I’ve created a highly <em>fault-tolerant</em> data layer that I drop into my projects to handle caching without the bloat.</p><h3>State Representation: Rethinking ResultState</h3><p>Orchestrating complex data flows requires a strict contract for state representation. A standard sealed class handles the basic loading, success, and error states, but the mechanism used to unwrap that state dictates the cleanliness of the presentation layer. The versatility of the ResultState lends itself well to be used in API call returns, I/O operations, or for use cases being observed by the ViewModel.</p><pre>sealed class ResultState {<br>    data class Complete&lt;out O&gt;(val data: O?) : ResultState()<br>    data class Running(val message: String? = null) : ResultState()<br>    data class Error(val error: Throwable? = null) : ResultState()<br>    <br>    inline fun &lt;reified O&gt; parse(<br>        onRunning: (String?) -&gt; Unit = {},<br>        onError: (Throwable?) -&gt; Unit = {},<br>        onComplete: (O?) -&gt; Unit = {},<br>    ) {<br>        when (this) {<br>            is Running -&gt; onRunning(this.message)<br>            is Error -&gt; onError(this.error)<br>            is Complete&lt;*&gt; -&gt; this.data?.let {<br>                it.takeIf { it is O }?.let { result -&gt; onComplete(result as O?) }<br>                    ?: run { onError(IllegalArgumentException(&quot;Expected output of type ${O::class.simpleName}; got ${data?.let { data::class.simpleName }}&quot;)) }<br>            } ?: run { onComplete(null) }<br>        }<br>    }<br>}</pre><p>Standard state implementations often force the caller to write repetitive when statements and perform unsafe casts in the UI or ViewModel. I intentionally avoid this by relying on the inline fun parse function to safely handle type checking and casting at runtime. If the type does not match, it gracefully routes to the onError block, preventing an abrupt ClassCastException and keeping the app&#39;s crash-free rate intact.</p><h3>The Orchestrator: networkBoundResource</h3><p>My core orchestrator is a single, highly optimized function. Relying heavily on inline and crossinline, it eliminates the runtime overhead associated with the higher-order functions passed into it.</p><pre>inline fun &lt;reified DomainType, reified DtoType&gt; networkBoundResource(<br>    crossinline query: () -&gt; Flow&lt;ResultState&gt;,<br>    crossinline fetch: suspend () -&gt; ResultState,<br>    crossinline saveFetchResult: suspend (DtoType) -&gt; Unit,<br>    crossinline shouldFetch: (DomainType?) -&gt; Boolean = { it == null },<br>    crossinline mapDtoToDomain: (DtoType) -&gt; DomainType,<br>    crossinline onCachePresent: () -&gt; Unit = {}<br>) = flow {<br>    emit(ResultState.Running(&quot;Checking cache...&quot;))<br>    val cachedDataResult = query().last()<br>    var cachedData: DomainType? = null<br><br><br>    cachedDataResult.parse&lt;DomainType&gt;(<br>        onError = { Timber.w(it, &quot;Cache returned an error.&quot;) }<br>    ) { cachedData = it }<br><br>    if (shouldFetch(cachedData)) {<br>        emit(ResultState.Running(&quot;Cache miss. Fetching from remote...&quot;))<br><br>        when (val remoteResult = fetch()) {<br>            is ResultState.Complete&lt;*&gt; -&gt; {<br>                val dto = remoteResult.data as? DtoType<br><br>                if (dto != null) {<br>                    emit(ResultState.Complete(mapDtoToDomain(dto)))<br><br>                    supervisorScope {<br>                        launch {<br>                            try {<br>                                saveFetchResult(dto)<br>                            } catch (e: Exception) {<br>                                Timber.e(e, &quot;Failed to save network resource to cache.&quot;)<br>                            }<br>                        }<br>                    }<br>                } else {<br>                    emit(ResultState.Error(IllegalStateException(&quot;Type mismatch: Remote fetch did not return the expected DTO.&quot;)))<br>                }<br>            }<br>            is ResultState.Error -&gt; emit(remoteResult)<br>            is ResultState.Running -&gt; emit(remoteResult)<br>        }<br>    } else {<br>        onCachePresent()<br>        emit(ResultState.Complete(cachedData!!))<br>    }<br>}</pre><p>Two specific architectural decisions drive this implementation, focusing on performance and fault tolerance:</p><ol><li><strong>Immediate UI Emissions:</strong> When the remote fetch succeeds, the code emits the Complete state before initiating the database save. Disk I/O is slow. Forcing the UI to wait for Room to finish inserting records is an unnecessary bottleneck. The user gets the mapped domain model instantly.</li><li><strong>Detached Caching:</strong> Launching saveFetchResult inside a supervisorScope acts as a defensive shield. If the database insertion fails due to a constraint violation or disk issue, the exception is caught and logged by Timber. The overarching coroutine running the Flow does not crash, and the UI retains the successfully fetched in-memory data.</li></ol><h3>Implementation: Concurrent Caching</h3><p>An abstraction is only as effective as its call site. Integrating this into my PokemonRepoImpl demonstrates how I handle complex, relational data saving without blocking the thread.</p><pre>class PokemonRepoImpl(<br>    private val remote: PokemonRepo.Remote,<br>    private val local: PokemonRepo.Local,<br>    private val dispatchers: DispatcherProvider<br>) : PokemonRepo {<br>    override fun getPokemonById(id: Long) = networkBoundResource&lt;PokemonDetails, PokemonDto&gt;(<br>        query = { local.getPokemonById(id) },<br>        fetch = { remote.getPokemonById(id).last() },<br>        saveFetchResult = { dto -&gt; cacheRemotePokemon(dto.toDomainModel()) },<br>        mapDtoToDomain = { dto -&gt; dto.toDomainModel() }<br>    )<br><br>    private suspend fun cacheRemotePokemon(details: PokemonDetails) {<br>        supervisorScope {<br>            val saveOperations: List&lt;Pair&lt;String, suspend () -&gt; Unit&gt;&gt; = listOf(<br>                &quot;pokemon&quot; to { local.savePokemon(details.pokemon) },<br>                &quot;cries&quot; to { local.saveCries(details.cries) },<br>                &quot;sprites&quot; to { local.saveSprites(details.sprites) },<br>                &quot;abilities&quot; to { local.saveAbilities(details.abilities) }<br>            )<br><br>            saveOperations.forEach { (name, action) -&gt;<br>                launch(dispatchers.io) {<br>                    try {<br>                        action()<br>                    } catch (e: Exception) {<br>                        Timber.e(e, &quot;Error caching $name&quot;)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Mapping a large API payload to a relational database requires splitting the data into multiple tables. Executing these inserts sequentially scales poorly.</p><p>By wrapping the inserts in a supervisorScope and iterating through a list of saveOperations with launch(dispatchers.io), this repository performs concurrent database inserts. More importantly, the supervisorScope ensures fault isolation. If the API returns a malformed URL for a sprite that violates a database constraint, that specific coroutine fails and logs an error, but the parent scope remains active, allowing the pokemon, cries, and abilities to be cached successfully.</p><h3>Final Thoughts</h3><p>This implementation is my take on a pragmatic approach to Android architecture. Combining reified generics for type safety, inline functions for zero-overhead abstractions, and structured concurrency for fault-tolerant caching - yields a repository layer that is highly readable and extremely resilient. It solves a universal problem by leaning on the language, entirely avoiding the need for bloated external dependencies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c9df00575e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Copying Gradle Code]]></title>
            <link>https://medium.com/@horvat.tom/stop-copying-gradle-code-eb654a15be36?source=rss-8340c3529505------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb654a15be36</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[multi-module-project]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[gradle]]></category>
            <dc:creator><![CDATA[Tom Horvat]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 04:15:30 GMT</pubDate>
            <atom:updated>2026-03-28T01:46:34.351Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Copying Gradle Code — A Practical Guide to Convention Plugins</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J2034ppqmyl8rku0GcyNKA.png" /></figure><p>If you’ve worked on a multi-module Android project, you know the pain: build.gradle.kts files multiplying like rabbits, each containing the exact same Android compileSdk, Kotlin compiler options, and Compose configurations. When you need to bump a version or change a compiler flag, you end up doing a massive &quot;Find and Replace&quot; across 20 different modules.</p><p>We know we shouldn’t copy and paste application code, yet we routinely accept copy-pasting our build configuration.</p><p>It’s time to stop. In this article, we’ll explore how to use a build-logic module to create custom Gradle convention plugins. By moving boilerplate out of your module-level build files, you can enforce consistency across your entire project and make maintaining your build system a breeze.</p><p>To demonstrate, we will reference a real-world implementation from the <a href="https://github.com/Tom-Horvat/RandomPokemon">RandomPokemon</a> repository.</p><h3>The “After” Picture: A Clean app/build.gradle.kts</h3><p>Before we look at how to build convention plugins, let’s look at why we want them.</p><p>Here is what the final app/build.gradle.kts looks like after migrating to convention plugins:</p><pre>plugins {<br>    // Plugins<br>    id(&quot;myapp.android.application&quot;)<br>    id(&quot;myapp.android.compose&quot;)<br>}<br><br>dependencies {<br>    // Modules<br>    implementation(project(&quot;:core&quot;))<br>    implementation(project(&quot;:common&quot;))<br>    implementation(project(&quot;:navigation&quot;))<br>    implementation(project(&quot;:landing&quot;))<br>    // Module specific dependencies<br>    implementation(libs.koin)<br>    implementation(libs.voyager.navigator)<br>    implementation(libs.timber)<br>}</pre><blockquote><em>NOTE: Starting with Gradle 9, significant changes have been introduced in the way how application and library modules get configured.</em></blockquote><p>Notice what’s <strong>missing</strong>: No compileSdk, no minSdk, no buildFeatures { compose = true }, no Kotlin compiler arguments, and no core Compose dependencies. All of that complex boilerplate is completely hidden behind our custom plugins. The app-level build file is now strictly concerned with things specific to the app module.</p><h3>Setting Up the build-logic Module</h3><p>To achieve this, we create a completely separate, standalone Gradle build inside our main project directory called build-logic. As with any new module you want to add to your project, for Gradle to know it exists, you must add it to the project level settings.gradle.kts. The only difference is, since this is a build folder, the keyword is different:</p><pre>// Pre Gradle 9<br><br>includeBuild(&quot;build-logic&quot;) // &lt;-- add this before all other inclusions<br>include(&quot;:app&quot;)<br>...<br><br>// Gradle 9+<br>pluginManagement {<br>    repositories {<br>        google {<br>            content {<br>                includeGroupByRegex(&quot;com\\.android.*&quot;)<br>                includeGroupByRegex(&quot;com\\.google.*&quot;)<br>                includeGroupByRegex(&quot;androidx.*&quot;)<br>            }<br>        }<br>        mavenCentral()<br>        gradlePluginPortal()<br>    }<br>    includeBuild(&quot;build-logic&quot;) // &lt;-- the includeBuild instruction gets moved to the pluginManagement block<br>}</pre><p>Because it’s an isolated build, Gradle doesn’t automatically know about our primary project’s version catalog (libs.versions.toml). We need to explicitly link it. Also, add entries into the catalog so that the Gradle script can reach them:</p><pre>// Pre Gradle 9<br>[versions]<br>agp = &quot;8.13.2&quot;<br>kotlin = &quot;2.3.20&quot;<br>room = &quot;2.8.4&quot;<br>...<br>[libraries]<br>android-gradle = { group = &quot;com.android.tools.build&quot;, name = &quot;gradle&quot;, version.ref = &quot;agp&quot; }<br>kotlin-gradle = { group = &quot;org.jetbrains.kotlin&quot;, name = &quot;kotlin-gradle-plugin&quot;, version.ref = &quot;kotlin&quot; }<br>room-gradle = { group = &quot;androidx.room&quot;, name = &quot;room-gradle-plugin&quot;, version.ref = &quot;room&quot; }<br>...<br><br>// Gradle 9 introduces builtIn Kotlin so we need to remove it from the plugins block<br>[versions]<br># Gradle &amp; Kotlin<br>agp = &quot;9.1.0&quot;<br>kotlin = &quot;2.3.20&quot;<br>ksp = &quot;2.3.6&quot;<br><br># Data<br>room = &quot;2.8.4&quot;<br>...<br><br>[libraries]<br># Gradle &amp; Kotlin Plugins<br>android-gradle = { group = &quot;com.android.tools.build&quot;, name = &quot;gradle&quot;, version.ref = &quot;agp&quot; }<br>kotlin-gradle = { group = &quot;org.jetbrains.kotlin&quot;, name = &quot;kotlin-gradle-plugin&quot;, version.ref = &quot;kotlin&quot; }<br>room-gradle = { group = &quot;androidx.room&quot;, name = &quot;room-gradle-plugin&quot;, version.ref = &quot;room&quot; }<br>...<br><br>[plugins]<br>android-application = { id = &quot;com.android.application&quot;, version.ref = &quot;agp&quot; }<br>android-library = { id = &quot;com.android.library&quot;, version.ref = &quot;agp&quot; }<br>kotlin-compose = { id = &quot;org.jetbrains.kotlin.plugin.compose&quot;, version.ref = &quot;kotlin&quot; }<br>ksp = { id = &quot;com.google.devtools.ksp&quot;, version.ref = &quot;ksp&quot; }<br>room = { id = &quot;androidx.room&quot;, version.ref = &quot;room&quot; }<br>// the kotlin-android plugin has been removed<br>// kotlin-android = { id = &quot;org.jetbrains.kotlin.android&quot;, version.ref = &quot;kotlin&quot; }</pre><blockquote><em>NOTE: </em><em>gradle.properties will also be edited when you migrate from Gradle 8 to 9, feel free to clean up everything you do not need or use. I am still dependent on the </em><em>newDsl = false flag since the official </em><em>protobuf plugin that I am using is not compatible with Gradle 9 features.</em></blockquote><h4>For Gradle 9 only</h4><p>The kotlin.android plugin needs to be removed from your project level gradle.build.kt .</p><h3>1. Linking the Version Catalog (build-logic/settings.gradle.kts)</h3><p>Create a settings.gradle.kts file inside your new build-logic directory. We need to tell this separate build where to find our shared versions and dependencies:</p><pre>dependencyResolutionManagement {<br>    repositories {<br>        google()<br>        mavenCentral()<br>        gradlePluginPortal()<br>    }<br>    versionCatalogs {<br>        create(&quot;libs&quot;) {<br>            from(files(&quot;../gradle/libs.versions.toml&quot;)) // &lt;-- This points to your version catalog<br>        }<br>    }<br>}</pre><h3>2. Configuring Dependencies (build-logic/build.gradle.kts)</h3><p>Next, inside build-logic/build.gradle.kts, we define the dependencies that our plugins will need to compile. We use compileOnly so we don&#39;t force our plugin&#39;s AGP/Kotlin versions onto the project that consumes this plugin.</p><p>This is also where we register our plugins so Gradle knows what ID maps to which class:</p><pre>plugins {<br>    `kotlin-dsl`<br>}<br><br>dependencies {<br>    compileOnly(libs.android.gradle)<br>    compileOnly(libs.kotlin.gradle)<br>    compileOnly(libs.room.gradle)<br>}<br><br>gradlePlugin {<br>    plugins {<br>        register(&quot;myapp.android.library&quot;) {<br>            id = &quot;myapp.android.library&quot;<br>            implementationClass = &quot;AndroidLibraryConventionPlugin&quot;<br>        }<br><br>        register(&quot;myapp.android.application&quot;) {<br>            id = &quot;myapp.android.application&quot;<br>            implementationClass = &quot;AndroidApplicationConventionPlugin&quot;<br>        }<br><br>        register(&quot;myapp.android.compose&quot;) {<br>            id = &quot;myapp.android.compose&quot;<br>            implementationClass = &quot;AndroidComposeConventionPlugin&quot;<br>        }<br>    }<br>}</pre><h3>Creating the Plugins</h3><p>Now for the fun part: writing the actual plugins. In build-logic/src/main/kotlin/, we write standard Kotlin classes that implement Gradle&#39;s Plugin&lt;Project&gt; interface.</p><h3>A Focused, Reusable Plugin: ProjectPluginExtensions.kt</h3><p>First, let’s look at how to centralize base Android and Kotlin configuration. The best practice here is to write an extension function that configures the CommonExtension (which both Android Libraries and Android Applications use), and then call that function from a concrete Plugin class.</p><p>Here is the setup and the <strong>usage example</strong> of how it gets applied:</p><pre>// Pre Gradle 9<br>internal fun Project.configureKotlinAndroid(<br>    commonExtension: CommonExtension&lt;*, *, *, *, *, *&gt;,<br>) {<br>    commonExtension.apply {<br>        compileSdk = 36<br>        defaultConfig {<br>            minSdk = 31<br>        }<br><br>        compileOptions {<br>            sourceCompatibility = JavaVersion.VERSION_21<br>            targetCompatibility = JavaVersion.VERSION_21<br>        }<br>    }<br><br>    tasks.withType&lt;KotlinCompile&gt;().configureEach {<br>        compilerOptions {<br>            jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_21)<br>        }<br>    }<br>}<br><br>// Gradle 9<br>internal fun Project.configureKotlinAndroid(<br>    commonExtension: CommonExtension, // &lt;-- CommonExtension does not accept type parameters<br>) {<br>    commonExtension.apply {<br>        compileSdk = 36<br><br>        defaultConfig.apply { // &lt;-- change in method of accessing the minSdk property<br>            minSdk = 31<br>        }<br><br>        compileOptions.apply { // &lt;-- change in method of accessing the compileOptions property<br>            sourceCompatibility = JavaVersion.VERSION_21<br>            targetCompatibility = JavaVersion.VERSION_21<br>        }<br>    }<br><br>    tasks.withType&lt;KotlinCompile&gt;().configureEach {<br>        compilerOptions {<br>            jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_21)<br>        }<br>    }<br>}</pre><pre>// Pre Gradle 9<br>class AndroidLibraryConventionPlugin : Plugin&lt;Project&gt; {<br>    override fun apply(target: Project) {<br>        with(target) {<br>            pluginManager.apply(&quot;com.android.library&quot;)<br>            pluginManager.apply(&quot;org.jetbrains.kotlin.android&quot;)<br><br>            extensions.configure&lt;LibraryExtension&gt; {<br>                configureKotlinAndroid(this) // &lt;-- Use the extension function with the LibraryExtension<br><br>                // Set library specific flags, general build type configuration, etc.<br>            }<br>        }<br>    }<br>}<br><br>// Gradle 9<br>import com.android.build.api.dsl.LibraryExtension // &lt;-- New import for LibraryExtension<br><br>class AndroidLibraryConventionPlugin : Plugin&lt;Project&gt; {<br>    override fun apply(target: Project) {<br>        with(target) {<br>            pluginManager.apply(&quot;com.android.library&quot;)<br>            // pluginManager.apply(&quot;org.jetbrains.kotlin.android&quot;) &lt;-- this in not needed anymore<br><br>            extensions.configure&lt;LibraryExtension&gt; {<br>                configureKotlinAndroid(this) // &lt;-- Use the extension function with the LibraryExtension<br><br>                // Set library specific flags, general build type configuration, etc.<br>            }<br>        }<br>    }<br>}</pre><p>By splitting the logic, an AndroidLibraryConventionPlugin can easily call configureKotlinAndroid(this) on its LibraryExtension, guaranteeing identical setups across your entire project. The same logic applies to a BaseAppModuleExtension:</p><pre>// Pre Gradle 9<br>class AndroidApplicationConventionPlugin : Plugin&lt;Project&gt; {<br>    override fun apply(target: Project) {<br>        with(target) {<br>            pluginManager.apply(&quot;com.android.application&quot;)<br>            pluginManager.apply(&quot;org.jetbrains.kotlin.android&quot;)<br><br>            extensions.configure&lt;BaseAppModuleExtension&gt; {<br>                configureKotlinAndroid(this) // &lt;-- Use the extension function with the BaseAppModuleExtension<br><br>                // Set app module specific flags<br>                namespace = &quot;com.example.myapp&quot;<br><br>                defaultConfig {<br>                    applicationId = &quot;com.example.myapp&quot;<br>                    targetSdk = 36<br>                    versionCode = 1<br>                    versionName = &quot;1.0.0&quot;<br>                }<br>            }<br>        }<br>    }<br>}<br><br>// Gradle 9<br>import com.android.build.api.dsl.ApplicationExtension<br><br>class AndroidApplicationConventionPlugin : Plugin&lt;Project&gt; {<br>    override fun apply(target: Project) {<br>        with(target) {<br>            pluginManager.apply(&quot;com.android.application&quot;)<br>            // pluginManager.apply(&quot;org.jetbrains.kotlin.android&quot;) &lt;-- this in not needed anymore <br><br>           extensions.configure&lt;ApplicationExtension&gt; { // &lt;-- Different extension class<br>                configureKotlinAndroid(this) // &lt;-- Use the extension function with the BaseAppModuleExtension<br><br>                // Set app module specific flags<br>                namespace = &quot;com.example.myapp&quot;<br><br>                defaultConfig {<br>                    applicationId = &quot;com.example.myapp&quot;<br>                    targetSdk = 36<br>                    versionCode = 1<br>                    versionName = &quot;1.0.0&quot;<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>A Complex Plugin: AndroidComposeConventionPlugin.kt</h3><p>Sometimes a plugin needs to do more than just set flags — it needs to pull in dependencies and configure specific tooling features. Compose is a perfect candidate for this.</p><p>Here is an example of a plugin that configures Compose and injects required dependencies directly into the module applying it:</p><pre>class RandomPokemonAndroidComposeConventionPlugin : Plugin&lt;Project&gt; {<br>    override fun apply(target: Project) {<br>        with(target) {<br>            val libs = extensions.getByType&lt;VersionCatalogsExtension&gt;().named(&quot;libs&quot;)<br><br>            pluginManager.apply(&quot;org.jetbrains.kotlin.plugin.compose&quot;)<br><br>            pluginManager.withPlugin(&quot;com.android.application&quot;) {<br>                extensions.configure&lt;ApplicationExtension&gt; {<br>                    buildFeatures.compose = true<br>                }<br>            }<br>            pluginManager.withPlugin(&quot;com.android.library&quot;) {<br>                extensions.configure&lt;LibraryExtension&gt; {<br>                    buildFeatures.compose = true<br>                }<br>            }<br><br>            dependencies {<br>                &quot;implementation&quot;(platform(libs.findLibrary(&quot;androidx.compose.bom&quot;).get()))<br>                &quot;implementation&quot;(libs.findLibrary(&quot;androidx.ui&quot;).get())<br>                &quot;implementation&quot;(libs.findLibrary(&quot;androidx.ui.tooling.preview&quot;).get())<br>                &quot;implementation&quot;(libs.findLibrary(&quot;androidx.material3&quot;).get())<br>            }<br>        }<br>    }<br>}</pre><p>By applying this single plugin, any module in your project that implements this plugin immediately gets Compose enabled, the correct Compose compiler linked, the BOM applied, and the tooling dependencies configured. If you ever need to update the Compose BOM or compiler, you do it centrally in your version catalog. Your feature module is clean and only lists specific flags and dependencies particular to it.</p><pre>plugins {<br>    id(&quot;myapp.android.library&quot;)<br>    id(&quot;myapp.android.compose&quot;)<br>}<br><br>android {<br>    namespace = &quot;io.bitbot.bemusedbaboon.landing&quot;<br>}<br><br>dependencies {<br><br>    implementation(project(&quot;:core&quot;))<br>    implementation(project(&quot;:common&quot;))<br>    implementation(project(&quot;:navigation&quot;))<br><br>    implementation(libs.timber)<br><br>    implementation(libs.koin)<br>    implementation(libs.koin.compose)<br><br>    implementation(libs.voyager.navigator)<br><br>    implementation(libs.coil.compose)<br>    implementation(libs.coil.network)<br>}</pre><h3>Bonus: Dynamically Generating Library Namespaces</h3><p>If you want to take your boilerplate reduction a step further, look at how you declare namespaces in your library modules.</p><p>Typically, every library’s build.gradle.kts requires an android block just to declare a deeply nested namespace:</p><pre>android { <br>    namespace = &quot;com.example.myapp.commons&quot; <br>}</pre><p>Since the base namespace com.example.myapp never changes, repeating it across dozens of modules is prone to typos and adds unnecessary noise. Because our build-logic is written in Kotlin, we can create a simple top-level extension function to handle this for us.</p><h3>1. The Helper Function (build-logic/src/man/kotlin/ProjectPluginExtensions.kt )</h3><p>Create a new Kotlin file in your convention plugin source directory. We’ll define our base namespace as a constant and write an extension function on Project that configures the LibraryExtension:</p><pre>// Define your single source of truth for the base namespace<br>private const val BASE_NAMESPACE = &quot;com.example.myapp&quot;<br><br>/**<br> * Automatically applies the base namespace and appends the provided suffix.<br> */<br>fun Project.libraryNamespace(suffix: String) {<br>    extensions.configure&lt;LibraryExtension&gt; {<br>        namespace = &quot;$BASE_NAMESPACE.$suffix&quot;<br>    }<br>}</pre><h3>2. The Final Library build.gradle.kts</h3><p>Now, you can completely eliminate the android { ... } block from your library modules. Whenever you create a new library, you simply call your custom function directly in the build script:</p><pre>plugins {<br>    id(&quot;myapp.android.library&quot;)<br>    id(&quot;myapp.android.room&quot;)<br>}<br><br>libraryNamespace(&quot;commons&quot;)<br><br>dependencies {<br>    ...<br>}</pre><p>By adding this tiny extension function, your library build scripts become incredibly concise, and your project enforces a strict, typo-free naming convention for all module namespaces.</p><h3>Conclusion</h3><p>Migrating your Gradle build configuration to custom convention plugins requires an initial upfront investment, but the ROI is massive:</p><ol><li><strong>Readability:</strong> Module-level build.gradle.kts files become declarative summaries of what a module <em>is</em>, rather than a script of <em>how</em> it compiles.</li><li><strong>Safety:</strong> New modules are guaranteed to use the correct compiler flags, Java targets, and core dependencies.</li><li><strong>Maintainability:</strong> Updating your project to a new Java version, bumping compileSdk, or changing compiler arguments happens in exactly one place.</li></ol><p>Stop copying Gradle code. Treat your build configuration with the same architectural respect you give to your application architecture. Your future self — and your team — will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb654a15be36" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>