<?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 Pollyanna - Kotlin Development on Medium]]></title>
        <description><![CDATA[Stories by Pollyanna - Kotlin Development on Medium]]></description>
        <link>https://medium.com/@androidpollyanna?source=rss-c8b790b253c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yaT5S6_snhE2CYi48Kz_PQ.jpeg</url>
            <title>Stories by Pollyanna - Kotlin Development on Medium</title>
            <link>https://medium.com/@androidpollyanna?source=rss-c8b790b253c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:03:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@androidpollyanna/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[紀錄我在台灣 Gogolook 走著瞧所聞所見珍貴的事物]]></title>
            <link>https://androidpollyanna.medium.com/%E7%B4%80%E9%8C%84%E6%88%91%E5%9C%A8%E5%8F%B0%E7%81%A3-gogolook-%E8%B5%B0%E8%91%97%E7%9E%A7%E6%89%80%E8%81%9E%E6%89%80%E8%A6%8B%E7%8F%8D%E8%B2%B4%E7%9A%84%E4%BA%8B%E7%89%A9-97ecf55514bd?source=rss-c8b790b253c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/97ecf55514bd</guid>
            <dc:creator><![CDATA[Pollyanna - Kotlin Development]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 18:44:41 GMT</pubDate>
            <atom:updated>2026-07-19T19:03:48.208Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Hi! It’s Polly. This article isn’t technical; it’s more of a record of my personal growth from Taipei to Prague, so I will be writing it in my native language, Traditional Mandarin.</blockquote><blockquote>I believe there are always some moments so precious and moving that you simply have to use your native language to express them. If you haven’t experienced this yet, I sincerely hope a moment like this comes to you someday.</blockquote><p>我這週剛從布拉格花了 17 個小時回台灣，其中一個任務是從 Gogolook 離職。這個過程實在有一點太快，加上在台灣有太多行政跟社交行程在跑了，我直到今天才稍微感受到與公司同事離別的感性 XDDDD</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuKYFoECuWejT5sy_h7DUg.jpeg" /><figcaption>TMI，我是帶著幾乎空的行李箱回台灣的，上面這套除了皮鞋都是在台灣買的 ( 沒人想知道誒）在台灣買衣服就是舒服</figcaption></figure><p>我想離職對於成年人的世界是無比正常的事情， 我這個初級大人想趁還不是很習慣的時期，紀錄一下我第一份正職工作的感受與感謝。</p><p>Gogolook 在台灣最知名的產品就是來電辨識 app <a href="https://web.whoscall.com/en">whoscall</a> ，而我也有幸能在職涯初期就能見證如此知名且完整的產品的成長與變化，在進入這家公司以來我一直很以此為榮。這是我從 Appworks School 畢業後第一間進入的公司，我記得 Gogolook 並不是 Appworks 的 partner ，對當時的我來說相對是比較陌生的團隊。裡面絕大部分的工程師都很資深，所以我經歷了一個很害怕犯錯、甚至自己不夠格的時期。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z_ZihttsOo9T22Au.jpg" /><figcaption>不知道未來 whoscall 是否會成為只有老人才知道的 app QQ ，還是想記錄一下這在 2026 年還是很厲害的！圖片來源：<a href="https://www.gogolook.com/zh-tw/newsroom/whoscall-wins-best-app-of-2025-on-google-play-a-major-milestone-following-its-major-app-revamp-chinese">https://www.gogolook.com/zh-tw/newsroom/whoscall-wins-best-app-of-2025-on-google-play-a-major-milestone-following-its-major-app-revamp-chinese</a></figcaption></figure><p>不過我真的非常幸運，初次跟我 cowork 的人有我的主管 Chris 跟資深同事 Jason ，一言以蔽之的話，我會說他們是嚴格與溫和兼具的好人。他們保持著耐心與真誠相待，慢慢幫我找到從錯誤中學習的步調。我覺得 gogolook 的團隊文化真的很好，能在困境之中彼此學習，平衡著彈性與 best practice。我聽說人跟人初次見面七秒鐘就可以產生對這個人的直覺，其實我覺得進入一個產業也是。我相信第一份工作的好與壞，都會深深的決定一個人的工作態度與工作信念，而我很慶幸我是遇到好的工作的那個人。</p><p>並且在最後這一年，我多認識了 PM Joy，他的熱情、真誠，以及遇到問題積極解決的勇氣，如果一個人 30 歲就能成為這樣的樣子，那我會很想趕快 30 歲。我原本想說我很希望我可以在布拉格也遇到布拉格版本的走著瞧同事，但仔細想想，我最想要的應該還是有朝一日，我能夠有部分像我很欣賞的他們：</p><p>希望有凱哥的臨危不亂與可靠感</p><p>希望有威力跟 eden 的嚴謹與耐心</p><p>希望有海明的幽默感與替人著想</p><p>希望有 Joy 與 colette 的機智與產品能力</p><p>從學生時期一直以來，我並不是在團體裡面最有才華、最閃閃發光的那個人，但總是運氣好、被推到一個很好的環境，時常會覺得自己何德何能。不過我很真實的感受到，今天的我，比 2023 年 11 月底面試 Gogolook 的自己成長了非常多，我扎實的覺得今天自己真的是個工程師。我想，在這個能夠不斷挑戰並成就自我的環境滋養出來的信心，也是我今天一卡皮箱就入住布拉格的養分。</p><p>我記得之前有一次 AHM 我們的 CEO 說過一個他的觀察，原文我其實有一點忘記了，我非常認同，簡單描述一下我的印象。台灣這個小島市場不大，可能不像是日本或是中國可以自給自足，產品成長到一個程度，我們就一定要走出去才有成長空間。但也因為這樣，台灣人的團隊總是充滿著各種彈性，以及嘗試新事物的勇氣，這也是我在 Gogolook 最重要的 takeaway 。</p><p>現在距離台北 9000 公里，14 小時飛行航程、時差六小時，但我還是會繼續在這個相對陌生的地方，拿出台灣人的勇氣與韌性，繼續走著瞧的（不知道為什麼想來點播一首滅火器的今天的我）</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FA0AW9NixPAo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DA0AW9NixPAo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FA0AW9NixPAo%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/35176ece9b7add0763883e9031a7834f/href">https://medium.com/media/35176ece9b7add0763883e9031a7834f/href</a></iframe><p>感謝 Gogolook ，我們後會有期！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97ecf55514bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Koin on the Backend: Architecture Decisions in a Ktor Service]]></title>
            <link>https://androidpollyanna.medium.com/koin-on-the-backend-architecture-decisions-in-a-ktor-service-8193db922cc4?source=rss-c8b790b253c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8193db922cc4</guid>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[koin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Pollyanna - Kotlin Development]]></dc:creator>
            <pubDate>Wed, 27 May 2026 14:43:55 GMT</pubDate>
            <atom:updated>2026-05-27T14:44:43.027Z</atom:updated>
            <content:encoded><![CDATA[<p>Most Koin material is written for Android. The DSL is the same on the backend, but the constraints are different enough that the decisions you make end up looking nothing like the ones you’d make in an Android app.</p><blockquote>This post walks through the three <a href="https://insert-koin.io/">Koin</a> and <a href="https://ktor.io/">Ktor</a> architecture decisions in <a href="https://github.com/pollyannaanalytics/JustWoo-KMP">JustWoo</a>, the backend for a KMP side project, that I think are genuinely different from how you’d reach for Koin on Android. The stack is Ktor + Exposed + Postgres + Redis.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*c6_FCa0InCejYHhv2PCiAg.png" /></figure><h3>Decision 1: Every service is single, because services are stateless</h3><p>There is no factory, no per-request scope, no equivalent of viewModel { } anywhere in the modules. Every service and repository is a single.</p><pre>val servicesModule = module {<br>    single&lt;HouseService&gt;     { DefaultHouseService(get(), get()) }<br>    single&lt;TaskService&gt;      { DefaultTaskService(get(), get(), get()) }<br>    single&lt;AuthService&gt;      { DefaultAuthService(get(), get(), get(), get(), get(), get()) }<br>    single&lt;ProfileService&gt;   { DefaultProfileService(get()) }<br>    single&lt;SettlementService&gt;{ DefaultSettlementService(get(), get(), get()) }<br>}</pre><p>This is safe because services hold no mutable state. Every piece of request-specific state enters as a parameter:</p><pre>override suspend fun loginByEmailAndPassword(<br>    email: String,<br>    plainPassword: String,<br>    deviceId: String,<br>): AuthDataResult&lt;AuthResponse&gt; { ... }</pre><p>Two concurrent logins for two different users hit the same DefaultAuthService instance and never see each other, because the only state they each touch lives in their own stack frame. The class itself owns nothing besides its injected dependencies, which are also singletons.</p><p>The Android equivalent (ViewModel) keeps state in fields because the UI observes those fields over time. A backend service has no observer; the response goes out and the state is discarded. Pushing state out of fields and into parameters is what makes single the correct default rather than a dangerous shortcut.</p><h3>Decision 2: Custom AuthenticationProvider, bridged to Koin via getKoin().get&lt;&gt;()</h3><p>Ktor ships a jwt {} plugin that handles JWT validation inline. JustWoo doesn&#39;t use it. Instead, JWT verification sits behind an AccessTokenProvider interface:</p><pre>interface AccessTokenProvider {<br>    fun createAccessToken(userId: Long): String<br>    fun verifyAccessToken(token: String): DecodedJWT?<br>}</pre><p>And the authentication plugin takes the interface, not the JWT library:</p><pre>class JustwooAuthProvider(config: Config) : AuthenticationProvider(config) {<br>    class Config(name: String?) : AuthenticationProvider.Config(name) {<br>        lateinit var tokenProvider: AccessTokenProvider<br>    }<br>    private val tokenProvider = (config as Config).tokenProvider<br>    // onAuthenticate uses tokenProvider to verify and produce a UserIdPrincipal<br>}</pre><p>The reason for the extra layer is that the built-in jwt {} block couples authentication to a specific JWT implementation and to a config that lives inside the install(Authentication) lambda. Replacing it for tests means reaching into Ktor internals. With the interface in front, DefaultAuthService and the auth plugin both depend on AccessTokenProvider, and tests can register a fake provider in Koin without touching either consumer.</p><p>The interface boundary creates one new problem: install(Authentication) is a DSL block, not a class constructor, so there&#39;s no place to inject AccessTokenProvider from outside. The bridge is an extension function that reads from the container directly:</p><pre>fun AuthenticationConfig.customAuth(name: String? = &quot;auth-jwt&quot;) {<br>    val tokenProvider = getKoin().get&lt;AccessTokenProvider&gt;()<br>    val config = JustwooAuthProvider.Config(name).apply {<br>        this.tokenProvider = tokenProvider<br>    }<br>    register(JustwooAuthProvider(config))<br>}<br><br><br>install(Authentication) {<br>    customAuth(&quot;auth-jwt&quot;)<br>}</pre><p>This is technically the <strong>Service Locator pattern</strong>. On Android it would be a smell, because Hilt and Koin both have machinery that lets constructor injection reach almost anywhere. Ktor’s plugin DSL doesn’t expose that surface — it’s a runtime callback into a configuration object, and the only way to get arbitrary dependencies into it without globals is to ask the container by name.</p><p>One consequence is that install order becomes load-bearing: install(Koin) has to run before install(Authentication), because customAuth reads from the container at install time. Reorder them and startup throws at the first request.</p><h3>Decision 3: Request isolation lives outside the container</h3><p>Once every service is a singleton, the obvious question is: what stops ten concurrent requests from stepping on each other inside the same DefaultAuthRepository instance? The answer is that Koin doesn&#39;t have to solve this, because two lower layers already do.</p><p><strong>Pooled resources, leased per call.</strong> JedisPool is bound as a singleton:</p><pre>single { RedisFactory.getPool() } onClose { it?.close() }</pre><p>But each operation leases a connection out of the pool and returns it with use { }:</p><pre>jedisPool.resource.use { jedis -&gt;<br>    jedis.hset(tokenKey, refreshToken.toMap())<br>    jedis.expire(tokenKey, expireDurationInSeconds)<br>}</pre><p>The pool is shared; the connection lease is scoped to one call.</p><p><strong>Transactions bound to the coroutine context.</strong> Every Exposed query goes through one helper:</p><pre>suspend fun &lt;T&gt; dbQuery(block: suspend () -&gt; T): T =<br>    newSuspendedTransaction(Dispatchers.IO) { block() }<br><br>// use<br>override suspend fun findUserByAccount(email: String): User? = dbQuery {<br>    Users.selectAll().where { Users.email eq email }<br>        .map { rowToUser(it) }<br>        .singleOrNull()<br>}</pre><p>newSuspendedTransaction attaches the transaction to the current coroutine context. Ten concurrent requests through the same singleton repository get ten independent transactions, because the transaction is tied to the coroutine, not to the repository instance.</p><p>On Android, “scope” is almost always a DI concern: You pick viewModel { } or scoped { } to control lifetime. On the backend, scope is rarely a DI concern. It&#39;s a resource-management concern handled by use { }, or a transaction concern handled by the coroutine context. <strong>Koin&#39;s job is just to make the shared, long-lived things discoverable; the per-request lifetime is enforced somewhere else.</strong></p><h3>What this adds up to</h3><ul><li>The DI container holds long-lived, stateless, shared objects.</li><li>Per-request state lives in function parameters and the coroutine context, not in DI scopes.</li><li>Plugin DSLs that can’t accept injection bridge to Koin explicitly via getKoin().get&lt;&gt;().</li></ul><p>Koin’s role on the backend turns out to be narrower than on Android. <strong>It manages the long-lived graph and bridges into Ktor plugins.</strong> It does not manage request scope, because the coroutine and the connection pool already do.</p><p><em>The JustWoo backend is a working side project, not a polished sample. A few rough edges in the source: the custom </em><em>AuthenticationProvider still has debug </em><em>println calls, the refresh-token flow issues a new token on each refresh without invalidating the old one, and </em><em>JwtAccessTokenProvider logs its algorithm in places it shouldn&#39;t. The decisions above hold up; the polish around them is in progress.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8193db922cc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Chose Ktor as the Backend for My Kotlin Full-Stack Project]]></title>
            <link>https://androidpollyanna.medium.com/why-i-chose-ktor-as-the-backend-for-my-kotlin-full-stack-project-606729699c47?source=rss-c8b790b253c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/606729699c47</guid>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Pollyanna - Kotlin Development]]></dc:creator>
            <pubDate>Sat, 16 May 2026 18:54:04 GMT</pubDate>
            <atom:updated>2026-05-16T18:56:22.587Z</atom:updated>
            <content:encoded><![CDATA[<p>For a while now, I’ve been working on a personal full-stack project called <a href="https://github.com/pollyannaanalytics/JustWoo-KMP"><strong>JustWoo</strong></a>. The Mobile uses Jetpack Compose for Android and Swift for iOS (still a work in progress — I’m wrestling with it!), the backend runs on <strong>Ktor</strong>, and the whole thing is glued together with Kotlin Multiplatform (KMP).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1pawy1pUMWPUIyCA.png" /><figcaption><a href="https://ktor.io/">https://ktor.io/</a></figcaption></figure><p>After working on it for some time, I noticed there were a few decisions worth writing down. This article is about the trade-offs behind each architectural choice — written for anyone on the fence about going down this path.</p><h3>The project’s module layout</h3><p>Before getting into the meat of it, I want to quickly walk through how I split my modules, because everything below builds on top of this.</p><p>Most KMP tutorials toss all shared code into a single shared module. My project goes one step further:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCI2fea_fnIq_zaMWkZSbA.png" /></figure><p>The key design choice is splitting :core:model and :shared into two separate modules. Here&#39;s why:</p><ul><li><strong>:core:model is the home of the API contract.</strong> It only contains data classes, sealed classes, enums, @Serializable DTOs, and an ApiResult&lt;T&gt; for expressing API outcomes. <strong>No platform dependencies, no business logic, no IO.</strong> Both the backend and the clients can safely depend on it — it&#39;s the minimum contract surface.</li><li><strong>:shared is the client-side shared implementation.</strong> It contains repositories, the Ktor HttpClient, the SQLDelight database, and Koin DI — all things that only mobile clients need. The backend never has to touch any of this.</li></ul><p>If I merged these two layers into one shared module, the backend would be forced to pull in SQLDelight, Koin, and other client-only dependencies it doesn&#39;t need. Build times, jar size, and cognitive load would all balloon.</p><p>In other words: :core:model is the real cross-tier sharing layer (between the backend and the clients), while :shared is just the cross-platform sharing layer (between Android and iOS). Splitting contract from implementation is what lets a KMP backend and KMP clients coexist happily.</p><p>commonMain holds &quot;pure Kotlin code with zero platform dependencies&quot; — data classes, sealed classes, serializable DTOs, validation logic, pure-function domain models. These compile to platform-specific artifacts and get picked up by each platform&#39;s main source set.</p><p>The point is: <strong>write it once in </strong><strong>commonMain, and both the backend and the frontends can use it.</strong> That&#39;s the foundation of the very first reason I picked Ktor.</p><h3>Reason for Using Ktor Part 1: Sharing DTOs across both sides — even sealed classes</h3><p>You’ll often hear “Node.js + TypeScript can share types too.” That’s true, but the experience is very different.</p><p>TypeScript’s type sharing stops at “same shape.” You can share an interface, but the runtime behavior still has to be re-implemented on each side. Sealed unions in TS rely on discriminated unions plus manual narrowing — there&#39;s no way to <em>enforce</em> exhaustive matching.</p><p>KMP is different. I can declare a sealed class ApiResponse&lt;T&gt; in commonMain, and both backend and frontend receive <strong>the same class</strong> — not just the same shape. The compiler also enforces exhaustive when matching, lighting up any branch I forgot to handle.</p><p>This setup makes “changing an API” a stress-free operation. Change the type of a single field and the compiler lights up red in the backend route, the frontend ViewModel, and the UI — all at once. You literally cannot miss a spot.</p><p><strong>Step 1 — The shared sealed result type, in </strong><strong>:core:model:</strong></p><pre>// core/model/src/commonMain/.../model/ApiResult.kt<br>package com.pollyannawu.justwoo.modelsealed class ApiResult&lt;out T&gt; {<br>    data class Success&lt;T&gt;(val data: T) : ApiResult&lt;T&gt;()<br>    data class Error(val exception: Throwable) : ApiResult&lt;Nothing&gt;()<br>    data object Loading : ApiResult&lt;Nothing&gt;()<br>}</pre><p>Three lines. Both the Ktor backend and the Android client import the exact same class.</p><p><strong>Step 2 — The shared DTO, also in </strong><strong>:core:model:</strong></p><pre>// core/model/src/commonMain/.../core/dto/HouseDto.kt<br>@Serializable<br>data class HouseRequest(<br>    val title: String,<br>    val name: String,<br>    val adminUserId: Long,<br>    val memberIds: List&lt;Long&gt; = emptyList(),<br>    val description: String,<br>    val avatar: String? = null,<br>    val createTime: Instant,<br>    val updateTime: Instant,<br>)<br><br>@Serializable<br>data class HouseResponse(<br>    val id: Long,<br>    val title: String,<br>    val name: String,<br>    val members: List&lt;MemberProfileResponse&gt;,<br>    val description: String,<br>    val avatarUrl: String,<br>    val createTime: Instant,<br>    val updateTime: Instant,<br>)</pre><p>Plain @Serializable data classes. They describe the wire format and nothing else — no validation, no business logic, no infrastructure.</p><p><strong>Step 3 — The Ktor backend consumes the DTO directly:</strong></p><pre>// backend/.../routes/HouseRoutes.kt<br>post {<br>    val userId = getUserId(call)<br>        ?: return@post call.respond(HttpStatusCode.Unauthorized)<br>    try {<br>        val request = call.receive&lt;HouseRequest&gt;()   // ← deserializes the shared DTO<br>        val result = houseService.createHouse(userId, request)<br>        call.respondResult(result)<br>    } catch (e: ContentTransformationException) {<br>        call.respond(HttpStatusCode.BadRequest, &quot;Invalid JSON format&quot;)<br>    }<br>}</pre><p>call.receive&lt;HouseRequest&gt;() automatically deserializes the JSON body into the same data class the client sent. No &quot;DTO-to-entity&quot; mapping ceremony, no parallel definitions in two languages.</p><p><strong>Step 4 — The Mobile client uses the same DTO going the other direction:</strong></p><pre>// shared/.../network/service/HouseApiService.kt<br>interface HouseApiService {<br>    suspend fun createHouse(request: HouseRequest): ApiResult&lt;HouseResponse&gt;<br>}<br>class DefaultHouseApiService(<br>    private val client: HttpClient,<br>) : HouseApiService {<br>    override suspend fun createHouse(<br>        request: HouseRequest,<br>    ): ApiResult&lt;HouseResponse&gt; = safeApiCall {<br>        client.post(&quot;/houses&quot;) {<br>            setBody(request)   // ← serializes the same DTO out<br>        }.body()               // ← deserializes the response DTO<br>    }<br>}</pre><p>The safeApiCall helper turns any thrown exception into ApiResult.Error, so the rest of the app never has to write a try-catch:</p><pre>suspend inline fun &lt;T&gt; safeApiCall(block: () -&gt; T): ApiResult&lt;T&gt; = try {<br>    ApiResult.Success(block())<br>} catch (e: CancellationException) {<br>    throw e<br>} catch (e: Throwable) {<br>    ApiResult.Error(e)<br>}</pre><p>That said, there’s a trap in KMP backend work: <strong>don’t dump everything into </strong><strong>commonMain.</strong> Database entities, internal domain models, anything tightly coupled to infrastructure, none of that belongs on the frontend. <strong>Keep </strong><strong>commonMain strictly for API contracts: request DTOs, response DTOs, error-code enums, validation rules</strong>. If you get greedy and share every model from day one, you&#39;ll end up with a &quot;pull one thread and the whole sweater unravels&quot; situation later.</p><h3>Reason 2: Exposed + coroutine transactions, an elegant way to handle atomicity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bSSn-IqOdGGeKe8Z.png" /><figcaption><a href="https://www.jetbrains.com/exposed/">https://www.jetbrains.com/exposed/</a></figcaption></figure><p>Once Ktor was on the table, picking Exposed for the ORM was almost a no-brainer. Same JetBrains lineage, a DSL that feels like Kotlin, and none of JPA’s annotation noise.</p><p>But there’s one Exposed API you really need to know about: newSuspendedTransaction { ... }.</p><p>A regular transaction { ... } is bound to a thread, because JDBC connections are thread-local. If you write something like this inside a coroutine:</p><pre>transaction {<br>    val user = UserDao.findById(id)<br>    delay(100)  // suspension point!<br>    user.update(...)<br>}</pre><p>after delay, the coroutine may resume on a different thread — one that doesn&#39;t hold the original transaction. Everything breaks.</p><p>newSuspendedTransaction fixes this with a dedicated dispatcher. It guarantees that the coroutine, across its suspend/resume cycles, always lands back on the same thread that holds the transaction. So you can call other suspend functions inside the transaction — hitting an external API, waiting on Redis — without worrying about thread switching.</p><p>The atomicity story is very Kotlin-flavored:<strong> throw an exception anywhere inside the block and the whole transaction rolls back</strong>. Finish normally and it commits. No try-catch-finally, no @Transactional annotation. The logic reads exactly like &quot;either all these steps succeed, or none of them happen.&quot;</p><p>Paired with <strong>HikariCP</strong> for connection pooling, this setup has been very stable on my server.</p><h3>Why Ktor instead of Spring Boot?</h3><p>Two main reasons:</p><h4><strong>1. Startup time and memory.</strong></h4><p>Spring Boot’s core is an IoC container plus annotation magic plus classpath scanning.<strong> It does a lot of reflection and auto-configuration on startup ( </strong>a mid-sized project easily takes 15–30 seconds to boot and sits at 300MB+ in memory). Ktor uses an explicit Kotlin DSL: reading the application module tells you exactly which plugins are loaded. Startup is usually 1–3 seconds. My JustWoo backend, with a JVM heap cap of 512MB, runs comfortably.</p><h4><strong>2. Coroutines as a first-class citizen.</strong></h4><p>Ktor is built on coroutines from the ground up ( every handler is a suspend function). Spring has WebFlux for reactive support, but it&#39;s a separate paradigm; you have to pick between MVC and WebFlux. With Ktor, that choice doesn&#39;t exist.</p><p>The trade-off is that Ktor doesn’t ship with Spring’s “batteries included” ecosystem — validation, scheduling, security, and so on all require picking a library or rolling your own. But for a project at my scale, that hasn’t been a real problem in the short term.</p><h3>The deployment turning point: why I gave in and used Docker</h3><p>Honestly, I was pretty resistant to Docker at first. My reasoning was: “The JVM is already platform-independent. A fat jar plus java -jar is enough. Wrapping it in Docker feels redundant — isn&#39;t that the kind of thing Node.js needs?&quot;</p><p>I actually spent a while just scping the jar onto the server and managing the process with systemd. But a few problems caught up with me fast:</p><ol><li><strong>I needed to connect to Postgres, but I didn’t want to install Postgres natively on my Mac.</strong> Installing it isn’t hard, but keeping the local version aligned with production is a pain.</li><li><strong>I wanted to add Redis for caching and nginx as a reverse proxy.</strong> Installing each one by hand, writing configs, setting them to start on boot — it’s a lot of busywork.</li><li><strong>One Lightsail reinstall meant redoing all the environment setup.</strong> That was the last straw.</li></ol><p>So I went back to Docker. But I gave myself a rule: keep the Dockerfile as minimal as possible.</p><h3>CI/CD: build on GitHub Actions, run on Lightsail</h3><p>For this project, I figured the service is simple enough that I didn’t need the traditional EC2 + RDS scale. Lightsail’s $5/month tier — 1 vCPU, 1GB of RAM — fits my budget. The catch is that running ./gradlew shadowJar on it would either OOM or take forever.</p><p>So I split build and run completely:</p><blockquote>Push to main → triggers a GitHub Actions workflow.</blockquote><blockquote>Actions runs ./gradlew test — if unit tests fail, the pipeline stops right there.</blockquote><blockquote>Then ./gradlew :backend:shadowJar produces backend-all.jar.</blockquote><blockquote>docker build and push the image to a registry (or push the jar directly — your call).</blockquote><blockquote>SSH into Lightsail and run docker compose pull &amp;&amp; docker compose up -d.</blockquote><p>The key point: Lightsail’s only job is docker compose pull and starting containers. <strong>It never builds anything</strong>. GitHub Actions runners come with 4 vCPUs and 16GB of RAM, and they&#39;re free for public repos (or cheap for private ones) , using them to carry the build workload makes far more sense.</p><h3>Takeaways</h3><p>Looking back at the whole stack, the part that still feels most worthwhile is <strong>sharing one piece of code across both sides</strong>. Changing an API becomes painless. The Compose side just imports the types and they work. No other language combination I’ve used delivers this experience.</p><p>The downside is <strong>community size</strong>. Ktor and Exposed get nowhere near the discussion volume of Spring and JPA — sometimes you have to dig into the source yourself to figure out what’s going on. But from another angle, that’s also forced me to understand the framework better.</p><p>If you’re weighing whether to use KMP for your backend, here are a few questions to ask yourself:</p><ul><li><strong>If your frontend is also Kotlin (Android / Compose Multiplatform / Kotlin/JS),</strong> there’s almost no reason not to choose KMP.</li><li><strong>If your frontend is React, Vue, or Swift,</strong> the benefit of a KMP backend shrinks quite a bit — you might be better off with Spring Boot or Node.js.</li><li><strong>If this is a personal project, you want to try something new, and you like a lightweight stack,</strong> Ktor is a great way in.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=606729699c47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating Legacy Codebases: 5 Takeaways from Implementing SDD with Open Spec]]></title>
            <link>https://androidpollyanna.medium.com/navigating-legacy-codebases-5-takeaways-from-implementing-sdd-with-open-spec-e45fb61997ed?source=rss-c8b790b253c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e45fb61997ed</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[spec-driven-development]]></category>
            <category><![CDATA[openspec]]></category>
            <dc:creator><![CDATA[Pollyanna - Kotlin Development]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 17:51:34 GMT</pubDate>
            <atom:updated>2026-04-11T17:51:34.034Z</atom:updated>
            <content:encoded><![CDATA[<p>Spec-Driven Development (SDD) isn’t exactly “breaking news” anymore. However, in my experience, there’s a massive gap between understanding the theory and actually executing it efficiently in a large-scale project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8Pw5IB8z-jRmO-Ds" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=medium&amp;utm_medium=referral">Nick Fewings</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As an engineer who work on a legacy codebase with over 10 years history, I realized that poorly planned SDD is often less efficient than simple prompt engineering.</p><blockquote>This article isn’t a tutorial on Open Spec or SDD : plenty of great docs exist for that. Instead, I want to share my honest lessons learned while trying to make SDD work within a massive legacy codebase.</blockquote><p>I currently use the <strong>Open Spec</strong> framework. Unlike SpecKit, it offers a more flexible structure and straightforward steps that make it much easier to “plug” into existing legacy systems. It also pursues the idea of “living documentation” — you can use the archivecommand after development to maintain a single source of truth. Plus, it plays well with various LLMs, so you aren’t locked into a specific AI ecosystem.</p><h3>Takeaway 1: Choosing the Right Battles for SDD</h3><p>The first thing I learned? Not every task needs a full SDD treatment.</p><p>The keyword for SDD is <strong>new business logic</strong>. This is where an engineer’s understanding of architecture and business decisions is most critical. You need to define the design decisions and, more importantly, human-defined boundaries (scope).</p><p>Another great use case is architectural refactoring. Even though we strive for “Clean Architecture,” real-world code is often a series of trade-offs based on business goals. SDD allows the engineer to keep the steering wheel, providing a structured definition that ensures the AI executes within a standardized framework.</p><p>Conversely, for straightforward bug fixes or simple UI tasks, I still prefer a <strong>Research -&gt; Plan -&gt; Implementation</strong> (RPI) flow. AI is already incredibly strong at tracking tech stacks and codebases; we don’t need to over-engineer the process.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrmvDxxNubIg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrmvDxxNubIg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrmvDxxNubIg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c7ecbe294a6626706934678f2d60dbf/href">https://medium.com/media/2c7ecbe294a6626706934678f2d60dbf/href</a></iframe><blockquote>My rule of thumb for using SDD:<br>1. Do I have confidence that I can align the AI’s understanding with mine in just three prompts?<br>2. Is it possible for the AI to grasp the full context just by reading the codebase?</blockquote><p>If the answer to both is<strong> No</strong>, that’s your cue to use SDD.</p><h3>Takeaway 2: Boundary Context is Everything</h3><p>When facing a legacy codebase, it’s easy to burn through tokens forcing an AI to read “fat” singleton objects.</p><p>The beauty of SDD is that we can use natural language to define the <strong>Boundary Context</strong>. We can tell the AI,</p><blockquote>”You’ll get specific values from this object; don’t bother digging deeper.”</blockquote><p>This is where your knowledge of the system architecture becomes a superpower. You define the data flow and current limitations, giving the AI “hints” that save reasoning resources.</p><p>Think of it as writing a natural language Interface<strong> </strong>for the AI agent. You define what matters and hide the legacy complexity that would only confuse it.</p><h3>Takeaway 3: Tools Change, Intent Stays</h3><p>The AI landscape moves at a breakneck pace. SDD as a concept is barely two years old, yet we already have a dozen “hot” tools.</p><p>However, the core remains the same: <strong>Intent-Driven Development</strong>. Whether you use Open Spec, SpecKit, or something else, the engineer’s job is to clarify:</p><blockquote><strong>What are we doing? Why? How do we verify it?</strong></blockquote><p>For a spec to actually work with AI, it needs to cover:<br>- Definition of Done (DoD)<br>- Design Approach<br>- Decisions &amp; Trade-offs<br>- In/Out of Scope<br>- Edge Cases</p><p>Stop focusing on how to tell the AI to write every line of code.<strong> Focus on how to let the AI know what the correct result looks like.</strong></p><h3>Takeaway 4: Spec Reviews are as Vital as Refactoring</h3><p>Open Spec’s “living document” feature is great — it summarizes your collaboration into documentation. But we have to be careful: <strong>Outdated documentation is technical debt.</strong></p><p>AI helps us produce faster, which also means we can produce “debt” faster.</p><blockquote>To keep things lean, I ask myself two questions before archiving a spec:<br>1. Would a future engineer (or a future AI) need this specific context to understand the system later?<br>2. Does this document bridge a significant knowledge gap?</blockquote><p>If the answer isn’t a solid <strong>Yes</strong>, don’t let it clutter your codebase.</p><h3>Takeaway 5: The Role of the Engineer</h3><p>I’m writing this last part for my future self. Sitting here in 2026, about 2.5 years into my career, I find myself constantly reflecting on my value in this AI-driven era.</p><p>I don’t have all the answers for where the industry is heading, but I do know this: Software engineers are, first and foremost,<strong> problem solvers for people.</strong> I entered this field because I love solving real-world problems.</p><p>AI might be a better “implementer” than I am, but as engineers, we are the ones who understand how to bridge the gap between human needs and AI execution. If we can find the right balance in this partnership, we can expand our “defensive range” and unlock ideas that were previously held back by platform limitations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e45fb61997ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is there a static equivalent in Kotlin?]]></title>
            <link>https://androidpollyanna.medium.com/is-there-a-static-equivalent-in-kotlin-7e942e72a311?source=rss-c8b790b253c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e942e72a311</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Pollyanna - Kotlin Development]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 14:38:26 GMT</pubDate>
            <atom:updated>2025-10-10T07:14:15.095Z</atom:updated>
            <content:encoded><![CDATA[<p>Before I started my Android journey, I actually spent some time learning basic Java concepts<strong>.</strong> Back then, the idea of “<strong>static</strong>” felt incredibly abstract. All that talk about “build time” versus “run time<strong>”</strong>? It was just so complicated! Later on, once I got my hands on a fantastic tool like <strong>Kotlin</strong>, I pretty much tossed the whole thing out of my mind<strong>.</strong></p><p>That is, until I recently dipped my toes back into some Java code and saw that familiar “boss” monster again. This time, though, a question suddenly popped into my head:</p><p><strong>Why doesn’t Kotlin have a </strong><strong>static keyword?</strong> Where did it go? Does Kotlin just not need it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*HmxDzajumn5QNgPH1gZgRg.png" /><figcaption>This image is generated by: <a href="https://www.codepng.app/">https://www.codepng.app/</a></figcaption></figure><h3>static in Java World</h3><p>To discuss this topic, we first need to clarify <strong>why Java needs the </strong><strong>static keyword</strong> — what problem is it designed to solve?</p><blockquote>static provides a mechanism that <strong>makes certain data or behaviors belong to the class itself rather than to any particular object</strong>.</blockquote><p>This mechanism has two main purposes:</p><h4>Allows data to be shared by all objects</h4><p>The main significance of <strong>static</strong> is that it allows data to be shared and accessed by <strong>all objects of a class without requiring an instance</strong> to be created. This prevents the scenario where every single object independently maintains duplicate copies of the same shared data. <strong>Crucially, this data or method can then be easily accessed and used by anything.</strong></p><p>For example, let’s consider a utility method for common checks:</p><pre>public class SystemUpdateUtils {<br>    public static boolean isTiramisu() {<br>        // check the system version<br>        // ...<br>    }<br>}</pre><p>By defining the isTiramisu() method as <strong>static</strong>, we <strong>don&#39;t need to instantiate</strong> the SystemUpdateUtils class to access this function in any object in the application.</p><h4>Enable utility data or methods to exist independently of specific objects.</h4><p>The underlying goal is to ensure <strong>tool data or utility methods aren’t owned by any specific object.</strong></p><p>Take the isTiramisu example above, or imagine we&#39;re developing an application that frequently requires mathematical calculations (such as distance, angles, or averages).</p><pre>public class MathUtils {<br>    public static double calculateDistance(double x1, double y1, double x2, double y2) {<br>        double dx = x2 - x1;<br>        double dy = y2 - y1;<br>        return Math.sqrt(dx * dx + dy * dy);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        double distance = MathUtils.calculateDistance(0, 0, 3, 4);<br>        System.out.println(&quot;Distance = &quot; + distance);<br>    }<br>}</pre><p><strong>This calculation logic doesn’t inherently belong to any specific object instance</strong> — it’s just a <strong>“toolbox method”</strong> used to assist computations elsewhere in the application.</p><p>So, if using <strong>static</strong> methods sounds so useful and logical, why is this operator nowhere to be seen in Kotlin?</p><p>Here’s my observation and understanding. If, after reading these points, you feel something crucial is missing or unconvincing, please feel free to reach out and discuss it!</p><h4><strong>Kotlin’s Solution: The </strong><strong>object Keyword</strong></h4><p>The main reason is that Kotlin uses its distinct <strong>object</strong> declaration to achieve the ideal Object-Oriented Programming (OOP) goal.</p><p>In Java, <strong>static</strong> methods and variables are often utilized for &quot;util&quot; or &quot;helper&quot; functions that don&#39;t depend on the state of any particular object. However, <strong>overusing </strong><strong>static can make the code hard to test and maintain.</strong> This is because static elements are tightly coupled to their class, making them difficult to mock or replace during testing.</p><p>Instead, for the original needs of <strong>utility functions</strong> or <strong>global access</strong>, Kotlin uses the <strong>object</strong> declaration.</p><p>For example, we can develop the SystemUpdateUtils in this way with Kotlin:</p><pre>object SystemUpdateUtils {<br>    fun isTiramisu():Boolean {<br>        // check the system version<br>        // ...<br>    }<br>}</pre><p>An object in Kotlin is essentially a <strong>singleton pattern</strong> that persists as long as the app is running (once it&#39;s initialized). We can store and access information that is <strong>cross-object</strong> and <strong>shouldn&#39;t depend on a specific instance</strong> within these objects.</p><p><em>(Note: Of course, good design patterns are still necessary to manage and organize these objects effectively!)</em></p><h4>The Elegant Usage of Companion Object</h4><p>Furthermore, if the need is to access a specific method <strong>without needing to instantiate any class</strong>, Kotlin allows us to define a <strong>companion object</strong> inside the class.</p><p>Although this object is syntactically <strong>attached to the class</strong>, it doesn’t require the class to be instantiated before it can be used. It looks just like the Java static call, but it’s a true object underneath.</p><p>This is often used for things like <strong>factory methods (Refer to Factory Pattern)</strong>, where you want to create an instance of a class without knowing the detailed steps.</p><pre>class User private constructor(val id: Int, val val name: String) {<br>  companion object {<br>    // This is a &quot;static&quot; method in spirit<br>    fun create(username: String): User {<br>        // Logic to look up ID or validate input<br>        val newId = username.length + 100 <br>        return User(newId, username)<br>    }<br>}</pre><h4>Defining Unattached Methods: Top-Level and Extension Functions</h4><p>In Java, it’s inevitable to see classes like XXXUtils or XXXManager—classes that serve no specific purpose other than being a container for static methods.</p><p>However, <strong>this design is a clear violation of the SOLID principles, specifically the Single Responsibility Principle (SRP).</strong> Over time, the convoluted member definitions within these utility classes become easy to forget and increase the risk of maintenance issues, such as <strong>reinventing the wheel</strong> with duplicate logic.</p><p>In these situations, Kotlin offers an elegant solution: <strong>top-level functions</strong> or <strong>extension functions</strong>.</p><p>Kotlin allows us to define functions directly outside of any class. This makes the code much cleaner and more readable because <strong>you don’t need to create an unnecessary class just to house these helper functions.</strong></p><p>A common scenario is converting a database entity into the data format required for a network response. This mapping logic doesn&#39;t belong to the entity class itself, nor should it sit in some random class.</p><pre>// entity definition<br>data class UserEntity()<br><br>// network data definition<br>data class UserResponse()<br><br>// our top-level extension function<br>fun UserEntity.toUserResponse(): UserResponse {<br>return UserResponse(<br>apiId = this.dbId.toString(), // Mapping logic<br>name = this.fullName,<br>lastActive = convertTimestampToDate(this.lastLogin) // Assume a helper function<br>)<br>}</pre><h3>Summary</h3><p>To summarize, here is how Kotlin addresses the needs typically handled by static in Java:</p><ol><li><strong>object declaration:</strong> Used to define a <strong>global singleton</strong>.</li><li><strong>companion object:</strong> Provides the convenience of a <strong>static method call without requiring class instantiation</strong>.</li><li><strong>Top-level functions:</strong> Defines utility functions that <strong>don’t need to be attached to any class at all</strong>.</li></ol><p>So, in fact, Kotlin didn’t eliminate the scenarios where static is used. Instead, it refined and compartmentalized the needs of static, implementing them with far more maintainable solutions. These alternatives make Kotlin code more flexible, readable, and highly compliant with modern Object-Oriented Design Principles<strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e942e72a311" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Android Jr Dev Journey ]— How to provide a flexible architecture with Strategy Pattern]]></title>
            <link>https://androidpollyanna.medium.com/android-jr-dev-journey-how-to-provide-a-flexible-architecture-with-strategy-pattern-1a8e78276c28?source=rss-c8b790b253c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a8e78276c28</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[sdk]]></category>
            <dc:creator><![CDATA[Pollyanna - Kotlin Development]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 13:45:23 GMT</pubDate>
            <atom:updated>2025-03-23T13:45:23.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5jngNhRYIboSxEJbVsBrg.png" /><figcaption>The image was exported by <a href="https://carbon.now.sh/">https://carbon.now.sh/</a></figcaption></figure><blockquote>As a junior engineer who has 1.5 years experience in Android, I often find myself working on SDK design in addition to regular app development. This presents a unique challenge: while our default implementation might be designed for scenario A, we must also consider how to accommodate scenario B smoothly when users have different needs.</blockquote><h3>Sample Dilemma: How to Support More Login Options in SDK in Simple Way</h3><p>If I need to design an auth module, and currently we only provide a native username-password login mechanism, I start to wonder:</p><p><em>if users integrate our SDK, how can they quickly connect other login methods?</em></p><p>As a newcomer to Android development, I start everything by following the MVVM architecture principles when get a new demand. Since authentication primarily belongs to the data layer, I initially thought the best approach would be to provide a repository-like interface for apps integrating this module.</p><p>So the first rough architecture would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*XsjBNWLQTDnUZHItrkNfpg.png" /></figure><ol><li>Define the login feature as an interface</li><li>Provide a default implementation through a concrete class</li><li>Inject this default object into the repository so that apps can easily use it.</li></ol><p>If we integrate authentication logic directly into AuthRepository, maintaining it becomes challenging—especially when supporting more than three login methods.</p><p>The main issue is that AuthRepository is responsible for two distinct concerns: exposing authentication functionality to the app and determining which AuthSource the user wants to use. This dual responsibility makes it overloaded and harder to manage.</p><p>To illustrate this problem more clearly, let’s look at a concrete example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*buDIvmDj6FgTzO34Z-ZnkQ.png" /></figure><p>For most apps nowadays, providing three or more login methods is quite common. However, it’s not a good idea to add a function every time a new source is introduced, as even if everything is packed into a single function, a large number of else if branches can still lead to a frustratingly complex and hard-to-maintain structure.</p><pre>class AuthRepository(...){<br>fun login(type){<br>   when(type){<br>     Default -&gt; DefaultAuthSource.login()<br>     Google -&gt; GoogleAuthSource.login()<br>     ...<br><br>   }<br>}<br>...<br>}</pre><p>For AuthRepository, this not only leads to a bloated structure but also violates the Single Responsibility Principle (SRP) in SOLID:</p><blockquote>The Single Responsibility Principle (SRP) is the concept that any single object in object-oriented programing (OOP) should be made for one specific function</blockquote><p>— — <a href="https://www.techtarget.com/whatis/definition/Single-Responsibility-Principle-SRP"><em>https://www.techtarget.com/whatis/definition/Single-Responsibility-Principle-SRP</em></a></p><h3>Strategy Pattern — Simplifying Complex else if Chains</h3><p>The Strategy Pattern is a design pattern that allows a family of algorithms or different implementations to be defined and encapsulated in separate classes. This makes it easy to swap one case for another without modifying the client code.</p><p>But how can it contribute to our work? Let’s go back to our auth module.</p><p>The main issue with the current AuthRepository is that it handles too many responsibilities. To address this, we can introduce a new object to take over the repository’s duty of managing different authentication data sources. Let me call this class AuthStrategy.</p><p>Also, you may have noticed that all of our authentication sources implement the same interface, allowing us to leverage type checking in Kotlin and Java. We can define a property in AuthStrategy to store all authentication sources in a single list and manage their behavior through unified functions. This way, apps can control which authentication source to use simply by modifying function parameters:</p><pre>class AuthStrategy(private val sources: List&lt;AuthSource&gt;){<br><br>fun login(index: Int){<br>    source[index].login()<br>}<br><br>fun login(index: Int){<br>    source[index].login()<br>}<br>}</pre><p>But Apparently this way is not clear enough: when the user of the SDK change the priority of these sources, their apps will suck up. So maybe we can use another type of Kotlin collection structure: map</p><p>The biggest advantage of using a map is that it stores data in key-value pairs, making it useful for retrieving values by their keys. To leverage this, we can declare an enum class to define different authentication types and map each type to its corresponding authentication source.</p><p>This way, whenever an app calls the login function, it simply provides an AuthType, and the strategy will automatically find the correct authentication source.</p><pre>enum AuthType{<br>DEFAULT, GOOGLE, TWITTER, FACEBOOK <br>}<br><br>class AuthStrategy(<br>private val sources: Map&lt;AuthType, AuthSource&gt; <br>  = mapOf(<br>      DEFAULT to DefaultAuthSource(),<br>      GOOGLE to GoogleAuthSource(),<br>      TWITTER to TwitterAuthSource(),<br>      FACEBOOK to FacebookAuthSource()<br>    )<br>){<br>fun login(authType: AuthType){<br>    source[authType].login()<br>}<br><br>fun login(authType: AuthType){<br>    source[authType].login()<br>}<br>}<br></pre><p>By eliminating complex if-else branches, AuthStrategy can be directly injected into AuthRepository, making it simpler and more maintainable. If an app needs to add a new login method, it only needs to update the auth sources map in AuthStrategy without modifying AuthRepository..</p><pre>class AuthRepository(strategy: AuthStrategy){<br>  fun login(authType: AuthType){<br>    strategy.login(authType)<br>  }<br><br>  fun logout(authType: AuthType){<br>    strategy.logout(authType)<br>  }<br><br>}</pre><h3>Final Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*Ohai2PWvgtmf1mlWbKjR8w.png" /></figure><p>By using the Strategy Pattern, we decouple authentication logic from AuthRepository, making the architecture more flexible and maintainable. New login methods can be added by updating AuthStrategy without modifying the repository. This improves <strong>scalability</strong>, <strong>readability</strong>, and <strong>adheres to SRP</strong>, ensuring a cleaner and more adaptable architecture design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a8e78276c28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android 出包日記 — 那些你以為面試之後就不用再碰的 Launch Mode 問題]]></title>
            <link>https://androidpollyanna.medium.com/android-%E5%87%BA%E5%8C%85%E6%97%A5%E8%A8%98-%E9%82%A3%E4%BA%9B%E4%BD%A0%E4%BB%A5%E7%82%BA%E9%9D%A2%E8%A9%A6%E4%B9%8B%E5%BE%8C%E5%B0%B1%E4%B8%8D%E7%94%A8%E5%86%8D%E7%A2%B0%E7%9A%84-launch-mode-%E5%95%8F%E9%A1%8C-d717aadd7e42?source=rss-c8b790b253c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d717aadd7e42</guid>
            <category><![CDATA[launch-mode]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Pollyanna - Kotlin Development]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 09:52:10 GMT</pubDate>
            <atom:updated>2024-06-04T09:52:10.616Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android 出包日記 — 那些你以為面試之後就不用再碰的 Launch Mode 問題</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUBPImYIWh1OzYcvyGPzfA.png" /></figure><p>作為菜鳥，我的日常就是去竭盡自己的力量追現有專案的架構了。追扣的過程中，總是會遇到一些 legacy code 看起來沒有很好讀，看起來做的事情好複雜，所以就偷雞摸狗的滑過去。</p><p>但前幾天我的主管給我一個很一針見血的建議： trace code 跟說扣時最不需要花時間看語法本身，因為這件事非常單純 ; 如果我可以多花心思思考這段 code 為什麼這樣設計、有什麼需求造成 code 這樣寫，那日後在維護 code 上比較能得心應手。</p><p>話才剛說完，我們在 trace code 的時候，就看到 Activity 有一段 code ：</p><pre>class Activity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>...<br>}<br><br>override fun onNewIntent(intent: Intent) {<br>    super.onNewIntent(intent)<br>    setContent{<br>     Greeting(name = &quot;我是誰？&quot;)<br>     }<br>}</pre><p>「Polly，你知道爲什麼要設置這個 Greeting 在 onNewIntent 嗎？」</p><p>看起來非常熟悉，但我在自己的大腦 Cache 找不到：）</p><p>「好的，那想給你一個作業，去研究一下 Luanch Mode」</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Gdtvm3bk1BIV-RpPgPbefQ.png" /></figure><p>一開始算是蠻煩躁的，覺得在面試的時候這個東西就偏背誦。不過如果我沒辦法在需求來臨的時候想到這個知識怎麼使用，那很顯然我沒有真的把這個概念學進去。</p><p>所以，我想要用比較有邏輯的方式，幫助自己重新理解 Launch Mode。</p><h3>為什麼我們會需要 Launch Mode?</h3><h4>Task 的設計</h4><p>task 指的是我們在手機裡面 activity 的集合，可以理解為讓一群 activity 疊在一起的容器。當我們點選某個 app ，預設上他會開一個 task ，然後放置 activity 。</p><p>如果有一個新的 activity 被開啟，那這個 activity 的狀態就會被暫存起來，然後被新的 activity 覆蓋過去。如果使用者點選了 back 按鍵，就會先從最上層的 activity 銷毀，退回之前的 activity 的 state 。因此 task 的設計，就是 FILO (first in last out) 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/0*K2U34An_ivm7rp6a.png" /><figcaption>取自官方文件：https://developer.android.com/guide/components/activities/tasks-and-back-stack#life-cycle</figcaption></figure><p>不過實際上我們在使用手機的時候，不可能只會開一個 app 。所以理所當然的，我們會有很多個 task 在管理不同的 app 。在這麼多個 task 中，被我們開啟並且手機螢幕呈現的那個 task ，就是 foreground task ，其餘的 task 都是 background task，activity 的狀態都被 stopped，等待使用者重新點開 app 被 resume。</p><p>不過問題就出在於，如果我今天在 task A 裡面某個 activity 裡面，跳轉到另一個 activity ，這個時候這個 activity 的狀態應該是什麼呢？是重新開一個實例，還是保存之前使用者的 state ?</p><h4>Activity 在 Task 的預設場景: Standard</h4><p>在預設的 standard 模式中，activity 只要被呼叫了，就是開一個新的實例、並且按 back 鍵就可以回去之前的 state 。但一定有一些場景是不希望這個行為發生的。舉例來說，如果有一個使用者在使用 premium 的時候被 expired 跳到付款頁面，老闆一定不希望他可以點 back 鍵直接偷用我們的付費服務對吧？這個時候就要使用到今天的主題 — — Launch Mode</p><p>我希望跟之前準備面試不一樣的是，我可以在紀錄實驗結果之虞，思考不同種 Launch Mode 對應的需求，以及舉出一個生活中的場景來應用 Launch Mode。</p><h3>Single Top : 跨 app 的時候，記憶 state 的簡單操作</h3><p>我覺得 singleTop 蠻單純的，在我點開這個 activity 的時候，我就只要看這個 activity 所屬的 task 最上面的 activity 是不是自己，如果是的話，我就重用這個 activity 並且呼叫 onNewIntent 這個 function 。</p><p>我覺得實際上的常見場景可能是跨 app 之間的操作，畢竟如果是自己的 task ，那 singleTop 發生的行為就會是自己 launch 自己，這太怪了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iuOPgkgqXikt9gDJ" /><figcaption>讓我們用網購衣服去情境來舉例：Photo by <a href="https://unsplash.com/@freestocks?utm_source=medium&amp;utm_medium=referral">freestocks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>但如果是：如果我今天在某網購 app 點選衣服瀏覽到一半，連尺寸跟顏色都選了，但想想還是冷靜一點，退了出去，跑去滑臉書。這個萬惡 app 為了鼓勵我買剛剛那件衣服，所以跳出了廣告 Notfication ，問我：「你還想要買這個商品嗎？這個商品正在打折！快點開查看：）」</p><p>這個時候我點擊了 Notification ，那 app 會期待我回去商品頁的時候，重新開這個頁面，我要重新選一次尺寸跟顏色嗎？</p><p>怎麼可能，那我就會直接放棄把荷包省下來了！</p><p>因此這個時候，就很適合使用 Launch Mode 中的 SingleTop : 當我點選回這個 app 的時候，直接回到剛剛瀏覽到一半的頁面，繼續我的購買流程。如果這時我的頁面需要有個修改：當使用者是中離再回來的時候，幫顧客打個小折並且把價格標成紅色，那就由 onNewIntent 出馬是再適合不過了：</p><pre>class ShoppingActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>...<br>}<br><br>override fun onNewIntent(intent: Intent) {<br>    super.onNewIntent(intent)<br>    setContent{<br>     viewModel.getNewPrice()<br>     showHightLight()<br>     }<br>}</pre><h3>Single Task: 即便在其他頁面跳轉的時候，我的 state 也需要被記得</h3><p>我們在 singleTop 會遇到一個限制：假設在同一個 app 裡面，我先去了某個 activityA 做了一些操作，又跑去另一個頁面 activityB ，又點某個按鍵（注意！不是按 back ）打開 activity A ，那這個時候原本 activity A 也不會被保存。原因是在 activityB 打開 activityA 的時候，此時的 task top 是 activityB ，所以 singleTop 並不會幫我們打開保存的 activityA。</p><p>不過有趣的是如果你這個時候一路按 back 回去，反而可以找到原本 activity A 的紀錄。</p><p>這個矛盾很顯然會成為一個 bug 對吧，因此這種情境下，我們會需要的是 singleTask 。在這個app 所屬的 task中，只有一個這個 activity A ，為了打開這個 activity A ，把其他頁面都銷毀掉也沒關係。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*9WTpRp9GHEwRMr1Q.png" /><figcaption>圖片來源：<a href="https://nextbigtechnology.com/launch-modes/">https://nextbigtechnology.com/launch-modes/</a></figcaption></figure><p>實作上，在 launch single task 的 activity 時，會去檢查這個 task 裡面有沒有這個 activity，如果有的話，就把在他上面的人全部銷毀掉，讓這個 activity resume。</p><p>因為 SingleTask 著重的重點是整個 task 這個 activity 只能有這個，並且因為可以把其他 activity 殺掉，可見這個 activity 的優先程度是高的。</p><p>實際在應用上，如果是剛剛那個網購 app ，我會認為在結帳頁面會是適合作為 singleTask 的場景。我就算結帳到一半，我仍然可以先切去其他商品頁面。但我切回來結帳時，作為使用者我會期待 app 不要忘記我正在填寫的使用者資訊狀態。</p><p>反過來說如果我在結帳頁面設置了 singleTop ，那這個時候我在同個 app 移去其他頁面，那除非我按 back 鍵回來，不然我點擊購物車頁面的話，就會是一個新的頁面，裡面沒有我之前填入的使用者資訊。</p><h3>Single Instance: 我是一個獨立且非常重要的頁面，不讓使用者返回</h3><p>Single Instance 的特色在於它是屬於一個獨立的 task 。因此我們在使用體驗上會有一個很明顯的水平切換的效果：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*PrSWq98xZ2Hbxkal.gif" /><figcaption>可以看到有一種切換 app 的視覺效果，並且沒辦法 back 回去前一個 activity</figcaption></figure><p>從上面的實驗結果可以看出 SingleInstance 的重點會放在：</p><p>1. 跟前面 activity 是不可逆的關係 (不過需要強調前面的 activity 並沒有被消除掉，只是所屬的 task 被退到 background 去了)</p><p>2. 所屬的 task 只會有這一個 activity ，並不會有其他 activity 把這個 activity 覆蓋掉</p><p>我自己有想到的場景是登入畫面：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CQhTgVFCI6Wd35UW" /><figcaption>Photo by <a href="https://unsplash.com/@onurbinay?utm_source=medium&amp;utm_medium=referral">Onur Binay</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>想像你現在也在用筆電享受網購的大尺寸體驗，但想到已經數年沒有換密碼，於是你在筆電換了密碼。</p><p>此時 app 應該要收到密碼更改的更新，理想上必須把使用者目前的使用暫存起來，並把使用者導到登入畫面對吧？就算使用者點選 back 鍵，app 都不會繼續讓還沒重新登入的使用者返回。</p><p>只有使用者完成了操作， app 也要記得帶使用者回原本的 task，而不是為了讓使用者完成登入，把使用者的操作都清掉也在所不惜，這就是 single task 跟 single instance 最大的差異。</p><p>像這樣，要逼迫使用者一定要完成的頁面，並且可以把這一頁跟其他頁面分開來管理的場景，就很適合 single instance。</p><h3>萬一我有更複雜的需求怎麼辦？</h3><p>也許有一些讀者會問：難道我只有這四種 Launch Mode 可以選嗎？難道我不能在 activity A 導過來的時候是 SingleTop，但其他場景導過來我都是 standard mode ?</p><p>有的，我們可以在 startActivity 的時候，帶上官方幫我們寫好的 <a href="https://developer.android.com/guide/topics/manifest/activity-element">intent action</a> ，這樣我們就可以指定在特定的 activity launch 時的 mode 。</p><pre>// manifest 是 standard mode<br>&lt;activity<br>    android:name=&quot;.ClearTopActivity&quot;<br>    android:exported=&quot;false&quot;<br>    android:label=&quot;@string/title_activity_clear_top&quot;<br>    android:theme=&quot;@style/Theme.LaunchModeLab&quot; /&gt;</pre><pre>// 實際在 launch Clear Top 時的狀態，會以 intent flag 為主覆蓋掉 manifest 的定義<br>val intent = Intent(this@StandardActivity, ClearTopActivity::class.java)<br>intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP<br>startActivity(intent)</pre><p>如果很不巧的，intent action 跟 manifest 上指定的 launch mode 有衝突，此時 intent flag 的優先度是比較高的，所以會以 intent 為主。我們可以把 intent flag 的設置當成 special case ，可以更自由地在 activity 使用不同的 launch mode ， intent 的定義比 launch mode 本身更多元細緻，可以有非常多種的場景是 launch mode 沒有包含，但可以使用 intent 來 launch 的。</p><p>覺得 launch mode 其實真的算東西比較繁瑣，說真的搞不好過一個月我就忘記 single task 在幹嘛了。但比起解說 launch mode 本身，我希望自己能更多培養用邏輯拆解原理，之後能隨機應變的能力才能高一些。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d717aadd7e42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android 出包日記： 我怎麼收不到自己發的 Broadcast ！ — 關於 implicit Intent 的系統限制]]></title>
            <link>https://androidpollyanna.medium.com/android-%E5%87%BA%E5%8C%85%E6%97%A5%E8%A8%98-%E6%88%91%E6%80%8E%E9%BA%BC%E6%94%B6%E4%B8%8D%E5%88%B0%E8%87%AA%E5%B7%B1%E7%99%BC%E7%9A%84-broadcast-%E9%97%9C%E6%96%BC-implicit-intent-%E7%9A%84%E7%B3%BB%E7%B5%B1%E9%99%90%E5%88%B6-16ec545d5754?source=rss-c8b790b253c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/16ec545d5754</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Pollyanna - Kotlin Development]]></dc:creator>
            <pubDate>Sun, 02 Jun 2024 11:01:13 GMT</pubDate>
            <atom:updated>2024-06-03T14:15:34.258Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android 出包日記： 我怎麼收不到自己發的 Broadcast ！ — 關於 implicit Intent 的系統限制</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WGHnhddnBT6k-FaYr-12aw.png" /></figure><h3>前情提要 — Android 14 的變革</h3><p>在 AOS 14 中，針對 Broadcast Receiver 新增了一些規範：</p><ul><li>在註冊 Broadcast Receiver 時，需要根據這個 receiver 能不能收到來自其他 app 的 broadcast 設置 Flag 為 RECEIVER_EXPORTED 或 RECEIVER_NOT_EXPORTED （如果是靜態註冊 receiver ，就需要添入屬性為 exported: true or false） 。</li></ul><pre><br>val listenToBroadcastsFromOtherApps = false<br>val receiverFlags = if (listenToBroadcastsFromOtherApps) {<br>    ContextCompat.RECEIVER_EXPORTED<br>} else {<br>    ContextCompat.RECEIVER_NOT_EXPORTED<br>}<br><br>ContextCompat.registerReceiver(context, br, filter, receiverFlags)<br>// 可以使用 Compat 來幫助我們處理 Android 惱人的版本兼容問題</pre><p>只要我們要收的廣播來源是其他 app ，不管是不是系統廣播（舉凡各種 intent filter 是從 android 原生提供的，那就是系統廣播），都需要把 flag 設置為 EXPORTED 。不過，如果是從系統發出的 Broadcast ，就會建議不要設置 flag （我懂，非常出爾反爾的規定）</p><p>舉個例子：假設今天有個 app 負責管理你的藍芽連線，雖然這個藍牙連線的廣播本身是 android 定義的，但因為我們要收的對象是 app ，那這個時候就需要設定為 EXPORTED ; 反之如果是系統發出的藍芽連線廣播，就不需要特別設定任何 flag 。</p><p>這裡要特別注意，如果有任何 Broadcast 沒有設置 tag ，會有 crash 發生，處理升版的朋友一定要記得特別注意。</p><h3>故事是這樣的</h3><p>某天早上剛吃完了早餐，想要來看 thread 活網時，slack 跳出了 PM 的緊急訊息：AOS 14 的用戶反應收到了聊天訊息的通知，在 notfication 傳送回覆訊息，卻沒有成功送出。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*nahs9A2m7NKS48BG.jpg" /><figcaption>我可能是只有 slack 訊息會找我，圖源：<a href="https://memes.tw/wtf?template=27152">https://memes.tw/wtf?template=27152</a></figcaption></figure><p>看著 PM 跳腳，我也不自覺緊張起來。聽起來似乎是我們的 app 跟 notfication 的聯繫之間出了什麼問題？</p><p>因為是我自己的 app 要接收來自自己的 Notification 廣播，所以我的 receiver 是這樣設置的：</p><pre>ContextCompat.registerReceiver(<br>  context, br, filter, ContextCompat.RECEIVER_NOT_EXPORTED<br>)</pre><p>插完 Log 發現，我的 receiver 似乎完全沒有 onReceive 到 Broadcast 進來。我看著我的 Broadcast 兩個小時，覺得他長得非常安好：</p><pre>Intent().also { intent -&gt;<br>    intent.setAction(&quot;com.example.broadcast.MY_NOTIFICATION&quot;)<br>    intent.putExtra(&quot;data&quot;, &quot;Nothing to see here, move along.&quot;)<br>    sendBroadcast(intent)<br>}</pre><h3>Implicit Intent hijacking</h3><p>後來我在官方網站針對<a href="https://developer.android.com/about/versions/14/behavior-changes-14"> AOS 14 的說明</a>中，有看到以下細節：</p><blockquote>Implicit intents are only delivered to exported components. Apps must either use an explicit intent to deliver to unexported components, or mark the component as exported.</blockquote><blockquote>If an app creates a mutable pending intent with an intent that doesn’t specify a component or package, the system throws an exception.</blockquote><p>回應到前期提要提到的 flag ，其實這樣的操作是為了避免<a href="https://developer.android.com/privacy-and-security/risks/implicit-intent-hijacking"> implicit intent hijacking </a>:</p><blockquote>The <a href="https://developer.android.com/guide/components/intents-filters#Types">implicit Intent</a> hijacking vulnerability occurs when an application does not specify a fully-qualified component class name or package when invoking an intent. This allows a malicious application to register an intent filter to intercept the intent instead of the intended application.</blockquote><p>很多惡意 App 會故意攔截其他 app 的 broadcast ，然後用自己的 app 去偷資料、或是影響別人的服務。這樣的狀況通常發生在我們的 intent 是隱式的，只有透過 filter 去過濾什麼樣的 app 可以用這個 intent ，但只要在這個 filter 中，我們的資料就有外流的風險。</p><p>為了避免這樣的問題，官方建議我們如果是自己要用的 broadcast ，可以用 explicit 標注明確給特定 app 使用的 intent ，並且由 flag 為 not exported 的 receiver 接收；而如果必須是 implicit intent ，就必須由 exported 的 flag 接收，並且不建議在 intent 裡面放置機密資訊。</p><p>這兩個邏輯算是相輔相成的。</p><p>回到我的問題，我的 receiver 為 not exported 的 receiver ，所以我就必須把我的 broadcast 的 intent 改成 explicit，在 intent 裡面 setPackage 為我自己的 package name:</p><pre>Intent().also { intent -&gt;<br>    intent.setAction(&quot;com.example.broadcast.MY_NOTIFICATION&quot;)<br>    intent.putExtra(&quot;data&quot;, &quot;Nothing to see here, move along.&quot;)<br>    intent.setPackage(BuildConfig.getApplicationId())<br>    // 指定 package name 跟 action 把 intent 轉成 explicit intent<br>    sendBroadcast(intent)<br>}</pre><p>我們的 Broadcast receiver 就正確接收到來自自己發出的 notification 操作了！</p><p>危機解除！開心</p><h4>PS: Receiver 可不可以直接設定成所有 api 都要 setFlag?</h4><p>不過回到一開始的狀態，不知道有沒有人思考過：</p><p>「如果只有 AOS 13 以上要在 register receiver 時要 setFlag, 那我可不可以就直接改成 setFlag 的版本呢？」</p><p>這邊可以連結到上一篇 《 <a href="https://medium.com/p/24d1ec1ad39f">Android 出包日記 — 版本更新難道不能簡單 RequiresApi 就好</a>》 ：如果讀者親自嘗試一次，會發現如果在 Api 32 以下的手機測試 set Flag ，會因為當時還沒定義這個 flag 而 throw 出 `java.lang.NoClassDefFoundError`</p><p>這次算是學到雖然 Android 版本兼容的問題很煩，但很多時候是有它的需求跟邏輯的。感覺之後需要督促自己看到新的規範時，從問題面著手思考，比較能避免這次只改一個地方、但另一個地方因為人家沒提到而漏改的問題發生。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16ec545d5754" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android 出包日記 — 版本更新難道不能簡單 RequiresApi 就好？！]]></title>
            <link>https://androidpollyanna.medium.com/android-%E5%87%BA%E5%8C%85%E6%97%A5%E8%A8%98-%E7%89%88%E6%9C%AC%E6%9B%B4%E6%96%B0%E9%9B%A3%E9%81%93%E4%B8%8D%E8%83%BD%E7%B0%A1%E5%96%AE-requiresapi-%E5%B0%B1%E5%A5%BD-24d1ec1ad39f?source=rss-c8b790b253c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/24d1ec1ad39f</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[轉職]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Pollyanna - Kotlin Development]]></dc:creator>
            <pubDate>Wed, 29 May 2024 08:48:40 GMT</pubDate>
            <atom:updated>2024-05-29T08:53:28.743Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android 出包日記 — 版本更新難道不能簡單 RequiresApi 就好？！</h3><p>今天開始，我想要每天寫個出包日記，記錄下每天最印象深刻的錯，並且要點到最深處的 Source Code ，了解整件事的相關原理。</p><p>先聲明一下，因為我還是一個很菜的工程師，之前做專案的態度很多都是能動就好，背後概念跟 Best Practice 都不是很懂。可能之後會有那種很小很基本的主題，但我希望我對自己的成長誠實，所以都會如實記錄下來，請大神勿噴。</p><p>今天就從升版開始說起。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*--Rcpj8HYBeTxUK2.jpeg" /><figcaption>圖片取自 Dcard: <a href="https://www.dcard.tw/f/meme/p/234517081">https://www.dcard.tw/f/meme/p/234517081</a></figcaption></figure><h3>故事是這樣的</h3><p>最近發現在 AOS 14 時，會強制檢查 Broadcast Receiver 在 AOS 13 的改動：在動態註冊 receiver 時，需要決定這個 broadcast 是不是可以被其他 app 聽到。</p><p>沒加的話可是會 crash 的喔，灰熊嚴重</p><p>回頭看看這段扣有黃色毛毛蟲，點開 Android Studio 給的提示：叫我要在 function 上加 RequiresApi</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*QrPPyNttEkTBBthHU_fhNQ.png" /></figure><p>拉拉手指，這還不簡單，我就點了人家的建議，在 function 上直接加了 Annotation 。commit 一下，發出 PR。結果不到一小時就被告知這樣改動完全錯誤，還是會在低版本的手機 crash 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*yZEiLlX3g-BJQYE7.jpg" /><figcaption>可能我跟我的 code reviewer 都是這樣想的。取自迷因庫：<a href="https://memes.tw/wtf/558325">https://memes.tw/wtf/558325</a></figcaption></figure><p>留著兩行熱淚，我滿頭疑惑：</p><p>一是原來加 RequiresApi 並不能避免 crash 嗎？那它的作用是啥 @@</p><p>二是那如果我今天要用很簡單漂亮而不要一堆 if else 的方式來做 AOS 版本管理，我可以怎麼做？</p><h3>About RequiresApi</h3><p>誠如上面所敘述， RequiresApi 就是個 Annotation 。<a href="https://developer.android.com/reference/androidx/annotation/RequiresApi">官方</a>的定義如下：</p><blockquote>Denotes that the annotated element should only be called on the given Android API level or higher.</blockquote><blockquote>This is similar in purpose to the older @TargetApi annotation, but more clearly expresses that this is a requirement on the caller, rather than being used to &quot;suppress&quot; warnings within the method that exceed the minSdkVersion.</blockquote><p>這個 Annotation 比較像輔助的效果，因為有一些物件跟 method 是新的 api 才有的，對於舊 api 來說這個物件是未知物件。為了避免開發者在低版本呼叫的時候呼叫到未定義的人，加入 Annotation 後會直接在編譯時就報錯。</p><p>這個 Annotation 並不會幫我們繞路迴避 crash 的結局，在低 api 呼叫未知物件，如果真的硬去呼叫，還是會往下執行，然後我們會遇到 `java.lang.NoClassDefFoundError` 的錯誤。但遇到這樣的錯誤本身，是因為我們沒有解決 「在低版本環境呼叫到高版本提供的 code 」的問題。</p><h3>Solution 1: 使用 if else 好嗎？</h3><p>其實這常常是我第一時間的解法，反正看到什麼東西需要條件，就用 if else 下去。</p><p>像這個 Case 也可以很單純，我大可以直接判斷 Build Version 就好：</p><pre>if(Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU) {<br>    this.registerReceiver(mReceiver, intent, SmsReceiver.RECEIVER_NOT_EXPORTED)<br>} else this.registerReceiver(mReceiver, intent)</pre><p>但後來有被提醒說，if else 很容易淪為 work around ，我們的程式碼會隨著每次的情境到處補丁，久而久之對於程式碼的可讀性跟維護性真的不是好事。</p><p>於是每次發出 PR 前都會去思考：這個 if / else 真的是必要的嗎？有沒有更 general 的寫法？</p><p>(結果搞出一個什麼RequiresApi )</p><p>但事實上，是真的存在比判斷 build version 更好更簡單的最佳解</p><h3>Solution 2: 使用 ContextCompat</h3><p>ContextCompat 是針對 Context 做的封裝，這是<a href="https://developer.android.com/reference/androidx/core/content/ContextCompat">官方文件</a>給的簡單有力定義：</p><blockquote>Helper for accessing features in <a href="https://developer.android.com/reference/android/content/Context.html">Context</a>.</blockquote><p>我覺得他還蠻像是 Android 為了 context 設計的語法糖的，需要 context 的 method 他通通都有提供，最厲害的地方，就是他<strong>有針對版本更新做了封裝</strong>。</p><p>就以 registerReceiver 來說，以下是 `ContextCompat.registerReceiver` 的 Source Code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*JQeRSz3MPk7gVUVT0FNdlQ.png" /></figure><p>所以只要呼叫 ContextCompat 並把我們所在位置的 context 丟進去， ContextCompat 就會自己幫我們確認版本了！我們根本不需要自己手寫做判斷：</p><pre>ContextCompat.registerReceiver(this, mReceiver, intent, RECEIVER_NOT_EXPORTED)</pre><p>這是我目前找到比較符合我的需求，也比較漂亮的 Solution</p><p>說實在話這是我第一次真的逼迫自己仔細往 Source Code 追，之前都是跟著其他大神的影片看一看，沒有自己真的找過答案。我覺得可能自己從 kotlin 開始學，或多或少有一點逃避看原生 Java 的東西。但如果不懂 Source Code ，可能要做到 Best Practice 永遠是天方夜譚。</p><p>很希望從今天開始，每天都可以學得更扎實一點！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24d1ec1ad39f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android 菜雞的一年轉職懶人包]]></title>
            <link>https://androidpollyanna.medium.com/android-%E8%8F%9C%E9%9B%9E%E7%9A%84%E4%B8%80%E5%B9%B4%E8%BD%89%E8%81%B7%E6%87%B6%E4%BA%BA%E5%8C%85-292f33b00d35?source=rss-c8b790b253c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/292f33b00d35</guid>
            <category><![CDATA[appworks-school]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[轉職]]></category>
            <dc:creator><![CDATA[Pollyanna - Kotlin Development]]></dc:creator>
            <pubDate>Tue, 28 May 2024 07:32:56 GMT</pubDate>
            <atom:updated>2024-05-28T07:32:56.801Z</atom:updated>
            <content:encoded><![CDATA[<p>好久沒有更新這裡的內容，想起第一次在 Medium 經營技術文章已經是一年以前的事情了，而隨性的文章是在更久之前的事情。</p><p>我目前算是成功轉職，以 Android 工程師的身份繼續學習下去。我目前自認自己算非常喜歡 Android 的領域，Android 需要花心思處理離線資料、甚至是跟底層的元件互動，都讓我覺得是蠻深奧的領域。工作快半年，遇到很多挑戰，但我還是想要在這個領域深耕茁壯。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2JiVSBJJO_aCrxaw" /><figcaption>Photo by <a href="https://unsplash.com/@rmrdnl?utm_source=medium&amp;utm_medium=referral">Daniel Romero</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>並且因為最近在工作上發現有很多自己覺得應該要會的內容，其實我沒有真的如自己期待的一樣超懂。我覺得可能要克服自己的方式，就是除了做 code lab 外，也要如實地把我的理解記錄下來，不能像過去一樣虎頭蛇尾。</p><p>這算是我這一季給自己的 OKR 吧！</p><p>不過這篇文章，想先簡單 go through 一下我一年的心路歷程。</p><h3>關於轉職之前的我</h3><p>其實雖說是轉職，其實現在 Android 工程師是我人生第一份工作。我在前年從大學畢業，本科是唸社會系的，除了統計軟體（ stata, spss, 很一點點的 R) 以外不會任何稱得上程式語言的東西，我當時也並不認為自己會跟軟體工程師牽扯得上關係。</p><p>我大學的時候，曾經是很篤定自己想要走學術的人。但不知道什麼時候開始，我有意識到自己在學術探索上的無力，這個無力包含自己能力不夠、也開始感受到不願意。我看到很多很有想法、論述能力也很強的人，嚴格來說我並不是特別突出的人。我開始思考生存在這樣的競爭環境中，真的是我想要的嗎？我真的對沒日沒夜的研究生活有這麼大的 commitment 嗎？還是說我其實只是對其他選擇沒有什麼想法？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VoEZIbmirhKhuszm" /><figcaption>Photo by <a href="https://unsplash.com/@miguel_photo?utm_source=medium&amp;utm_medium=referral">Miguel Henriques</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>於是我開始逼自己做一些新的事物，並規劃每半年就思考自己目前的嘗試是不是適合自己，如果不適合的話也要統整出理由，針對這個理由做些微調。一開始根據我對我自己的理解，不過就是可能對量化統計有一點辦法、也有被鼓勵學過更進階的統計理論。所以在研究所時期，去一家生科公司做資料分析。我負責了一個類似 inbody 儀器的產品，透過跟醫院的數據作誤差分析跟建模。</p><p>半年後，我覺得自己還算是喜歡寫程式、但想做更接近使用者的事情，於是那個時候就往前端學技術跟實習。一開始還沒有任何基礎，所以先去了另一家港商做 QA ，近距離學一些軟體知識。後來受到蠻多主管啟發、再加上自己在研究所覺得沒學到什麼東西，實在是有一點浪費時間，就休學衝一波了。</p><p>這個時候開始，我正式踏上了轉職軟工的路途，原本以為自己應該跟網路上的大神一樣，大概四個月就可以求職成功，沒想到自己一走，就走了一年。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9hGnJd_nSr8ttlZ8" /><figcaption>Photo by <a href="https://unsplash.com/@karlp?utm_source=medium&amp;utm_medium=referral">Karl Pawlowicz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>一開始去找工作的時候非常非常不順利，當時遇到了科技業寒冬，而且當時我完全是前端菜雞（說實在話我現在仔細想以當時的 side project 程度，敢去找工作可說是相當有勇氣），所以拿到面試的機會少之又少，當時是他們願意點開我的履歷我都跪謝的程度。轉職的路上非常孤單，遇到問題的時候沒人問、又怕別人問自己近況。當時很害怕跟大學同學聊天聊近況，不知道自己怎麼交代自己的狀態，又很怕自己兩頭空。當時的我真的遇到過那種開頭聊得很開心、後來聊到薪水開始拿非本科系、剛畢業開刀的老闆。每次去面試都是學測等級的焦慮（甚至不是指考，因為我對面試內容掌握度非常低）當時根本不是很理解 useRef 、MVC 是什麼，但面試前就是無腦通通背下來。</p><p>這個時期的我為了展現自己的企圖心跟積極，開始在 Medium 上面發文章，其實我覺得寫文章對瞭解一些基本知識真的蠻有幫助的，畢竟就是逼迫自己 output 出所有 input 過的內容。只是因為整理起來很煩瑣，就很有一搭沒一搭的更新，而且寫到後來會累，所以很常虎頭蛇尾XDDD</p><h3>巨人的肩膀： AppWorks School</h3><p>當時意外地剛好收到 Appworks School 的錄取，就想說搞不好可以再給自己一點 buffer 努力看看。</p><p>網路上應該有蠻多心得文了，就不流水帳紀錄裡面的瑣事。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1x8wwencyWRIqJzR.jpeg" /><figcaption>非本人照片，取自官方網站。最近 school 也有推出一些不需要全職投入的夜間班，非常推薦：<a href="https://school.appworks.tw/">https://school.appworks.tw/</a></figcaption></figure><p>如果說真的要給建議的話，就是需要在 Best Practice 跟敏捷開發之中取得平衡吧。School 真的是精神時光屋，每一次的專案都做得很趕，沒辦法規劃的很細。但我一直記得我的導師跟我說的：</p><blockquote>會寫程式的工程師到處都是，但工程師與工程師之間就差在有沒有處理到細節：包括 UI 有沒有對齊、小地方有沒有都做好，能夠一次到位，就是好的工程師。</blockquote><p>在寫專案的時候如果可以多思考別人為什麼要這樣寫？如果用我的寫法有什麼 Pros &amp; Cons ？多在寫程式之餘，思考程式語言的弦外之音，並且可以針對這樣的想法多問導師（我個人覺得最可惜的問法，就是拿一個根本官方文件就有的資料去問導師，而不是問為什麼。不過我有時候也會犯這種錯就是了…）</p><p>認真說真的很感謝 School，很難想像當時如果沒有選擇去 school ，自己的生活會有多不同，雖然那陣子真的是 … 很窮。跟前兩個月自己求職的狀況相比，完全理解一群人走的更遠是什麼意思。</p><p>可能是前面求職的不順利以及自己體認到專業技能上的不足，在這個階段的我變得很貪心，什麼都學、什麼文章都看到底，導師的任何建議都照做，即便畢業了也把自己的專案用好的架構拆掉重做。很鼓勵如果有自學者真的想要在 School 把基礎打磨好，就是多練習、並無條件吸收資深工程師的意見。</p><p>我覺得這段時間除了技術的成長，最大的成長應該是開始能對自己坦承吧。我覺得坦承其實也需要實力，需要看到這個知識背後有多複雜、坑有多深，才能確信自己其實只懂皮毛，也才能意識到這很正常，而不需要慌張地隱藏自己的一知半解而打腫臉充胖子。</p><p>後來大概畢業後一個月就找到工作了，當然不能說自己不努力，但這條路上只覺得自己很幸運，從實習的前輩、Appworks School 的導師到後來公司的面試官（？）都是大好人。</p><p>憑良心說我覺得不管台商外商，自己感受到的面試體驗都非常良好，雖然不是每一次都表現得很如意，但都遇到很願意花時間幫助自己跟分享自己經驗的面試官，每一次的面試真的都是跳耀性的成長。想說如果有讀者其實已經具備了一定程度的知識、也有拿得出手的 Side Project ，那很推薦就放手一博去面試看看，也許一開始不盡人意，但一定會越來越好。</p><p>當然我還是有遇過奇怪的面試，不過我只想在 Medium 口說好言，不該聽的都更新在面試趣（？？</p><p>很幸運自己走過這一切，但半年過去，我在這個技術上仍然有我需要克服的挫折，只要我還想在職涯上前進，我相信這段自學的路就不該結束。</p><h3>後記</h3><p>即便走過這條路，我仍然無法大膽推薦朋友勇敢轉職，因為裡面包含太多運氣成分了，我相信每一個人的轉職之路都有所不同。只能說我知道這條路真的很苦很孤單，可能還包括了些許的絕望，不知道自己到底會上到什麼樣的岸。也許實際上，人生這條路只要活著都不會真的上岸的，日後想必還會有許多轉折跟擱淺，但過程中的好與壞，相信都有機會成為未來的一道小小的靈光，走向柳暗花明的另一村。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=292f33b00d35" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>