<?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 Barr on Medium]]></title>
        <description><![CDATA[Stories by Barr on Medium]]></description>
        <link>https://medium.com/@weelow?source=rss-50c584f94be3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bdRgUTHiDbEuuOFb</url>
            <title>Stories by Barr on Medium</title>
            <link>https://medium.com/@weelow?source=rss-50c584f94be3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:51:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@weelow/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[Remember is Poison!]]></title>
            <link>https://medium.com/@weelow/remember-is-poison-0956bbc2ff60?source=rss-50c584f94be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0956bbc2ff60</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Barr]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 13:26:52 GMT</pubDate>
            <atom:updated>2026-07-01T15:50:48.719Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fs0djPKi1GsDq7pfNxzodg.png" /></figure><p><a href="https://medium.com/%40weelow/remember-%E6%98%AF%E6%AF%92%E8%97%A5-2ad03e8d45a3">Read in Chinese</a></p><h3>TL;DR</h3><p><strong>remember and effects aren&#39;t the poison — misappropriation is.</strong> Compose only <em>looks</em> like it runs on pure functions; the contract it actually keeps is the weaker <strong>idempotency</strong>, so local impurity is legitimate by design.</p><ul><li>A composable <em>describes</em> the UI but never <em>holds</em> the node (the node is unreachable), so state that must survive recomposition needs a home: that’s what remember is, and effects are the same idea for side effects.</li><li>App data belongs to the caller, so hoist it; UI-only state can stay internal until something needs to share or control it.</li><li>A command like scrollToItem isn&#39;t state, so model it as an event instead of forcing it through a remember key (and don&#39;t fetch business data in an effect).</li></ul><h3>§1 The remember and effect You Use All the Time</h3><p>Official docs love examples like this to teach state and side effects:</p><pre>val something by remember { mutableStateOf(...) }<br>LaunchedEffect(key) { ... }<br>val scope = rememberCoroutineScope()</pre><p>But doesn’t this clash with what the same docs preach — “hoist state,” “avoid side effects”?</p><h4>Declarative and Pure Functions</h4><p>Declarative UI: you describe what the screen looks like; the framework figures out how.</p><p>“Writing UI as a function” traces back to functional programming: starting with FRP (1997), converging in React into “UI is a pure function of state” (<strong>UI = f(state)</strong>) — Compose inherits this idea. That’s why f has to be a <strong>pure function</strong>: same input, same output, no side effects.</p><blockquote><em>Side effect: a function reading or writing something outside its own scope (a global variable, the network, state accumulated across calls). Once a side effect exists, the output can depend on the outside world or history — f stops being pure.</em></blockquote><h4>The Contradiction in the Official Example</h4><p>In that opening example, remember exists precisely so a value survives across <strong>recomposition</strong> — meaning the second time the composable runs, it sees the value from last time. That &quot;last time&quot; value isn&#39;t in the composable&#39;s parameters, which directly violates a pure function&#39;s &quot;same input, same output.&quot;</p><p>LaunchedEffect launches a coroutine that keeps running across recompositions — a violation of &quot;no side effects.&quot;</p><p>The docs encourage writing composables as pure functions, yet the very same docs recommend APIs that break purity. That’s the contradiction.</p><h4>The Creator’s Own Objection</h4><p>On 2024–11–23, Compose’s progenitor Jim Sproch called the official State page poison, on <a href="https://x.com/Zhuinden/status/1860130640232087981">X.com</a>:</p><blockquote><em>Yes, please treat that entire page as poison.</em></blockquote><blockquote><em>Yes, </em><em>remember {} is the original poison and is over used. The thing about remember is that there are a few legitimate use cases for it (eg. evanescent things, like animations), but it is largely overused and should generally be avoided when possible.</em></blockquote><p>Notice how narrow his bar is: legitimate use is rare — transient things, for instance — and everything else should be avoided whenever possible, far stricter than what the official docs teach. This isn’t a view he picked up in 2024; he’s held the same position for years — “poison” is just the heavier word he reached for this time.</p><blockquote><em>Note: “poison” is Sproch’s own sharp phrasing, not the Compose team’s official position — same direction, but the team doesn’t endorse the word.</em></blockquote><h4>If It’s Impure, Why Does It Exist?</h4><p>remember violates pure functions, Sproch calls it poison, and every declarative UI framework makes a similar purity compromise somewhere — yet Compose still ships it, and still teaches it as the official way.</p><p>Either this is a design flaw, or Compose UI was never a pure-function framework to begin with.</p><h3>§2 The Price of Being Declarative</h3><p>UI is a tree, and the framework’s job is to maintain it. In the imperative world, the client (the code using the framework) touches nodes by hand — addView, setText, invalidate. In the declarative world, the client only writes a description of &quot;what the UI looks like,&quot; and the framework takes over maintenance.</p><p>But the tree isn’t static — state keeps changing, and the framework has to keep the tree in sync. How to update it correctly is the core problem any declarative framework has to solve.</p><h4>The Mechanism</h4><p>Inside the declarative paradigm there are two paths: <strong>re-execution</strong> (Compose, React, SwiftUI, Elm) and <strong>fine-grained reactivity</strong> (Solid, Svelte 5).</p><p>Compose falls into re-execution: the client only hands over a description, never an action. For the framework to know what the tree currently looks like, it re-runs the description. In Compose this mechanism is called <strong>recomposition</strong> — when state changes, the framework calls the composable function again, computes the new result, and applies it. And the composable function being re-called is, underneath it all, just an ordinary Kotlin function.</p><h4>The Independence of Function Calls</h4><p>Since it’s just an ordinary function, its local variables live on that call’s <strong>stack frame</strong>: the moment the function returns, the frame — and its local variables — gets reclaimed. Recomposition is repeated re-calling, and every call gets a fresh frame, so naturally it can’t reach last time’s local variables. Most of the time this is clean, but components often need a value that “survives across recomposition,” and that’s where it breaks.</p><p>Say you want a TitlePanel component that shows three pieces of information: the title passed in by the caller, the current update time, and the time this component first appeared on screen. The intuitive way to write it:</p><pre>@Composable<br>fun TitlePanel(title: String) {<br>    val updateTime = System.currentTimeMillis().toString()<br>    val firstCompositionTime = System.currentTimeMillis().toString()<br>    Text(<br>        &quot;&quot;&quot;<br>        title = $title<br>        updateTime = $updateTime<br>        firstCompositionTime = $firstCompositionTime<br>        &quot;&quot;&quot;.trimIndent()<br>    )<br>}</pre><p>When the caller passes a new title, TitlePanel runs again:</p><ul><li>title changes with the caller — it&#39;s external input</li><li>updateTime gets recomputed on every re-run — it&#39;s a local variable, and that matches the semantics of &quot;current update time&quot;</li><li>firstCompositionTime is named to remember &quot;the first time,&quot; but in practice it&#39;s recomputed every time just like updateTime — what it actually captures is never the first time at all</li></ul><p>Values with this “survive across recomposition” semantic show up all over declarative UI development: a computed result that should only ever initialize once, an animation’s progress mid-flight, the scroll position the user has scrolled to.</p><p><strong>How the imperative world solves it: the view is its own container</strong></p><p>In the View system, the view object <em>is</em> the node — state just lives directly in the view’s fields:</p><pre>class TitleView(context: Context) : View(context) {<br>    private val firstDisplayTime = System.currentTimeMillis()<br><br>    fun setTitle(title: String) { /* ... */ }<br>}</pre><p>The view object is persistent — firstDisplayTime is computed once when the view is instantiated, and it lives as long as the view does. scrollView.scrollY / editText.getText() work the same way: values that need to survive across multiple updates naturally live inside the view.</p><p>But in the declarative world you don’t hold a reference to the view — that solution is off the table: <strong>the node is unreachable</strong>. You only write the description, you never touch the node, the spot is gone, yet you still need access to it.</p><h4>The Composition Layer and the Two-Layer Architecture</h4><p>A composable re-runs on every recomposition, but the node has to stick around: screen elements need to keep existing, receive interaction, animate. So something needs to sit between the description and the node: execute the description, track identity, diff the before/after, and sync it onto the node tree.</p><p>That’s the reason the <strong>composition layer</strong> exists — the necessary bridge that turns declarative syntax into a framework that actually runs.</p><p>To stay in sync, the composition layer needs to know how “this run’s description” maps to “last run’s node.” Compose’s answer is <strong>positional</strong>: every composable, by the position it appears at, gets matched to a fixed slot in memory, and that slot also remembers the node it produced. On recomposition, walking back to the same position — <strong>if it’s still the same composable, identity is unchanged</strong> — last time Text(&quot;A&quot;), this time Text(&quot;B&quot;), still the same Text; if the parameters changed, the new value just gets applied to its existing node (a <strong>property update</strong>). If a <em>different</em> composable now sits at that position, identity has changed, and that&#39;s an insert / remove / move — a <strong>structural change</strong>.</p><p>Compose’s implementation of this positional memory is called the <strong>SlotTable</strong>. <strong>It’s internal machinery the runtime built for itself, purely to stay in sync — it’s not exposed to the client.</strong></p><p>This is where Compose’s <strong>two-layer architecture</strong> comes from — description and implementation live in two separate layers:</p><p><strong>composable function</strong> | Declarative · Description layer</p><ul><li>Only writes “what it looks like,” never holds the node</li><li>The framework syncs your description onto a node for you</li></ul><p><strong>Modifier.Node</strong> | Imperative · Implementation layer</p><ul><li>Is the node itself — reads and writes its own fields directly, holds state</li><li>Custom drawing and gestures are written at this layer — no remember needed</li></ul><p>The imperative path never disappeared — it just got tucked into the framework’s foundation, somewhere you don’t touch while writing composables.</p><p>So a composable function is a <strong>describer</strong>, not a <strong>holder</strong>. But some state has to be held by <em>somebody</em> — who should own it?</p><p>firstCompositionTime&#39;s requirement can&#39;t be solved by Modifier.Node (the client never touches the node), and it can&#39;t be solved by local variables either (they recompute every time). The composition layer already has this positional memory mechanism on hand — the question is <strong>whether it should be exposed to the client</strong>.</p><h3>§3 Why remember Exists</h3><p>To answer that, start by asking what the client actually needs the framework to provide.</p><h4>Node Properties vs. Declarative Syntax</h4><p>A perfectly pure declarative model only needs one thing: <strong>binding declarations between state and layout style</strong>. Text(user.name), Column { ... }, Modifier.padding(16.dp) — these are pure descriptions, they don&#39;t depend on any runtime capability.</p><p>But UI isn’t only layout and style. Components need <strong>lifecycle</strong> (entering/leaving), <strong>animation</strong> (transitions), and to <strong>survive across recomposition</strong> (scroll position, expanded state) — these are node properties, and they go beyond describing pure layout and style.</p><p>The composition layer folds node properties and layout style into the same syntax: LaunchedEffect, animateFloatAsState, remember are all composable functions, mixed into the same layer of syntax as Text() / Column {}. The cost: the syntax is no longer purely a binding declaration — it starts touching runtime capability, and purity breaks.</p><p>Could you avoid the breakage — hoist every bit of state that node properties need all the way out, and keep the description pure?</p><h4>Everything Can Be Hoisted</h4><p>Technically, every stateful part on the client side can be hoisted: expanded, drag offset, cursor position — all of it can be pushed up to the caller.</p><p>The upside of hoisting everything: the composable function becomes a fully pure function — the description makes zero difference to how the framework recomposes it, and the purity promise is 100% delivered. <strong>This is exactly the road Elm took</strong>: reject component-local state entirely, all state lives in one Model.</p><h4>The Fatal Cost of Hoisting Everything</h4><ul><li><strong>API surface explosion</strong>: every piece of internal state becomes a caller parameter, and a component balloons into 10+ props</li><li><strong>Broken encapsulation</strong>: the caller is forced to manage the component’s internal mechanics (ripple, open/close toggles), and the component stops being reusable</li></ul><p>The lack of component-local state has drawn no shortage of complaints in the Elm community over the years — the concrete face of this cost.</p><h4>Mainstream Frameworks Choose Self-Containment</h4><p>Purity (hoisting everything) fights with <strong>self-containment</strong> (component-local state) — every declarative paradigm has to pick a side: Elm picked purity (rejecting component-local state); the mainstream — React, SwiftUI, Solid, Svelte 5, Compose — all picked self-containment.</p><p>A composable function tolerates local impurity in exchange for self-containment and composability. And now §1’s contradiction has an answer: the contract re-execution actually needs was never purity — it’s the weaker <strong>idempotency</strong>. Idempotency just means: however many times you recompute the same state, the <strong>UI result</strong> stays consistent, and it doesn’t lean on external values like globals or randomness. (Here “state” isn’t only the function’s parameters — it also includes two things the runtime stores for you: <strong>Snapshot</strong>, the observable state behind mutableStateOf, and <strong>SlotTable</strong>, what remember stores.) As long as the description makes no difference to how the framework recomputes it, purity can be broken locally. So Compose was never a pure-function framework — purity is the ideal it inherited, idempotency is the actual floor.</p><p>Self-containment is a design choice, not a technical necessity — but it has become the mainstream consensus. And if a component’s state has to survive across re-execution, something underneath has to provide a mechanism for it — that’s the shared design slot occupied by React’s useState, SwiftUI&#39;s @State, and Compose&#39;s remember { mutableStateOf() }.</p><h4>remember: A Design Choice That Hitches a Ride</h4><p>Once you’ve chosen self-containment, components need a way to hold internal state that survives re-execution. How?</p><p>A fact already established earlier: the composition layer already has positional memory (the SlotTable), built purely to stay in sync. This infrastructure naturally already has:</p><ul><li><strong>positional identity</strong>: no extra declaration needed — position alone tells you “same one”</li><li><strong>lifecycle binding</strong>: a group entering/leaving = the component appearing/disappearing, state automatically lives and dies with it</li><li><strong>survives across recomposition</strong>: the value is stored in a slot, later recompositions just read it back, no recompute</li><li><strong>hierarchical scope</strong>: the composable call tree = nested groups, parent/child scope is self-evident</li></ul><p>The internal, cross-recomposition state components need — expanded, scroll position, an animation mid-flight — needs exactly these properties.</p><p>The framework doesn’t need to build a whole separate mechanism — it just needs to open a door so the client can use the memory mechanism that already exists. That door is remember.</p><p>In implementation, remember is thin to the point of being nearly transparent — the whole thing is one line:</p><pre>@Composable<br>public inline fun &lt;T&gt; remember(crossinline calculation: @DisallowComposableCalls () -&gt; T): T =<br>    currentComposer.cache(false, calculation)</pre><p>It’s the only public wrapper around Composer.cache (the @ComposeCompilerApi slot read/write primitive) — even the framework&#39;s own components use it, none of them touch the underlying primitive directly.</p><p>Back to the earlier firstCompositionTime problem — wrap it in remember:</p><pre>val firstCompositionTime = remember {<br>    System.currentTimeMillis().toString()<br>}</pre><p>remember claims one slot in the current group: the first composition runs the lambda and stores the result in the slot; every subsequent recomposition just reads the same slot and skips the lambda. firstCompositionTime finally lives up to its name.</p><p>Three layers of binding emerge:</p><ul><li><strong>Local variable binds to execution identity</strong>: recomputed every time</li><li><strong>remember binds to composition identity</strong>: preserved across recomposition at the same position</li><li><strong>Parameter binds to the caller</strong>: external data that’s been hoisted out, owned by the caller</li></ul><p>remember / *Effect violate pure functions, but they <strong>don&#39;t violate idempotency</strong>: the SlotTable is identity continuity the framework maintains for you — it&#39;s not history you&#39;re secretly hoarding.</p><p>Effects that need a lifecycle are also built on top of remember: LaunchedEffect(key)&#39;s implementation is remember(key) { LaunchedEffectImpl(...) } — the key changes → remember recomputes → the old effect is disposed → the new effect launches. DisposableEffect works the same way. rememberCoroutineScope, rememberScrollState, animateFloatAsState are all consumers of remember.</p><p><strong>remember is the composition layer&#39;s one and only public interface to positional memory: the framework&#39;s own components and the client use the exact same API, on equal footing.</strong></p><h4>remember’s Designed Use Case: One Binding Declaration</h4><p>So remember&#39;s designed use case comes down to exactly one thing:</p><blockquote><strong><em>A value that needs to survive across recomposition, internal to the component</em></strong><em>: the caller’s contract doesn’t care about it — the composable function can just hold it itself.</em></blockquote><p>At bottom, remember { X } is a binding declaration: it binds X to this composable call&#39;s composition identity. There&#39;s nothing inherently right or wrong about the binding itself — which X should bind to composition identity, and which should be owned by the caller, is a question of <strong>placement</strong>.</p><h3>§4 Where Should State Live? Hoist or remember</h3><p>§3 established remember&#39;s designed use case: a value internal to the component that survives across recomposition. But which state actually counts as &quot;internal&quot;?</p><h4>Sproch’s Line: Hoist by Default</h4><p>The second half of §1’s quote is his complete position: legitimate use is rare, avoid everything else whenever you can. Turned into an operating rule: <strong>hoist by default, state always comes from outside</strong>. Write every component stateless, data flows in from the top. His <a href="https://jetc.dev/slack/2021-05-23-using-state-holders.html">2021 version</a> of the same idea:</p><blockquote><em>Read from the view model up at the top of your application and split it off into only the non-ViewModel data that your individual composables need.</em></blockquote><p>The ViewModel only lives at the top; everything below it only receives data and lambdas — components themselves hold no state.</p><p>He also gave <a href="https://jetc.dev/slack/2021-05-23-using-state-holders.html">an operational test</a>:</p><blockquote><em>If your composable does not behave well in Preview, that is almost always an indication your composable is not sufficiently isolated from the rest of the platform/application code.</em></blockquote><p>Why does Preview work as a test? Because Preview is the literal execution of UI = f(state): call f with one set of inputs, look at the screen. If all state can be injected, you just supply whichever inputs give you the screen you want. Conversely, state hidden inside remember can&#39;t be supplied that way. A component with an internal remember-ed expanded will run fine in Preview, but you can&#39;t specify the expanded = true screen — you&#39;d have to depend on actually running it.</p><p><strong>What he wants is for UI = f(state) to hold completely: state comes from the input, the only exception is anything transient.</strong></p><h4>The Classic Case: Form Values</h4><p>What most tutorials teach:</p><pre>@Composable<br>fun LoginForm() {<br>    var email by remember { mutableStateOf(&quot;&quot;) }<br>    var password by remember { mutableStateOf(&quot;&quot;) }<br><br>    TextField(value = email, onValueChange = { email = it })<br>    TextField(value = password, onValueChange = { password = it })<br>    Button(onClick = { /* submit */ }) { Text(&quot;Login&quot;) }<br>}</pre><p>email / password are app data typed in by the user — they need validation, they need submitting. remember looks like it&#39;s enough. <strong>But what if something external needs to change email dynamically?</strong> remember(key) resetting it still works, barely. <strong>Push further: what if something needs to append to the end of it dynamically?</strong> Now you need an effect, and you have to referee the user&#39;s own typing against an external write fighting over the same value. Every new requirement stacks another layer of machinery on top — all in service of a value that was never the component&#39;s to own. In §3&#39;s binding language: <strong>an X that belongs in the caller&#39;s hands got bound to the wrong identity</strong>.</p><p>The correct pattern:</p><pre>@Composable<br>fun LoginForm(<br>    email: String,<br>    password: String,<br>    onEmailChange: (String) -&gt; Unit,<br>    onPasswordChange: (String) -&gt; Unit,<br>    onSubmit: () -&gt; Unit<br>) {<br>    TextField(value = email, onValueChange = onEmailChange)<br>    TextField(value = password, onValueChange = onPasswordChange)<br>    Button(onClick = onSubmit) { Text(&quot;Login&quot;) }<br>}</pre><p>The caller (usually a ViewModel) holds email / password — the lifecycle is decided by the caller&#39;s own scope, no longer bound to the composition.</p><p><strong>remember holding app data = a misplaced binding</strong> — this is the textbook case behind Sproch&#39;s &quot;poison.&quot; It&#39;s like using a List as a Map: not a matter of taste, it&#39;s simply using the wrong tool. The same pattern generalizes to checklists, search bars, filter chips, settings screens.</p><blockquote><strong><em>remember nails state to the composition&#39;s lifecycle. For something purely internal, that&#39;s exactly the design. For something purely external, it&#39;s stuffing something long-lived into a short-lived container — and that&#39;s where the poison comes from.</em></strong></blockquote><h4>Pushback: UI Details Escalated to the Business Layer</h4><p>But Sproch’s line doesn’t stop at cutting form values. Under “hoist everything except transients,” every UI detail inside a component has to get pushed up to the caller — and §3’s cost of hoisting everything comes right back: API surface explosion, the caller forced to manage the component’s internal mechanics, the component no longer self-contained. Concretely: an isMenuOpen sitting inside a ViewModel.</p><p>Is opening and closing a menu really business logic?</p><h4>The Official Rule: Layer by Need</h4><p>The official docs don’t draw an absolute line — they give a <a href="https://developer.android.com/develop/ui/compose/state-hoisting">conditional rule</a>:</p><blockquote><em>Hoisting state isn’t always required. State can be kept internal in a composable when no other composable needs to control it.</em></blockquote><p>Two operational questions:</p><ul><li><strong>Who reads/writes it?</strong> Hoist to the lowest common ancestor of everyone who reads or writes it; if nobody else needs it, leave it internal.</li><li><strong>Does business logic touch it?</strong> Only hand it to the ViewModel if it does.</li></ul><p>The official docs classify values like this as <strong>UI element state</strong>: it originates from interaction inside the component, it’s not external data being poured in. The official ChatBubble example&#39;s showDetails (the same species as expanded) is left right inside the component. Opening and closing a menu isn&#39;t business logic.</p><h4>Two Axes: Where State Lives, Who Triggers the Change</h4><p>Sproch and the official docs seem to be arguing past each other, but they’re actually asking the same question: should state stay in the component or get handed off? Split that question apart and there are two independent axes. One: who does it serve. Two: who initiates its change — the component itself (mutating itself or firing a callback), or the outside. Lay out both axes and it becomes clear exactly where each side draws its line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MlROJIp33NzBIpqi4FDFIg.png" /></figure><p>Where it lives and who triggers it basically determine how you write it: External×External and Internal×Internal just mean keeping everything managed together, outside or inside; External×Internal is the classic <strong>Unidirectional Data Flow (UDF)</strong> — state flows down, events flow up; the <strong>?</strong> at Internal×External is saved for §5. The genuinely hard part is actually deciding whether a given piece of state counts as external or internal in the first place.</p><ul><li><strong>Sproch</strong>: tightest — for Internal×Internal, legitimate use is rare, e.g. transients (animation); things like expanded all get hoisted to External×Internal.</li><li><strong>Official</strong>: loosest — if expanded isn&#39;t shared, leave it at Internal×Internal; only push it out if it&#39;s shared or business logic touches it.</li></ul><p>A local variable derived by a pure computation (val showError = errors.isNotEmpty()) is completely uncontroversial — it always belongs inside, and most of the time you can skip remember entirely.</p><h4>Edge Cases: The Gray Zone That Could Go Either Way</h4><p>Whether a piece of state counts as internal or external depends on how it’s used. But some state can’t be pinned down at design time:</p><ul><li><strong>selectedTab</strong>: if it&#39;s only used internally, it&#39;s internal — but if it needs to support a deep link setting the current tab, it has to be externally controllable</li><li><strong>isMenuOpen</strong>: a self-contained menu counts as internal — but if it needs to be opened/closed programmatically, it has to be externally controllable</li></ul><p>In that case, hand the choice to wherever it’s used: the component defaults to remember-ing it itself (<strong>stateful</strong>); if the caller wants control, it passes the state in and holds it itself (<strong>hoisted to stateless</strong>):</p><pre>@Composable<br>fun rememberMyState(): MyState = remember { MyState() }<br><br>@Composable<br>fun MyComponent(state: MyState = rememberMyState()) {<br>    // caller can omit it (defaults to internal)<br>    // or hold it itself (hoisted to external)<br>}</pre><p>rememberLazyListState() / rememberScrollState() are both built this way: letting a component serve both the &quot;internal to the UI&quot; case and the &quot;controlled externally&quot; case at once.</p><h4>Back to UI = f(state)</h4><p>Which of a component’s state gets modeled as f’s input, injectable from outside, and which gets sealed into the internal implementation. All the disagreement is about how much UI state should be pushed outward; app data, on the other hand, both sides agree has to be hoisted.</p><p><strong>My standard: the requirement decides whether to hoist</strong></p><ul><li><strong>No requirement</strong>: leave it internal, remember is the right call.</li><li><strong>A requirement appears</strong> (needs sharing, needs to be previewable, business logic needs to read/write it): push it up — from inside the component, to a plain state holder at the screen layer, to the ViewModel.</li></ul><p>This is really just YAGNI: none of these requirements exist yet during prototyping, so reducing complexity comes first — only hoist once external injection is actually needed.</p><p><strong>Only understanding earns you the right to call it a choice</strong></p><p>By now you know: writing UI element state into remember uses a capability the composition runtime built purely for its own cross-recomposition memory. Used for the renderer&#39;s own job, that&#39;s exactly its intended role. The moment it&#39;s used <em>outside</em> that role — pressed into storing app data — that&#39;s <strong>misappropriation</strong>, that&#39;s debt, the same logic as the old trick of &quot;deriving a result implicitly from a pile of state&quot;: convenient right now, but the complexity gets buried in an implicit mechanism, and eventually nobody can follow it. What most tutorials teach is exactly this — using it this way without even realizing it.</p><p>When you’re not sure, this <a href="https://jetc.dev/slack/2021-03-07-stateful-rows-lazycolumn.html">line</a> of Sproch’s still holds:</p><blockquote><em>Hoisting state is never a bad idea.</em></blockquote><h3>§5 The Code Smell of scrollToItem</h3><p>There’s still one more situation: internal state, external control — the most common case being a ViewModel that needs to scroll a list to some item. This is exactly the “Internal×External” that §4’s table left with a question mark.</p><p>The most intuitive way to write it is one line: listState.scrollToItem(scrollTarget). But this line sits in the composable&#39;s body, and any change unrelated to scrollTarget will also trigger a recomposition that re-runs it — meaning updating some unrelated text could yank the list back to scrollTarget&#39;s position, completely against the requirement. scrollToItem is also a suspend fun in its own right, so it can&#39;t just sit in the body either — it needs a coroutine.</p><p>Wanting it to run only when scrollTarget changes means using its value as the trigger criterion — that&#39;s exactly remember&#39;s key: remember(key1 = scrollTarget) { ... }. But that suspend call still can&#39;t go inside remember&#39;s plain lambda — remember&#39;s block has to return a value at the end; it&#39;s a container for values, it was never meant to hold side effects. That suspend call can only be wrapped in a separate coroutine, and that coroutine has to follow the lifecycle of the composition and the key.</p><p>A coroutine like that is exactly what LaunchedEffect packages up for you:</p><pre>@Composable<br>fun ChatScreen(scrollTarget: Int) {<br>    val listState = rememberLazyListState()<br>    LaunchedEffect(key1 = scrollTarget) {<br>        listState.scrollToItem(scrollTarget)<br>    }<br>    LazyColumn(state = listState) { /* ... */ }<br>}</pre><h4>Not State — a Command</h4><p><strong>scrollTarget looks like state. It isn&#39;t.</strong> State is a value the description needs; and the description is what decides this UI tree&#39;s structure (control flow) and the property bindings on its nodes. The text in Text(message), the branch in if (open) — both are computed by the description reading state. But the description never uses scrollTarget: change it, and the tree comes out identical. It&#39;s only attached to LaunchedEffect&#39;s key, purely to trigger that one line of scrollToItem. It&#39;s a command, not state.</p><p>Recomposition exists to keep the screen in sync with state; but scrollTarget isn&#39;t bound to anything on screen — the recomposition it triggers doesn&#39;t reflect any state at all, it&#39;s purely being misappropriated to run LaunchedEffect&#39;s key comparison once and send a command. Worse: if the list was last scrolled to item 5, something else moves the position away, and you try to scroll to item 5 again — the key hasn&#39;t changed, the effect doesn&#39;t re-run, and you can&#39;t get back there. <strong>When it works, it&#39;s misappropriation; when it doesn&#39;t, it&#39;s a dropped command.</strong> You think you&#39;re declaring state; you&#39;re actually issuing a command.</p><h4>Switching to Event-Driven</h4><p>Where state relies on binding, a command can instead be modeled as an <strong>event</strong>. scrollToItem is a command — the most common way to handle it is to have the ViewModel emit the target position as an event, and have the UI execute it when the event arrives:</p><pre>@Composable<br>fun ChatScreen(scrollEvents: Flow&lt;Int&gt;) {<br>    val listState = rememberLazyListState()<br>    LaunchedEffect(Unit) {<br>        scrollEvents.collect { target -&gt; listState.scrollToItem(target) }<br>    }<br>    LazyColumn(state = listState) { /* ... */ }<br>}</pre><p>Every new event scrolls the list to the matching position; relying on an event instead of a key avoids that whole round of unrelated recomposition.</p><h4>effect</h4><p>And the LaunchedEffect used in both of these examples is a second concept within the declarative model: <strong>effect</strong>.</p><p>Outside the UI = f(state) paradigm’s description, there’s usually a lot of work left over: scrolling a list, running an animation, managing focus — all of them are the side effects §1 talked about (reading or writing something outside the function’s own scope). The description gets re-run over and over, and a side effect re-run along with it spirals out of control; so the declarative model gives this its own formal mechanism: declare <em>when</em> it should run, and hand execution over to the framework. That’s <strong>effect</strong>.</p><p>All of these operations are things the renderer itself wants — effect just picks the right moment to run them, which is exactly its job, the same logic as remember storing cross-recomposition state on the renderer&#39;s behalf.</p><h4>The Misappropriation of effect</h4><p>But effect can also get pressed into running business logic:</p><pre>@Composable<br>fun UserProfile(userId: String) {<br>    var user by remember { mutableStateOf&lt;User?&gt;(null) }<br>    LaunchedEffect(userId) {<br>        user = repository.fetchUser(userId)<br>    }<br>    // ...<br>}</pre><p>fetchUser is a business operation, yet it&#39;s been bound to the composition&#39;s lifecycle — rotate the screen and it re-fetches. Data like this belongs in the ViewModel.</p><p>The test is the same as before: who does it serve. scrollToItem is the renderer&#39;s own scrolling — putting it in an effect is its job. fetchUser fetches business data — putting it in an effect is misappropriation.</p><p>remember holds cross-recomposition state, violating &quot;same input, same output&quot;; effect produces side effects, violating &quot;no side effects.&quot; These are Compose&#39;s <strong>two sources of impurity</strong>.</p><h4>Bonus: What About Just Returning the Internal Handle?</h4><p>Back to the scrolling example — if all you want is to avoid that recomposition, what if you just return the component’s internal handle straight to the caller?</p><pre>// pushed out via a parameter, or returned directly<br>@Composable<br>fun ChatScreen(<br>    messages: List&lt;Message&gt;,<br>    onListStateReady: (LazyListState) -&gt; Unit,<br>    onScrollerReady: ((Int) -&gt; Unit) -&gt; Unit,<br>)<br><br>@Composable<br>fun ChatScreenAndReturnLazyListState(messages: List&lt;Message&gt;): LazyListState<br><br>@Composable<br>fun ChatScreenAndReturnScrollLambda(messages: List&lt;Message&gt;): (Int) -&gt; Unit</pre><p>The first pushes the handle out via a callback; the other two just return it directly. Once the outside world (usually a ViewModel outside the composition) has it, it can just call scope.launch { listState.scrollToItem(target) } itself. No scrollTarget parameter, so that round of recomposition is saved. But don&#39;t celebrate yet: a value-returning composable can&#39;t be skipped — the two return-based versions actually get recomposed <em>more</em> often, so you don&#39;t even win on performance. Only the callback version genuinely saves that round.</p><p>But it feels dirtier, doesn’t it — and nobody writes it this way? Because you’ve leaked a composition-scoped internal handle <em>outside</em> the composition, letting the business layer directly puppeteer the screen — which runs exactly against the whole point of being declarative: a composable’s only job is to describe; it shouldn’t leak an internal handle to the outside.</p><p>And even the official docs tell you not to do this! The <a href="https://github.com/androidx/androidx/blob/androidx-main/compose/docs/compose-api-guidelines.md">Compose API Guidelines</a> hit two rules at once:</p><ul><li><strong>“Emit XOR return a value”</strong>: a @Composable either emits content into the composition, or returns a value — never both. ChatScreenAndReturnLazyListState renders a LazyColumn <em>and</em> returns listState — it hits this exactly.</li><li><strong>Naming rules</strong>: a value-returning @Composable has to use camelCase — a PascalCase factory-style name is forbidden (only something returning Unit counts as &quot;a declarative entity that may or may not appear in the composition&quot;). So it&#39;s not even legal to call it ChatScreen.</li></ul><p>It’s no longer a declarative entity — it’s a factory.</p><p>And here’s the crux: that smell was never about performance. It comes from putting something imperative in a place declarative was never meant to hold — disguising a command as state, and leaking an internal handle past the layer boundary, are the same thing pointed in two directions. Most people can smell it without being able to say exactly what’s wrong. But by now, I think you can point at it too.</p><h3>§6 Conclusion: Impurity Is Inevitable — Misappropriation Is the Poison</h3><p>Compose borrowed functional programming’s banner — UI = f(state), the screen as a pure function of state. But between that ideal and a framework that actually runs, there’s a gap: the screen has to remember where it scrolled to, run animations, manage focus — all of it beyond what a pure function can do. What the framework ultimately holds the line on isn’t purity — it’s the weaker idempotency: recomputing has to produce the same result.</p><p>remember and effect live in that gap — the two sources of impurity. What the renderer needs for itself — remembering scroll position, running animations, managing focus — is the necessary toll for crossing that bridge. Stuffing app data into remember, or business logic into effect, is the <em>unnecessary</em> impurity.</p><p>Back to the question this piece opened with: are remember and *Effect the root of the poison? Yes — but that&#39;s not the point. <strong>Misappropriation is the poison.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0956bbc2ff60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[remember 是毒藥！]]></title>
            <link>https://medium.com/@weelow/remember-%E6%98%AF%E6%AF%92%E8%97%A5-2ad03e8d45a3?source=rss-50c584f94be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ad03e8d45a3</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Barr]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 09:44:41 GMT</pubDate>
            <atom:updated>2026-07-01T15:52:38.622Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fs0djPKi1GsDq7pfNxzodg.png" /></figure><p><a href="https://medium.com/@weelow/remember-is-poison-0956bbc2ff60">英文版</a></p><h3>TL;DR</h3><p>remember 跟 effect 不是毒，挪用才是。 Compose 只是「看起來」跑在純函數上；真正守的契約是更弱的冪等，所以局部不純是刻意的設計。</p><ul><li>composable 只描述 UI、從不持有 node（node 不可達），需要跨重組存活的 state 就得有地方落腳，那就是 remember；effect 對副作用是同一套邏輯。</li><li>app data 屬於 caller，一律 hoist；純 UI state 可留在內部，直到有共用或控制的需求才外提。</li><li>像 scrollToItem 這種命令不是 state，該建模成事件，別硬塞進 remember 的 key（也別在 effect 裡抓業務資料）。</li></ul><h3>§1 你常用的 remember 與 effect</h3><p>官方文件常用這類範例教學如何使用狀態與副作用：</p><pre>val something by remember { mutableStateOf(...) }<br>LaunchedEffect(key) { ... }<br>val scope = rememberCoroutineScope()</pre><p>但這寫法不就跟官方自己推薦的「狀態提升」、「避免副作用」打架了嗎？</p><h3>聲明式與純函數</h3><p>聲明式 UI：畫面長什麼樣由你描述，怎麼實現由框架負責。</p><p>而「把 UI 寫成函數」源自函數式編程：從 FRP（1997）開始，到 React 收斂成「UI 是 state 的純函數」（<strong>UI = f(state)</strong>），Compose 則是這個思想的繼承者。這就是為何 f 是<strong>純函數</strong>：同輸入同輸出、沒副作用。</p><blockquote><em>副作用：函數讀寫函式範圍外的東西（全域變數、network、跨呼叫累積狀態）。一有副作用，輸出就可能依賴外界或歷史，f 就不純了。</em></blockquote><h4>官方範例的矛盾</h4><p>開頭那份範例裡，remember 的目的就是讓值跨**重組（recomposition）**存活，意思是 composable 第二次跑時，看到的是上次的值。「上次的值」不在 composable 的參數裡，這直接違反純函數「同參數、同輸出」。</p><p>LaunchedEffect 啟動 coroutine 跨重組執行，違反「沒副作用」。</p><p>官方鼓勵把 composable 寫成純函數，範例卻直接推薦違反純函數的 API。這就是矛盾。</p><h4>創始者的反對意見</h4><p>2024–11–23，Compose 創始者 Jim Sproch 在 <a href="https://x.com/Zhuinden/status/1860130640232087981">X.com</a> 把<a href="https://developer.android.com/develop/ui/compose/state">官方 State 頁</a>罵成毒藥：</p><blockquote><em>Yes, please treat that entire page as poison.</em></blockquote><blockquote><em>Yes, </em><em>remember {} is the original poison and is over used. The thing about remember is that there are a few legitimate use cases for it (eg. evanescent things, like animations), but it is largely overused and should generally be avoided when possible.</em></blockquote><p>注意他的尺度：合法用途只有少數，例如瞬態，其餘能避則避，比官方教學窄得多。這不是 2024 才有的看法，他多年來都持相同論點，”poison” 只是他換上的更重的詞。</p><blockquote><em>注意：「poison」是 Sproch 個人的尖銳用詞，不是 Compose 團隊的官方立場，同方向但不背書這個詞。</em></blockquote><h4>如果這樣不純，為什麼需要？</h4><p>remember 違反純函數，Sproch 罵有毒，各個聲明式 UI 框架都有類似的純度妥協，但 Compose 還是提供它、推為官方教法。</p><p>要嘛是設計缺陷，要嘛 Compose UI 根本不是純函數框架。</p><h3>§2 聲明式的代價</h3><p>UI 是樹，框架則負責維護它。命令式裡 client（使用框架的程式碼端）親手操作 node（addView、setText、invalidate），聲明式裡 client 只寫「UI 長什麼樣」的描述，框架接管維護。</p><p>但樹不是靜態的，state 持續變，框架必須讓樹跟著更新。如何正確更新，就是聲明式框架的核心問題。</p><h4>原理</h4><p>聲明式範式內部有兩條路徑：<strong>重執行</strong>（re-execution；Compose、React、SwiftUI、Elm）跟 <strong>細粒度反應式</strong>（fine-grained reactivity；Solid、Svelte 5）。</p><p>Compose 落在重執行：client 只給描述、不給動作，框架要知道樹現在的樣子，就是重新跑一次描述，在 Compose 裡這個機制叫 <strong>重組</strong>（recomposition），state 變了，框架把 composable function 重新呼叫一次，計算新結果並套用，而被重新呼叫的 composable function 其實也只是一般的 Kotlin 函數。</p><h4>函數呼叫的獨立性</h4><p>既然只是一般函數，局部變數就活在這次呼叫的 <strong>stack frame</strong> 上：函數一 return，frame 連同局部變數一起回收。重組是反覆重新呼叫，每次都是新的 frame，自然拿不到上次的局部變數。多數時候這很乾淨，但組件常有「<strong>跨重組保留</strong>」的值，這時就出問題。</p><p>假設要做一個 TitlePanel 組件，顯示三層資訊：caller 傳進來的 title、本次更新時間、這個組件首次進入畫面的時間。直覺上會這樣寫：</p><pre>@Composable<br>fun TitlePanel(title: String) {<br>    val updateTime = System.currentTimeMillis().toString()<br>    val firstCompositionTime = System.currentTimeMillis().toString()<br>    Text(<br>        &quot;&quot;&quot;<br>        title = $title<br>        updateTime = $updateTime<br>        firstCompositionTime = $firstCompositionTime<br>        &quot;&quot;&quot;.trimIndent()<br>    )<br>}</pre><p>當 caller 傳新的 title，TitlePanel 被再次執行：</p><ul><li>title 跟著 caller 改，是外部輸入</li><li>updateTime 每次重新執行都重算，是局部變數，符合「本次更新時間」這個語意</li><li>firstCompositionTime 名字想記「首次」，實際卻跟 updateTime 一樣每次重算，拿不到的根本不是首次</li></ul><p>這類「跨重組保留」語意的值在聲明式 UI 開發裡不少：只該初始化一次的計算結果、進行中的動畫進度、user 滑到的 scroll 位置。</p><p><strong>命令式怎麼解：view 自己就是容器</strong></p><p>View 系統裡 view 物件就是 node 本身，狀態直接放在 view fields：</p><pre>class TitleView(context: Context) : View(context) {<br>    private val firstDisplayTime = System.currentTimeMillis()<br><br>    fun setTitle(title: String) { /* ... */ }<br>}</pre><p>view 物件是持久的，firstDisplayTime 在 view 實例化時算一次，跟著 view 活到 view 死。scrollView.scrollY / editText.getText() 同理：跨多次更新保留的值自然活在 view 裡。</p><p>但聲明式裡你不持 view 引用，這條解法用不上：node <strong>不可達</strong>，你只寫描述、不碰 node，位置沒了，但依舊需要訪問它。</p><h4>組合層與雙層架構</h4><p>composable 每次重組都重新執行，node 卻必須留著：畫面元件要持續存在、接收互動、做動畫。描述跟 node 之間就需要一層機制：執行描述、追蹤 identity、diff 前後差異、同步到 node tree。</p><p>這就是<strong>組合層</strong>存在的理由：聲明式從「語法」變成「能運作的框架」的必要橋接。</p><p>組合層要同步，就得知道「這次的描述」跟「上次的 node」怎麼對應。Compose 的辦法是<strong>按位置</strong>：每個 composable 按它出現的位置，在記憶裡對到固定的一塊，那塊也記著它產出的 node。重組時走回同一個位置，<strong>若還是同一個 composable，identity 不變</strong> — — 上次 Text(&quot;A&quot;)、這次 Text(&quot;B&quot;)，同一個 Text，看參數變了就把新值套到它的 node 上（<strong>屬性更新</strong>）；若位置上換成別的 composable，identity 變了，就是 insert / remove / move 的<strong>結構變動</strong>。</p><p>這套按位置的記憶，Compose 的實作叫 <strong>SlotTable</strong>。<strong>它是 runtime 為了同步而自建的內部設施，不對 client 開放。</strong></p><p>這帶出 Compose 的<strong>雙層架構</strong>，描述與實作分屬兩層：</p><p><strong>composable function</strong>｜聲明式 · 描述層</p><ul><li>只寫「長什麼樣」，不持有 node</li><li>框架替你把描述同步成 node</li></ul><p><strong>Modifier.Node</strong>｜命令式 · 實作層</p><ul><li>node 自身，直接讀寫自己的 fields、放 state</li><li>custom draw、手勢從這層寫，不靠 remember</li></ul><p>命令式那條路沒消失，只是被收進框架底層，不是你寫 composable 時碰的。</p><p>所以 composable function 是<strong>描述者</strong>，不是<strong>持有者</strong>。但 state 總得有人持有，owner 該是誰？</p><p>firstCompositionTime 的需求，Modifier.Node 解決不了（client 不碰 node），局部變數也解決不了（每次重組都重算）。組合層手上有的按位置記憶機制，問題是<strong>是否該暴露給 client？</strong></p><h3>§3 為什麼 remember 存在</h3><p>要回答這個，先看 client 到底需要框架提供什麼。</p><h4>節點特性與聲明語法</h4><p>絕對純度的聲明式只需要一件事：<strong>狀態與佈局樣式的綁定聲明</strong>。Text(user.name)、Column { ... }、Modifier.padding(16.dp)，這些是純描述，不依賴任何執行期能力。</p><p>但 UI 不只佈局跟樣式。組件需要 lifecycle（進場 / 離場）、animation（過渡）、跨重組保留（scroll position、展開狀態），這些是<strong>節點特性</strong>，超出純佈局樣式的描述。</p><p>組合層把節點特性跟佈局樣式收進同一種語法：LaunchedEffect、animateFloatAsState、remember 都是 composable function，跟 Text() / Column {} 混在同一層語法。代價是，語法不再只是純綁定聲明，開始觸及執行期能力，純度破壞。</p><p>那能不能不破壞，把所有節點特性需要的 state 全部 hoist 到外部，保持描述純粹？</p><h4>萬物皆可 hoist</h4><p>技術上，所有 client stateful 部分都可以 hoist：expanded、drag offset、cursor 位置通通可以推給 caller。</p><p>全 hoist 的好處：composable function 完全變 pure function，描述對框架重組完全無差別，純度承諾 100% 兌現。<strong>這正是 Elm 走的路</strong>：拒絕 component-local state，所有 state 一個 Model。</p><h4>全 hoist 的致命代價</h4><ul><li><strong>API surface 爆炸</strong>：每條 internal state 變 caller parameter，組件變成 10+ 個 props</li><li><strong>違反封裝</strong>：caller 被迫管組件 internal 機制（ripple、開合 toggle），組件也複用不了</li></ul><p>無 component-local state 長期在 Elm 社群招來不少抱怨，就是這條代價的具體呈現。</p><h4>主流框架選 self-contain（自包含）</h4><p>純度（全 hoist）跟 self-contain（component-local state）打架，聲明式範式必須選邊：Elm 選純度（拒絕 component-local），主流 React、SwiftUI、Solid、Svelte 5、Compose 全都選 self-contain。</p><p><strong>composable function 容忍局部不純，換來 self-contain 跟 composability</strong>。到這裡，§1 那個矛盾才有答案：重執行要的契約從來不是純函數，是更弱的 <strong>冪等（idempotent）</strong>。冪等就是同一份狀態重算多少次，UI 結果都一致，且不靠 global、random 這類外部值。（這裡的「狀態」不只函數參數，還含 runtime 替你存的兩樣：<strong>Snapshot</strong>（mutableStateOf 背後的可觀察狀態）和 <strong>SlotTable</strong>（remember 存的值）。）只要描述對框架怎麼重算無差別，純度就能局部破壞。所以 Compose 不是純函數框架；純函數是它沿用的理想，冪等才是底線。</p><p><strong>self-contain 是設計選擇、不是技術必然</strong>，但也已成為主流共識。而組件的 state 要跨重執行還在，底層就得有一套機制，這就是 React useState / SwiftUI @State / Compose remember { mutableStateOf() } 共享的設計位置。</p><h4>remember：搭便車的設計選擇</h4><p>選了 self-contain，就需要讓組件持有跨重執行的 internal state。怎麼做？</p><p>前面建立的事實：<strong>組合層為了同步已經有按位置記憶（SlotTable）。</strong> 這套基礎設施天然具備：</p><ul><li><strong>positional identity</strong>：不用額外宣告，按位置就知道「同一個」</li><li><strong>lifecycle 綁定</strong>：group 進入/離開 = 組件存在/消失，state 自動共存亡</li><li><strong>跨重組保留</strong>：值存進格子，後續重組直接讀回、不重算</li><li><strong>層級範圍</strong>：composable 呼叫樹 = group 巢狀，父子範圍不言自明</li></ul><p>組件內部的跨重組 state（expanded、scroll position、animation in-flight）需要的恰好就是這些特性。</p><p>框架不需要另建一套機制：<strong>開個口讓 client 也能用已經存在的記憶機制就夠了</strong>。這個口就是 remember。</p><p>實作上，remember 薄到幾乎透明，本體只有一行：</p><pre>@Composable<br>public inline fun &lt;T&gt; remember(crossinline calculation: @DisallowComposableCalls () -&gt; T): T =<br>    currentComposer.cache(false, calculation)</pre><p>它是 Composer.cache（@ComposeCompilerApi、slot 讀寫原語）唯一的公開封裝，連框架自己的組件都使用，不直接碰底層原語。</p><p>回到前面 firstCompositionTime 的問題，用 remember 把它包起來：</p><pre>val firstCompositionTime = remember {<br>    System.currentTimeMillis().toString()<br>}</pre><p>remember 在當前 group 的 slot 裡佔一格：第一次 composition 跑 lambda，存入 slot；後續重組直接讀同一格，跳過 lambda。firstCompositionTime 的名字承諾兌現。</p><p>三層綁定浮現：</p><ul><li><strong>局部變數綁定 execution identity</strong>：每次計算新值</li><li><strong>remember 綁定 composition identity</strong>：同一位置跨重組保留</li><li><strong>parameter 綁定 caller</strong>：hoist 出去的外部資料，歸 caller 持有</li></ul><p>remember / *Effect 違反純函數，但<strong>不違反冪等</strong>：SlotTable 是框架替你維護的 identity 連續性，不是你偷藏的歷史。</p><p>需要 lifecycle 的 effect 也建在 remember 之上：LaunchedEffect(key) 的實作是 remember(key) { LaunchedEffectImpl(...) }，key 變了 → remember 重算 → 舊 effect dispose → 新 effect 啟動。DisposableEffect 同理。rememberCoroutineScope、rememberScrollState、animateFloatAsState 全部是 remember 的消費者。</p><p><strong>remember 是組合層按位置記憶的唯一公開介面：框架組件和 client 用的是同一個 API，地位相同。</strong></p><h4>remember 的設計 use case：一條綁定聲明</h4><p>所以 remember 的設計 use case 只有一條：</p><blockquote><strong><em>組件內部跨重組保留的值</em></strong><em>：caller 契約不關心，composable function 自己持有就好。</em></blockquote><p>說到底，remember { X } 是一條綁定聲明：把 X 綁上這個 composable 呼叫的 composition identity。綁定本身沒有對錯；哪些 X 該綁 composition identity、哪些該歸 caller 持，是放置問題。</p><h3>§4 state 該住哪？hoist 還是 remember</h3><p>§3 立了 remember 的設計 use case：組件內部跨重組保留的值。但哪些 state 算「內部」？</p><h4>Sproch 的劃分：預設 hoist</h4><p>§1 引文的後半是他的完整立場：合法用途不多，其餘能避則避。換成操作規則：<strong>預設 hoist，state 一律從外部來</strong>。組件全寫成 stateless，資料從頂端進，他 <a href="https://jetc.dev/slack/2021-05-23-using-state-holders.html">2021 年的版本</a>：</p><blockquote><em>Read from the view model up at the top of your application and split it off into only the non-ViewModel data that your individual composables need.</em></blockquote><p>ViewModel 只活在頂層，往下只傳 data 跟 lambda，組件自身不持狀態。</p><p>他還給了<a href="https://jetc.dev/slack/2021-05-23-using-state-holders.html">一條操作化檢驗</a>：</p><blockquote><em>If your composable does not behave well in Preview, that is almost always an indication your composable is not sufficiently isolated from the rest of the platform/application code.</em></blockquote><p>Preview 為什麼能當檢驗？因為 Preview 就是 UI = f(state) 的字面執行：拿一組輸入呼叫 f，看畫面。state 全可注入，要哪個畫面就給哪組輸入。反過來，藏在 remember 裡的 state 給不到。內部 remember expanded 的組件在 Preview 跑得起來，但 expanded = true 的畫面你指定不出來，必須依賴實際運行。</p><p><strong>他要的就是讓 UI = f(state) 完全成立：state 從輸入來，例外只有瞬態。</strong></p><h4>經典案例：表單值</h4><p>絕大多數教學的教法：</p><pre>@Composable<br>fun LoginForm() {<br>    var email by remember { mutableStateOf(&quot;&quot;) }<br>    var password by remember { mutableStateOf(&quot;&quot;) }<br>    <br>    TextField(value = email, onValueChange = { email = it })<br>    TextField(value = password, onValueChange = { password = it })<br>    Button(onClick = { /* submit */ }) { Text(&quot;Login&quot;) }<br>}</pre><p>email / password 是 user 輸入的 app data，要驗證、要 submit。remember 看似夠用，<strong>那要讓外部動態改 email 呢？</strong> remember(key) 重置一下還行。<strong>更進一步，要動態在字尾補值呢？</strong> 這就得動用 effect，還得擺平使用者輸入和外部回寫搶同一個值。每加一層需求就多疊一層機制——全為了一個不該歸組件的值。用 §3 的綁定語意說：<strong>該歸 caller 持的 X，綁錯了 identity</strong>。</p><p>正確模式：</p><pre>@Composable<br>fun LoginForm(<br>    email: String,<br>    password: String,<br>    onEmailChange: (String) -&gt; Unit,<br>    onPasswordChange: (String) -&gt; Unit,<br>    onSubmit: () -&gt; Unit<br>) {<br>    TextField(value = email, onValueChange = onEmailChange)<br>    TextField(value = password, onValueChange = onPasswordChange)<br>    Button(onClick = onSubmit) { Text(&quot;Login&quot;) }<br>}</pre><p>caller（通常 ViewModel）持有 email / password，lifecycle 由 caller 自己的 scope 決定，不再綁 composition。</p><p><strong>remember 持 app data = 綁定錯位</strong>，這就是 Sproch 罵 poison 的經典案例。就像把 List 當 Map 用，不是品味，是用錯。同樣模式推廣到勾選清單、搜尋欄、filter chips、設定頁。</p><blockquote><strong><em>remember 把 state 釘在 composition lifecycle 上。對純內部，這正是它的設計；對純外部，就是把長命的東西塞進短命的容器，就是毒的來由。</em></strong></blockquote><h4>質疑：UI 細節上升到業務層</h4><p>但 Sproch 的線不只切掉表單值。照「除瞬態外全部 hoist」，組件裡的 UI 細節都得推給 caller，§3 講過的全 hoist 代價原樣回來：API surface 爆炸、caller 被迫管組件內部機制、組件不再 self-contain。具體畫面是：ViewModel 裡躺著一條 isMenuOpen。</p><p>難道開合 menu 是業務邏輯？</p><h4>官方的規則：按需求分層</h4><p>官方沒有一條絕對的線，給的是<a href="https://developer.android.com/develop/ui/compose/state-hoisting">條件規則</a>：</p><blockquote><em>Hoisting state isn’t always required. State can be kept internal in a composable when no other composable needs to control it.</em></blockquote><p>操作上兩問：</p><ul><li><strong>誰讀寫它？</strong>hoist 到所有讀寫者的最低共同祖先（lowest common ancestor），沒別人要就留內部</li><li><strong>業務邏輯碰不碰？</strong>碰，才交給 ViewModel</li></ul><p>官方把這類值歸為 <strong>UI element state</strong>：源自組件內互動、不是外部資料灌進來的。官方範例 ChatBubble 的 showDetails（expanded 的同款）就直接留在組件內部。開合 menu 不是業務邏輯。</p><h4>兩個軸：state 住哪、誰發起改變</h4><p>Sproch 和官方看似各執一詞，問的其實是同一個問題：state 該留組件還是交出去。把這問題拆開，有兩個獨立的軸。一，它為誰服務。二，它的改變由誰發起，組件自己（自改或發 callback），還是外部。兩軸一擺，每一方的線落在哪就清楚了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yokhFxuXClndmITjnMJFSA.png" /></figure><p>位置和發起基本決定寫法：外 × 外、內 × 內 就是統一放外/內一起管；外 × 內 是經典的<strong>單向資料流（Unidirectional Data Flow, UDF）</strong> — — 狀態下降、事件上升；內 × 外 那個 <strong>？</strong> 留到 §5。真正的難點反而是 state 到底算外還是內。</p><ul><li><strong>Sproch</strong>：最緊，合法用途不多，例如瞬態（動畫），expanded 這類一律 hoist 到外 × 內。</li><li><strong>官方</strong>：最鬆，expanded 沒共用就留內 × 內，要共用或業務碰才推外。</li></ul><p>而由衍生計算推導<strong>局部變數</strong>（val showError = errors.isNotEmpty()）則完全沒有爭議，一定是放在內部，多數情況還能省下 remember。</p><h4>邊界 case：可內可外的灰色地帶</h4><p>state 算內還算外，得先看用法。但有些 state，設計時無法確定該放內還是放外：</p><ul><li><strong>selectedTab</strong>：自己用算內部，但若要支援 deep link 設定當前 tab，就得能外部控制</li><li><strong>isMenuOpen</strong>：自包含 menu 算內部，但若要 programmatic 開合，就得能外部控制</li></ul><p>這時把選擇交給用它的地方：組件預設自己 remember（<strong>stateful</strong>），caller 要控制就傳 state 進來、自己持有（<strong>hoist 成 stateless</strong>）：</p><pre>@Composable<br>fun rememberMyState(): MyState = remember { MyState() }<br><br>@Composable<br>fun MyComponent(state: MyState = rememberMyState()) {<br>    // caller 可以不傳（UI 內部預設）<br>    // 也可以自己持（hoist 給外部）<br>}</pre><p>rememberLazyListState() / rememberScrollState() 都是這個設計：讓組件同時服務 UI 內部跟外部控制 case。</p><h4>回到 UI = f(state)</h4><p><strong>組件的 state，哪些建模成 f 的輸入、可被外部注入，哪些封進內部實作。</strong> 分歧全在 UI state 該外提多少；app data 則是兩邊都要求 hoist。</p><p><strong>作者的標準：需求決定是否 hoist</strong></p><ul><li><strong>沒需求</strong>：留內部，remember 合理。</li><li><strong>需求出現</strong>（要共用、要 preview、業務要讀寫）：往上提，組件內 → screen 層 plain state holder → ViewModel。</li></ul><p>其實這就是 YAGNI：原型期還沒這些需求，降低複雜度優先，真的需要外部注入再 hoist。</p><p><strong>理解才能稱作選擇</strong></p><p>讀到這裡你已經知道，UI element state 寫進 remember，用的是 composition runtime 為自己跨重組記憶而建的能力。用在 renderer 自己是它的本職；一旦用到本職外、拿去存 app data，就是挪用，就是債，跟「好幾個 state 隱式推導出結果」的老寫法同一個邏輯：當下省事，複雜性藏進隱式機制，久了沒人看得懂。絕大多數教學教的就是不知情地這麼用。</p><p>拿不準的時候，Sproch <a href="https://jetc.dev/slack/2021-03-07-stateful-rows-lazycolumn.html">這句</a>仍然成立：</p><blockquote><em>Hoisting state is never a bad idea.</em></blockquote><h3>§5 scrollToItem 的 code smell</h3><p>還有一種情境：內部狀態、外部控制，最常見的就是 ViewModel 要讓 list 捲到某一項。這正是 §4 表格裡那個留問號的「內 × 外」。</p><p>最直覺的寫法是直接放一行 listState.scrollToItem(scrollTarget)。但這行在 composable body 裡，scrollTarget 以外的變化也會引發重組再次執行，等於說某個 text 的更新都可能把 list 拉回 scrollTarget 的位置，完全違反需求。scrollToItem 本身也是 suspend fun，直接擺進 body 也不行，得有 coroutine。</p><p>只想在 scrollTarget 變時才執行，就得拿它的值當作觸發與否的判準，這正是 remember 的 key：remember(key1 = scrollTarget) { ... }。但那個 suspend 呼叫，remember 的普通 lambda 裡也擺不進去——remember 的 block 尾部要 return 一個值，是值的容器，本就不裝副作用。這個 suspend 只能另外包進一個 coroutine，而且這個 coroutine 還必須跟隨 composition 與 key 的生命週期。</p><p>這樣一個 coroutine 就是 Compose 打包好的 LaunchedEffect：</p><pre>@Composable<br>fun ChatScreen(scrollTarget: Int) {<br>    val listState = rememberLazyListState()<br>    LaunchedEffect(key1 = scrollTarget) {<br>        listState.scrollToItem(scrollTarget)<br>    }<br>    LazyColumn(state = listState) { /* ... */ }<br>}</pre><h4>不是 state，是命令</h4><p><strong>scrollTarget 看起來像 state，其實不是。</strong> state 是描述所需的值；而描述，就是決定這棵 UI 樹的結構（控制流）與 node 的屬性綁定。Text(message) 的字、if (open) 的分支，都是描述讀了 state 算出來的。但描述沒用到 scrollTarget：改它，樹一模一樣。它只掛在 LaunchedEffect 的 key 上、觸發那行 scrollToItem。它是命令，不是狀態。</p><p>重組是讓畫面跟上 state 的；但 scrollTarget 沒綁任何畫面，它一變引發的那輪重組不反映 state，純粹是挪用來讓 LaunchedEffect 的 key 比較跑一次、送出命令。更糟的是，上次捲到第 5 項後位置被別的因素移開，你再捲一次第 5 項，key 沒變、effect 不重跑，就回不去了。能動是挪用、不動是漏送。你以為在 declare 狀態，其實在下命令。</p><h4>改用事件驅動</h4><p>相較狀態靠綁定，命令其實可以建模成事件。scrollToItem 是命令，最主流的接法就是讓 ViewModel 把目標位置發成事件，在 UI 收到時執行：</p><pre>@Composable<br>fun ChatScreen(scrollEvents: Flow&lt;Int&gt;) {<br>    val listState = rememberLazyListState()<br>    LaunchedEffect(Unit) {<br>        scrollEvents.collect { target -&gt; listState.scrollToItem(target) }<br>    }<br>    LazyColumn(state = listState) { /* ... */ }<br>}</pre><p>每次新事件，清單就捲動到對應位置；靠事件、不靠 key，就避免了那輪無關更新的重組。</p><h4>effect</h4><p>而這兩個例子所用的 LaunchedEffect，就是聲明式中的另一個概念：effect。</p><p>UI = f(state) 範式下的描述之外，往往還有許多操作：捲動清單、跑動畫、管焦點，都是 §1 講的副作用（讀寫函式範圍外的東西）。描述會被反覆重跑，副作用跟著重跑就會失控；聲明式於是給這種事一個正式做法：宣告何時跑，執行交給框架。這就是 effect。</p><p>這些操作都是 renderer 自己要的，effect 替它們挑對的時機跑，是本職，跟 remember 替 renderer 存跨重組 state 同個道理。</p><h4>effect 的挪用</h4><p>但 effect 也可能被拿去跑業務：</p><pre>@Composable<br>fun UserProfile(userId: String) {<br>    var user by remember { mutableStateOf&lt;User?&gt;(null) }<br>    LaunchedEffect(userId) {<br>        user = repository.fetchUser(userId)<br>    }<br>    // ...<br>}</pre><p>fetchUser 是業務操作，卻綁上了 composition 的生命週期，螢幕一轉就重抓。這種資料本該活在 ViewModel。</p><p>判準還是那句，為誰服務。scrollToItem 是 renderer 自己的捲動，放 effect 是本職；fetchUser 抓的是業務資料，放 effect 就是挪用。</p><p>remember 持跨重組狀態，違反「同輸入同輸出」；effect 產生副作用，違反「沒副作用」。這就是 Compose 的兩個不純源。</p><h4>Bonus：直接回傳內部 handle 呢？</h4><p>回到捲動那例，如果只是避免重組，那直接回傳組件內部 handle 交給 caller 呢？</p><pre>// 用參數遞出，或直接回傳<br>@Composable<br>fun ChatScreen(<br>    messages: List&lt;Message&gt;,<br>    onListStateReady: (LazyListState) -&gt; Unit,<br>    onScrollerReady: ((Int) -&gt; Unit) -&gt; Unit,<br>)<br><br>@Composable<br>fun ChatScreenAndReturnLazyListState(messages: List&lt;Message&gt;): LazyListState<br>@Composable<br>fun ChatScreenAndReturnScrollLambda(messages: List&lt;Message&gt;): (Int) -&gt; Unit</pre><p>前者用 callback 把 handle 推出去，後兩個直接回傳。外部（往往是 composition 外的 ViewModel）拿到後，自己用 scope.launch { listState.scrollToItem(target) } 即可操作。沒有 scrollTarget 參數，那輪重組是省了。但別高興太早：回傳值的 composable 不能被 skip，後兩個回傳版反而更常被重組，連效能都不討好；真正省到那輪的只有 callback 版。</p><p>但感覺更髒了，還沒人這麼寫？因為你把一個 composition-scoped 的內部 handle 洩漏到 composition 外，讓業務層直接操控畫面，這正好完全違背聲明式的初衷：composable 只負責描述，不該向外洩漏內部 handle。</p><p>而且連官方都叫你不要這麼做！<a href="https://github.com/androidx/androidx/blob/androidx-main/compose/docs/compose-api-guidelines.md">Compose API Guidelines</a> 一次就點到兩條：</p><ul><li><strong>「Emit XOR return a value」</strong>：一個 @Composable 要嘛把內容發射進 composition、要嘛回傳值，不能兩者都來。ChatScreenAndReturnLazyListState 一邊渲染 LazyColumn、一邊把 listState 回傳出去，正好踩中。</li><li><strong>命名規則</strong>：回傳值的 @Composable 必須用 camelCase、禁止 PascalCase 工廠名（只有回傳 Unit 的才算「可出現或不出現在 composition 裡的宣告式實體」）。所以它連叫 ChatScreen 都不合法。</li></ul><p>它不再是宣告式實體，是個工廠。</p><p>這就是關鍵：那股 smell 從來不是來自效能。它來自你把命令式的東西放進了聲明式不該放的位置 — — 把命令偽裝成 state、把內部 handle 漏出層外，是同一件事的兩個方向。多數人聞得到味道，卻很難具體解釋。但讀到這裡，我想你也指得出問題了。</p><h3>§6 結語：不純必然存在，挪用才是毒</h3><p>Compose 借了函數式的招牌，UI = f(state)，畫面是 state 的純函數。但從理想到一個真能跑的框架，中間隔著一道鴻溝：畫面要記住捲到哪、要跑動畫、要管焦點，全都超出純函數的能力。框架最後守住的不是純函數，是更弱的冪等，重算結果必須相同。</p><p>remember 和 effect 就住在這道鴻溝裡，是兩個不純源。renderer 自己要的，記 scroll、跑動畫、管焦點，是過橋的必要成本；而把 app data 塞進 remember、把業務塞進 effect，則是不必要的不純。</p><p>回到開頭那個問題，remember 跟 *Effect 是毒的根源嗎？是，但這不是重點，挪用才是毒。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ad03e8d45a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s wrong with the two fixes for Nav3’s double-back crash: the modeling mistake behind debounce…]]></title>
            <link>https://medium.com/@weelow/why-double-tap-back-crashes-nav-3-debounce-and-dropunlessresumed-are-modeling-mistakes-c7569aa83072?source=rss-50c584f94be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7569aa83072</guid>
            <category><![CDATA[navigation-3]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Barr]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 16:03:17 GMT</pubDate>
            <atom:updated>2026-04-20T16:41:49.405Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x3sKJNd5A73vzPA-" /><figcaption>Photo by <a href="https://unsplash.com/@framesbyfin?utm_source=medium&amp;utm_medium=referral">Heidi Fin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What’s wrong with the two fixes for Nav3’s double-back crash: the modeling mistake behind debounce and dropUnlessResumed</h3><blockquote>Gating back with navigation’s derived UI state is a modeling mistake.</blockquote><p><a href="https://medium.com/@weelow/nav-3-%E7%82%BA%E4%BD%95%E9%81%87%E5%88%B0%E9%9B%99%E6%93%8A-back-%E5%B4%A9%E6%BD%B0-%E9%98%B2%E6%8A%96%E8%88%87-dropunlessresumed-%E7%9A%84%E5%BB%BA%E6%A8%A1%E9%8C%AF%E8%AA%A4-5b20bbff06eb">Read in Chinese</a></p><p>Double-tap back blows up in Nav3. The minimal symptom:</p><pre>NavDisplay(<br>    backStack = backStack,<br>    onBack = { backStack.removeLastOrNull() },<br>    ...<br>)</pre><p>The second tap pops an already-empty stack — crash, or a blank screen. Two patches are common in the wild: debounce (remembering lastClickTime), and the official recommendation dropUnlessResumed. Both lower the incident rate. Neither solves the problem; they just put the check in the wrong place.</p><p>The claim of this post: <strong>the arbiter of legality has to be the stack itself</strong>. The stack is the SSOT for this problem. Everything else — time deltas, flags, lifecycle state — is either unrelated to it or a derived copy of it. Using any of those to decide whether a back should fire is a modeling mistake.</p><h3>§1 Debounce: time isn’t state — modeling on the wrong axis</h3><p>Debounce looks like this:</p><pre>var lastClickTime = 0L<br>val onBack = {<br>    val now = SystemClock.uptimeMillis()<br>    if (now - lastClickTime &gt; 300) {<br>        lastClickTime = now<br>        backStack.removeLastOrNull()<br>    }<br>}</pre><p>It suppresses some incidents, but the core issue isn’t “it might swallow a legitimate click.” It’s that <strong>it never looks at the stack, not even once</strong>.</p><p>What is the stack’s state when the second back fires? This code doesn’t know and doesn’t ask. It just guesses on the time axis: “A second click within 300ms is probably an accident.” That’s forcing a stack-consistency problem onto the time axis — betting on 300ms and hoping for the best.</p><p>Two concrete failure modes:</p><ul><li><strong>Legitimate rapid taps, wrongly blocked</strong>: A → B → C, three layers deep, the user wants to pop two quickly — the second tap within 300ms gets eaten by the debounce.</li><li><strong>Stale click past the threshold, let through</strong>: the 301ms tap slips through. More realistic case: the project uses a longer exit transition animation, so the button stays clickable on screen for well over 300ms — debounce lets it through, applied to a stack that no longer belongs to it.</li></ul><p>The 300ms threshold is a naked guess: raise it and you block more legitimate clicks; lower it and stale clicks slip through more easily. Either way it’s wrong, because the axis is wrong — it’s asking about time, but the problem is asking about stack state.</p><h3>§2 dropUnlessResumed: derived state isn&#39;t SSOT — modeling on an out-of-sync copy</h3><p>The official recommendation wraps onBack in dropUnlessResumed:</p><pre>entry&lt;PageB&gt; {<br>    val onBack = dropUnlessResumed {<br>        backStack.removeLastOrNull()<br>    }<br>    PageScaffold(PageB) { BackButton(onClick = onBack) }<br>}</pre><p>The logic: if the current entry’s Lifecycle.State isn&#39;t RESUMED, drop the callback. After the first back, PageB enters its exit transition and the lifecycle drops to STARTED; the second back is caught on arrival.</p><p>One step better than debounce — at least it’s looking at Nav3’s lifecycle. But it still stands on the same underlying error: <strong>lifecycle state isn’t the stack; it’s a derived result of stack transitions</strong>. The stack changes first; the lifecycle catches up afterwards. There’s a sync delay between them, and that delay window is the hole.</p><p>Anywhere two sites fire onBack in the same frame, this layer is bypassed. For example: a &quot;delete all selected&quot; flow auto-calls onBack to return to the previous page when it finishes, and the user happens to press back at that exact moment — two onBack calls run back-to-back in the same event round, the lifecycle hasn&#39;t had a chance to drop to STARTED, the second call still sees RESUMED, and it goes through. Low probability, but not zero.</p><p>The stack has already changed; lifecycle state hasn’t caught up — this isn’t a bug in dropUnlessResumed. Using derived state as the arbiter of legality is inherently out of sync with the SSOT, and that out-of-sync gap is exactly where the problem slips through.</p><h3>§3 Back to SSOT: the trigger’s expectation, checked against the stack itself</h3><p>The fix is to stop routing through derived state. State the definition of legality directly: <strong>whoever triggered this back — what did they expect the stack to be? Does the actual stack still match?</strong></p><pre>entry&lt;PageB&gt; {<br>    val onBack = {<br>        if (backStack.lastOrNull() === PageB) {<br>            backStack.removeLastOrNull()<br>        }<br>    }<br>    PageScaffold(PageB) { BackButton(onClick = onBack) }<br>}</pre><p>Two things made explicit:</p><p><strong>What does PageB’s back expect?</strong> To remove itself from the top of the stack. That expectation is written straight into the entry&lt;PageB&gt; scope where the button lives — the button exists solely to let PageB leave, and the PageB key itself <em>is</em> the expected target. Nothing needs to be passed around or recorded.</p><p><strong>So legality collapses into a single question: is PageB still the stack top?</strong> backStack.lastOrNull() reads the stack&#39;s real current top, with no derived state in between; === compares referential identity, so only the same entry key instance passes. If it&#39;s still me, pop; if not, leave it alone.</p><p>Double-tap, same-frame double-fire, stale callbacks — under this predicate they all collapse into the same noop. If the stack top isn’t PageB, there’s no back to fire. No extra derived knowledge; only the stack, as the one source of judgment.</p><h3>§4 A modeling mistake, not an implementation detail</h3><p>The predicate lastOrNull() === PageB in §3 is just the degenerate form of this model for the pop-top case. The same principle extends directly to richer back semantics:</p><ul><li><strong>Sign-out cleanup</strong>: signing out has to remove every entry in the stack that’s “only legitimate when signed in,” in one shot. The predicate changes from lastOrNull() === PageB to backStack.removeAll { it.requiresAuth }; the arbiter is still the stack, with nothing in between.</li></ul><p>The shared structure is just one thing: <strong>the trigger carries an expectation about the stack, and the stack itself is the one thing you compare against.</strong> Debounce and dropUnlessResumed do prevent some problems, but they still miss the essence — they only happen to work on top of the wrong model.</p><h3>Appendix: the official discussion</h3><p>Google’s position and patch trail is scattered across three places — and pointedly absent from the primary guide pages:</p><ul><li><strong>Navigation 3 1.1.0-rc01 release note</strong> (<a href="https://developer.android.com/jetpack/androidx/releases/navigation3">developer.android.com/jetpack/androidx/releases/navigation3</a>): “NavDisplay now ensures that entries that are displayed underneath overlays have their Lifecycle capped at STARTED. This ensures APIs like dropUnlessResumed continue to work when using dialogs.&quot; Google officially treats dropUnlessResumed as the recommended guard, and has shipped a patch (<a href="https://issuetracker.google.com/issues/483966071">b/483966071</a>) specifically for cases where dialogs failed to drop the lifecycle.</li><li><a href="https://github.com/android/nav3-recipes/issues/107"><strong>android/nav3-recipes#107</strong></a>: “It is best practices for buttons to be wrapped in Lifecycle.dropUnlessResumed blocks to ensure we avoid any unintended double button presses.&quot; The official samples repo writes this into its best-practice list, then retrofits every onClick callsite in <a href="https://github.com/android/nav3-recipes/pull/225">PR #225</a>.</li><li><a href="https://issuetracker.google.com/issues/434109022"><strong>b/434109022</strong></a><strong> “dropUnlessResumed sometimes doesn’t prevent double taps”</strong>: Google’s own issue tracker confirms the guard leaks. This aligns with §2 of this article — using lifecycle as the arbiter of back legality is structurally leaky, not an implementation bug.</li><li><strong>dropUnlessResumed isn&#39;t a Nav3-native API</strong>: it ships from <a href="https://developer.android.com/reference/kotlin/androidx/lifecycle/compose/package-summary">androidx.lifecycle.compose</a> in Lifecycle 2.8.0, <em>before</em> Nav3 existed. It was a general lifecycle-aware click helper, then borrowed to serve as the Nav3 double-tap shim.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7569aa83072" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[修復 Nav3 雙擊 back 崩潰兩種方法的問題：防抖與 dropUnlessResumed 的建模錯誤]]></title>
            <link>https://medium.com/@weelow/nav-3-%E7%82%BA%E4%BD%95%E9%81%87%E5%88%B0%E9%9B%99%E6%93%8A-back-%E5%B4%A9%E6%BD%B0-%E9%98%B2%E6%8A%96%E8%88%87-dropunlessresumed-%E7%9A%84%E5%BB%BA%E6%A8%A1%E9%8C%AF%E8%AA%A4-5b20bbff06eb?source=rss-50c584f94be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b20bbff06eb</guid>
            <category><![CDATA[navigation-3]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Barr]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 16:03:13 GMT</pubDate>
            <atom:updated>2026-04-20T16:42:32.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UrKq8uCiB3Q1Ls7O" /><figcaption>Photo by <a href="https://unsplash.com/@framesbyfin?utm_source=medium&amp;utm_medium=referral">Heidi Fin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>用導航的衍生 UI 狀態判斷合法性就是建模錯誤</blockquote><p><a href="https://medium.com/@weelow/nav-3-%E7%82%BA%E4%BD%95%E9%81%87%E5%88%B0%E9%9B%99%E6%93%8A-back-%E5%B4%A9%E6%BD%B0-%E9%98%B2%E6%8A%96%E8%88%87-dropunlessresumed-%E7%9A%84%E5%BB%BA%E6%A8%A1%E9%8C%AF%E8%AA%A4-5b20bbff06eb">英文版</a></p><p>雙擊返回在 Nav3 會出事，最直接的症狀長這樣：</p><pre>NavDisplay(<br>    backStack = backStack,<br>    onBack = { backStack.removeLastOrNull() },<br>    ...<br>)</pre><p>第二次點擊把已經被 pop 空的 stack 再 pop 一次，app 閃退或畫面空白。社群常見的補丁有兩類：防抖（記 lastClickTime）與官方推薦的 dropUnlessResumed。兩類都能降低事故率，但都沒有解決這個問題，只是把判斷放在錯的地方。</p><p>本文的主張是：<strong>合法性的裁判必須是 stack 本身</strong>。stack 是這個問題的 SSOT，其他任何指標 — — 時間差、flag、lifecycle state — — 要嘛與它無關，要嘛是它的衍生副本。用這些判斷 back 能不能生效，就是建模錯了。</p><h3>§1 防抖：時間不是狀態，建模在錯的軸上</h3><p>防抖長這樣：</p><pre>var lastClickTime = 0L<br>val onBack = {<br>    val now = SystemClock.uptimeMillis()<br>    if (now - lastClickTime &gt; 300) {<br>        lastClickTime = now<br>        backStack.removeLastOrNull()<br>    }<br>}</pre><p>它能壓住一部分事故，但核心問題不是「會誤傷合法點擊」，而是<strong>它從頭到尾沒看 stack 一眼</strong>。</p><p>第二次 back 觸發時，stack 的狀態是什麼？這段程式碼不知道也不問。它只在時間軸上猜：「大概 300ms 內的第二次點擊都是誤觸吧。」這是把一個 stack 一致性問題，硬套到時間軸上建模，只是拿 300ms 兜底賭機率。</p><p>兩個具體失效場景：</p><ul><li><strong>合法連發被誤擋</strong>：A → B → C 三層，使用者想快速退兩層，300ms 內連按第二下 — — 被防抖吞掉。</li><li><strong>超過閾值的 stale 穿透</strong>：第 301ms 那下就穿過去了。更現實的場景：專案把離場 transition 動畫拉長，按鈕留在畫面上可點的時間直接超過 300ms — — 防抖放行，作用到已經不該它動的 stack 上。</li></ul><p>300ms 這個閾值是裸猜：調大誤擋更多，調小 stale 更容易穿透。兩邊都錯，因為軸選錯了 — — 它問的是時間，問題問的是 stack 狀態。</p><h3>§2 dropUnlessResumed：衍生狀態不是 SSOT，建模在不同步的副本上</h3><p>官方推薦把 onBack 包進 dropUnlessResumed：</p><pre>entry&lt;PageB&gt; {<br>    val onBack = dropUnlessResumed {<br>        backStack.removeLastOrNull()<br>    }<br>    PageScaffold(PageB) { BackButton(onClick = onBack) }<br>}</pre><p>邏輯是：若當前 entry 的 Lifecycle.State 不是 RESUMED，就丟棄 callback。第一次 back 觸發後 PageB 進入離場 transition，lifecycle 降為 STARTED，第二次 back 抵達時會被攔下。</p><p>比防抖好了一步 — — 它至少看了 Nav3 的生命週期狀態。但它仍然踩在同一個根本錯誤上：<strong>lifecycle state 不是 stack，而是 stack 變遷的衍生結果</strong>。stack 先改，lifecycle 才會跟著改；兩者之間有一個同步延遲，而這個延遲窗口就是漏洞。</p><p>只要兩個地方在同一幀都觸發 onBack，這層就被穿透。例如「刪除全部選中」完成後程式會自動呼叫 onBack 返回上頁，而使用者剛好在那一瞬間也按下 back——兩次 onBack 在同一輪事件中接連跑完，lifecycle 還來不及降到 STARTED，第二發看到的仍是 RESUMED，直接放行。機率不高，但不是零。</p><p>stack 已經變了，lifecycle state 還沒跟上 — — 這不是 dropUnlessResumed 的 bug，是拿衍生狀態當合法性裁判本身就會與 SSOT 不同步，那段不同步的空檔就是問題鑽進來的地方。</p><h3>§3 回到 SSOT：觸發者的預期對照 stack 本身</h3><p>要徹底處理，就要停止從衍生狀態繞路。合法性的定義直接寫成：<strong>觸發 back 的那個人，對 stack 有什麼預期？實際的 stack 是不是還符合？</strong></p><pre>entry&lt;PageB&gt; {<br>    val onBack = {<br>        if (backStack.lastOrNull() === PageB) {<br>            backStack.removeLastOrNull()<br>        }<br>    }<br>    PageScaffold(PageB) { BackButton(onClick = onBack) }<br>}</pre><p>兩件事講清楚：</p><p><strong>PageB 的 back 預期是什麼？</strong> 把自己從 stack top 移除。這個預期直接寫在它所在的 entry&lt;PageB&gt; scope 裡——按鈕只為讓 PageB 離開而存在，PageB 這個 key 就是預期目標，不需要額外傳遞或記錄。</p><p><strong>所以合法性就變成一個問題：PageB 現在還是 stack top 嗎？</strong> backStack.lastOrNull() 讀 stack 當下的真實頂部，不經過任何衍生狀態；=== 比 referential identity，同一個 entry key 實例才通過。是自己才 pop，不是自己就放著。</p><p>雙擊、同幀雙發、stale callback，在這個判斷式下全部收斂成同一句 noop — — stack top 不是 PageB，就沒有 back 可以生效。沒有額外衍生知識，只有 stack 作為唯一判斷來源。</p><h3>§4 建模錯誤不是實作細節</h3><p>§3 的判斷式 lastOrNull() === PageB 只是這個建模在 pop-top 情境下的退化形式。同樣的原則可以直接延伸到更複雜的 back 語意：</p><ul><li><strong>會員登出清場</strong>：登出要把 stack 裡「只在已登入情境下合法」的 entry 一次性移除。判斷式從 lastOrNull() === PageB 換成 backStack.removeAll { it.requiresAuth }；裁判仍然是 stack，沒有其他中間層。</li></ul><p>共通結構只有一個：<strong>觸發者帶著對 stack 的預期，stack 本身就是唯一的對照基準。</strong> 防抖與 dropUnlessResumed 的確能避免某些問題，但依舊未達本質，只是在錯誤的建模上碰巧可行罷了。</p><h3>附錄：官方討論</h3><p>官方立場與修補軌跡散落在三個地方，主要文件頁反而沒收錄：</p><ul><li><strong>Navigation 3 1.1.0-rc01 release note</strong>（<a href="https://developer.android.com/jetpack/androidx/releases/navigation3">developer.android.com/jetpack/androidx/releases/navigation3</a>）：「NavDisplay now ensures that entries that are displayed underneath overlays have their Lifecycle capped at STARTED. This ensures APIs like dropUnlessResumed continue to work when using dialogs.」—— Google 把 dropUnlessResumed 正式視為推薦守門人，並針對 dialog 覆蓋時 lifecycle 沒降下去的情境補丁（<a href="https://issuetracker.google.com/issues/483966071">b/483966071</a>）。</li><li><a href="https://github.com/android/nav3-recipes/issues/107"><strong>android/nav3-recipes#107</strong></a>：「It is best practices for buttons to be wrapped in Lifecycle.dropUnlessResumed blocks to ensure we avoid any unintended double button presses.」—— 官方範例倉庫直接把這個建議寫進 best practice，並以 <a href="https://github.com/android/nav3-recipes/pull/225">PR #225</a> 全面改寫 onClick callsite。</li><li><a href="https://issuetracker.google.com/issues/434109022"><strong>b/434109022</strong></a><strong>「dropUnlessResumed sometimes doesn’t prevent double taps」</strong>：官方 issue tracker 自己確認守門人會漏。這和本文 §2 的論證一致 — — 拿 lifecycle 當 back 合法性裁判，漏是結構性的，不是實作 bug。</li><li><strong>dropUnlessResumed 並非 Nav3 原生 API</strong>：它來自 <a href="https://developer.android.com/reference/kotlin/androidx/lifecycle/compose/package-summary">androidx.lifecycle.compose</a> 的 Lifecycle 2.8.0（Nav3 之前），原本是泛用的 lifecycle-aware click helper，被借來當 Nav3 雙擊的擋板。</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b20bbff06eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compose 如何局部更新]]></title>
            <link>https://medium.com/@weelow/compose-%E5%A6%82%E4%BD%95%E5%B1%80%E9%83%A8%E6%9B%B4%E6%96%B0-0bc35bb15462?source=rss-50c584f94be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bc35bb15462</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Barr]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 16:56:24 GMT</pubDate>
            <atom:updated>2026-01-16T16:56:24.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mp_XlWrpPaJxOs6EJN0-Lw.png" /></figure><p>Compose 和 View 兩者的更新其實非常類似，本質上都是對特定範圍標記｢髒｣來達成的，而這裡所說的範圍，是指｢可以獨立更新｣的區域。</p><p>Compose 與 View 中有個很大的差異，View 系統中每個 View 都是一個獨立的 RenderNode，Compose 則是在特定情況下才會建立額外的 RenderNode。RenderNode 就是紀錄可重放 DisplayList 的節點。</p><p>View 系統通常以單個 View 作為一個RenderNode，這是優點也是缺點，優點是更新邊界天然很細，缺點節點更多更碎，雖然 RenderNode 無法｢局部錄製｣，如果要更新都是全部的 drawXxx 完整重紀錄一遍，但 RenderNode 本身也有管理與記憶體成本，所以 Compose 不同的點是只有特定情況下產生 RenderNode，也算是 Compose 權衡下的設計。</p><p>雖然 Compose 看起來邊界較粗，但其實的精準更新不依賴 RenderNode 的細切，而是依賴 composition 階段產生的 changes，並透過 Applier 把變更增量地套用到 UI tree，因此 Compose 一樣能增量更新，不僅不依賴 RenderNode 做範圍分界同時還非常高效。而增量更新的關鍵，就是｢確認更新範圍｣。</p><p>更新 View 非常的直覺，哪個 View 被標記為髒，下一幀就會重新把繪製操作記錄到 RenderNode 上，那 Compose 呢？其實 Compose 也一樣，也是把需要更新的區域標記為髒。但你可能會問｢不對啊不都是用 State 驅動的嗎？｣。其實 Compose 和 View 系統也是將更新範圍標記為髒，只不過一個範圍是由 View 自身來切，一邊則是由 Composable 來切。</p><pre>(一個 composition frame 內)<br>Snapshot.takeMutableSnapshot(<br>  readObserver  = { value -&gt; composition.recordReadOf(value) },<br>  writeObserver = { value -&gt; composition.recordWriteOf(value) }<br>)<br><br>(組合中讀取時)<br>State.value read<br>  -&gt; snapshot readObserver<br>  -&gt; composition.recordReadOf(value)<br>  -&gt; observations.add(value, scope)  (建立 value -&gt; scope 映射)<br><br>(外部修改時)<br>State.value write<br>  -&gt; Snapshot.current<br>  -&gt; overwritableRecord(stateObject, snapshot, candidate)  // 取得可寫 record（必要時建立新 record）<br>  -&gt; record.value = newValue<br>  -&gt; snapshot.recordModified(stateObject)                  // write-set += stateObject<br>  -&gt; notifyWrite(snapshot, stateObject)                    // 通知 write observers</pre><p>大致流程是(這裡的 StateObject 就是一般看到的 State)</p><ul><li>組合開始時，會將所有｢讀取 StateObject｣的行為添加一個觀察者。</li><li>當讀取到該 StateObject 時，會調用該觀察者，一般的情況下會將當前的 RecomposeScope 與被讀取的 StateObject 之間的映射關係記錄到 observations 中。</li><li>下次寫入時，對被修改的 StateObject 進行變更登記，將他記錄到當前快照的 modified 變更集合中。</li></ul><p>重點就是 snapshot.recordModified(stateObject)，他把被改變的 StateObject 記錄到 modified 變更集合中。</p><p>有了變更集合 modified 以及映射集合 observations，就能知道哪些 Scope 是該重組的地方，接著就是將這些 Scope 標記</p><pre>Frame begin<br>  -&gt; Snapshot.sendApplyNotifications()                         // 宣告「有一批 state 寫入已提交」<br>  -&gt; Recomposer.recordComposerModifications()<br>       -&gt; composition.recordModificationsOf(changedValues)<br>            -&gt; drainPendingModificationsLocked()<br>                 -&gt; for each value in changedValues:<br>                      -&gt; observations.forEachScopeOf(value)    // 查：哪些 scope 曾讀過此 value<br>                           -&gt; scope.invalidateForResult(value) // 決定此 scope 是否需要 invalid<br>                                -&gt; owner.invalidate(scope, value)  // 標記 scope</pre><p>大致流程，對每個被寫入的 value</p><ul><li>重組時取出寫入的 value的變更集合 changes (modified)</li><li>透過映射集合 observations，找到所有依賴該 value 的 scope</li><li>判斷要不要真的 invalidate，若需要則標記</li></ul><p>所以它跟 View 系統一樣，都必須標記該區域後，才能正確地知道要更新哪一部分，並不是 State 系統讓 Compose 直接知道如何更新，而是 State 系統讓 Compose 知道哪個區域知道哪個區域該更新。</p><p>其實在自定義 View 中，也需要手動呼叫 invalidate()來正確更新 View 的繪製，Compose 也需要，只不過 State 系統幫我們｢自動調用｣而已，但本質上還是一樣，無論如何｢總要有個人調用invalidate()｣。</p><pre>(手動)<br>currentRecomposeScope.invalidate()<br>  -&gt; owner.invalidate(scope, instance = null)</pre><p>所以 Compose 也提供了手動更新的invalidate()，底層也和重組自己調用的是同一個函數，到最後都是執行 RecomposeScopeOwner.invalidate()。也就是說只要在 Composable 中這樣調用invalidate()，你也可以手動更新 Composable。舉個例子：</p><pre>val c = currentRecomposeScope<br>Text(Random.nextLong().toString(), Modifier.clickable { c.invalidate() })</pre><p>可以看到每次點擊後結果都不一樣，這是因為 Text 的這個作用域被標記了，所以下一幀就會重組這個作用域。</p><p>但其實我們還不知道invalidate()之後會發生甚麼，讓我們繼續往下看</p><pre>(任意時刻：手動或由 state 變更導致)<br>scope.invalidate() / scope.invalidateForResult(value)<br>  -&gt; owner.invalidate(scope, instance)<br>     -&gt; invalidateChecked(scope, anchor, instance)<br>        -&gt; invalidations.set(scope, ScopeInvalidated)<br>           // RecomposeScopeImpl 被記錄到待重組集合中</pre><p>可以看到，不論是手動或是由 State 驅動的變更，到最後都是將這個 Scope 記錄到一個 invalidations 集合中，這裡存放了所有下一次重組時需要被更新的 Scope。</p><p>那存好了之後要怎麼拿它來更新呢？我們說的重組就是 Recompose，在 Compose 裡面也有這個同名函數，就是 ControlledComposition.recompose()<br>Composable 能夠被重組再次執行就是因為他，我們來看看裡面發生什麼</p><pre>(下一幀開始)<br>composition.recompose()<br>  -&gt; invalidationsRequested = takeAndClear(compositionInvalidations)        // 取出並清空：上一輪累積的 scope invalidations<br>  -&gt; doCompose(invalidationsRequested)<br><br>doCompose(invalidationsRequested)<br>  -&gt; updateComposerInvalidations(invalidationsRequested)                    // ScopeMap -&gt; List&lt;Invalidation&gt;（寫入 composer.invalidations）<br>  -&gt; traverseGroups                                                         // 走訪 group tree：能跳過就跳過；若子樹含 invalidations 則精準重跑<br>       -&gt; recomposeToGroupEnd()                                              // 消耗 invalidations，逐一重跑被標記的 scope<br>            - invalidations.removeLocation(location)                         // 從集合中移除：消耗 1 個 scope 記錄<br>            - scope.compose(composer)                                        // 執行該 scope 的 restart lambda，產生 changes<br>  -&gt; invalidations.clear()                                                  // 本輪收尾：清空容器</pre><p>大致流程是</p><ul><li>composition 將上一輪累積的 scope invalidations 中交給 composer</li><li>composer 記錄成 invalidations: MutableList&lt;Invalidation&gt;</li><li>遍歷 invalidations，逐一清除並組合</li><li>清空 invalidations</li></ul><p>當下一幀到來時，composition 會從 invalidations 中取出全部待重組的 Scope，並將 invalidations 交給 composer(composer 就是實際執行重組的物件)。接著則是將 scope 逐個消耗掉並組合產生新的結果，當然以上經過非常大量的簡化，也有其他情況會有不同行為，但大致上可以這樣理解。</p><p>所以 Compose 和 View 系統其實很像，都會針對變更範圍標記，並在下一幀重新產生繪製紀錄，只不過 Compose 透過了強大的設計，實現了聲明式的<strong>寫入及綁定</strong>的能力，但底層其實非常複雜，這篇文也只是非常粗淺的介紹，裡面還有許多東西沒講到(畢竟我也沒完全看懂)，但不得不說這真的是個設計非常優雅又強大的框架。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bc35bb15462" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Dokka 的本質]]></title>
            <link>https://medium.com/@weelow/kotlin-dokka-%E7%9A%84%E6%9C%AC%E8%B3%AA-93aa61ce964b?source=rss-50c584f94be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/93aa61ce964b</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[dokka]]></category>
            <dc:creator><![CDATA[Barr]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 07:08:35 GMT</pubDate>
            <atom:updated>2025-11-18T07:08:35.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_GjTRV7LaEWYozQr94Y0w.png" /></figure><blockquote><a href="https://kotlin.github.io/dokka/1.7.20/#:~:text=Dokka%20is%20an%20API%20documentation%20engine%20for%20Kotlin%20that%20performs%20the%20same%20function%20as%20the%20Javadoc%20tool%20for%20Java%2C%20but%20it%27s%20modern%20and%20highly%20pluggable.">Dokka 是一個用於 Kotlin 的 API 文檔生成引擎，它的功能和 Java 的 Javadoc 工具有同樣的用途，但設計更現代，也具備高度的可插拔性。</a></blockquote><blockquote>這是一篇概念性文章，基本不會有「如何使用」的教學，適合想要對 Dokka 整體設計建立概念的人。</blockquote><h4>文檔的本質是「知識移轉」</h4><p>當一份專案的認知要從一個人的腦袋轉移到另一個人時，直接看程式碼往往低效，<em>這也是為什麼需要提供文檔給使用者與維護者。</em>但如何生成這份文檔呢？如果需要文檔呈現程式碼的完整結構呢？徒手打不僅不現實，也難以長期維護，這也是 API documentation engine 為何會存在。</p><h4>何謂 API documentation engine</h4><p>所謂的 API documentation engine，本質上是一個「文檔產生器」。它直接把程式碼和註解當成真相來源：直接讀取程式碼結構與特徵，從型別與註解裡萃取語意，並輸出結構化的文檔。</p><p>相比於徒手維護，API documentation engine 則是把「程式語意 → 文檔結構 → 最終輸出」這條路線變成一套可重複、可自動化的生成與維護流程。</p><h4>Dokka 是一種 Pipeline</h4><p>身為 Kotlin 的 API documentation engine，Dokka 不是單純輸出文檔，而是能輸出<strong>「多種格式」</strong>的文檔：HTML、Markdown 和 Javadoc 等等。一對多的直接實現並不現實，因此不是單純的暴力轉換，而是分層的抽象，將核心的共通特徵與最終的特定格式解耦。</p><p>因此 Dokka 將 <strong>「原始碼與註解 → 語意結構 → 佈局排版 → 輸出」 </strong>切成一串有明確輸入／輸出的處理節點：每一節點都接收前一階段的中間結果、產生下一階段的輸入，這就是典型的 Pipeline 模型。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*C7Vmb_qjFEEp_Ic2JxrOBA.png" /></figure><h4>Dokka 的 Pipeline</h4><p>對 Dokka 來說，這條 <strong>原始碼與註解 → 語意結構 → 佈局排版 → 輸出 </strong>的 Pipeline，在資料模型裡具體就是四層：</p><ul><li><strong>Input</strong>：原始來源層，抽象所有可以被 Dokka 讀入的東西，預設(但不限於) Kotlin／Java 原始碼與註解。</li><li><strong>Documentables</strong>：語意結構層，把來源統一成一棵語言無關的 API 樹，節點就是 class／function／package／property 等等。</li><li><strong>Pages</strong>：佈局排版層，把 API 樹組成「頁面＋內容」：每一頁是某個 API 的視圖，內容由文字、列表、程式碼區塊等 Content 組成。</li><li><strong>Output</strong>：輸出層，把 Page/Content 具體畫成 HTML、Markdown 或 Javadoc：PageNode 對應成檔案，ContentList／CodeBlock 對應成各格式的標記等等。</li></ul><h4><strong>抽象，是自由得以存在的邊界</strong></h4><p>預設的輸出樣式已經足夠完善，基本上不需要改動就能作為文檔使用，但依舊難以滿足特殊需求，而一個優秀的文檔生成引擎就該做到這些。客製化往往是既有實現的局部調整，也就是維持整體同時定點抽換，若流程耦合在單一實作，任何改動都可能造成無法預期的影響。</p><p>抽象是邊界，拆分出互不干涉的獨立維度，Dokka 拆分出了「來源、語意、佈局、輸出」，各自形成穩定的概念與契約，做到相同流程的前提下只對特定層級調整，而不是被迫重寫整個文檔管線。</p><h4>需求到客製化插件</h4><p>Dokka 的客製化能力，體現在對這四層抽象的獨立調整；不同類型的需求可以直接對應到各自的層級。</p><ul><li>Input：文檔的「來源與範圍」<br>若需調整被視為輸入的「來源與範圍」，即在 Input 層修改；此層決定最一開始有哪些內容會被讀入。</li><li>Documentables：API 的「語意結構」<br>若需針對 API 的「語意結構」增刪或調整，Documentables 提供相應的結構化資料；此層決定「內容具備何種 API 結構」。</li><li>Pages：文檔的「頁面、排版與佈局」<br>若需調整頁面、排版與佈局，Pages 提供對應的結構化資料；此層決定「內容在文件中的配置與呈現方式」。</li><li>Output：文檔的「最終格式」<br>若需調整最終載體與風格──無論是更換主題、額外輸出一份 Markdown／JSON，或新增超出 HTML／Markdown／Javadoc 以外的格式──即在 Output 層定義這些格式的輸出方式。</li></ul><h4>抽象的資料模型</h4><p>如果要改插件修改行為，多半會落在中間兩層：<strong>Documentables</strong> 和 <strong>Pages</strong>。一層是「Dokka 對 API 的內部模型」，一層是「Dokka 對文件頁面的內部模型」。理解這兩個 data model，就等於看懂 Dokka 眼中的 API 世界和文件世界。</p><h4>Documentables 與 DRI</h4><blockquote>Documentables 模型是 Dokka 用來表示專案 API 結構的內部模型，用於描述可被文件化的程式實體及其階層關係。</blockquote><p>在此模型中，Dokka 僅保留可作為文件主體的實體：模組、套件、類別、介面、物件、函式、屬性等，並依外層至內層的關係組成一棵樹，可視為一份「專案 API 清單與結構」：</p><pre>Documentables 結構示意<br>├─ Module<br>│  ├─ Package<br>│  │  ├─ Class / Interface / Object<br>│  │  │  ├─ Function<br>│  │  │  └─ Property<br>│  │  └─ 其他成員…<br>└─ …</pre><p>此層是自原始碼中剝離與文件無關的細節（語法糖、排版、局部實作等），取得一份穩定且聚焦於對外 API 的結構化資料，作為後續處理的基礎。</p><p>每一個 Documentables 節點都對應到一個 <strong>DRI（Dokka Resource Identifier）</strong>。DRI 是該 API 節點的唯一識別與定位資訊；後續階段若需引用某一 API（例如描述型別關聯、建立超連結或套用篩選條件），皆以 DRI 作為鍵值，再查回對應節點。</p><ul><li><strong>Documentables</strong> 是「可調整的 API 清單與結構」──用於決定哪些實體視為公開 API，以及如何分組與排列。</li><li><strong>DRI</strong> 是「操作這些節點所使用的識別與參照」──任何篩選、重組或加註，皆以一組 DRI 為基礎進行。</li></ul><p>凡是針對「有哪些 API 會出現在文件中」或「這些 API 在邏輯上如何分組與標記」的需求，實際調整的即是此層：透過條件選取一組 DRI，對應地過濾或重排 Documentables 節點，並視需要附加自訂屬性。</p><h4>Page / Content Model 與 DCI</h4><blockquote>Page / Content 模型是 Dokka 用來表示文件頁面與內容配置的內部模型，描述輸出前的頁面階層與內容元素。</blockquote><p>在此模型中，上一層的 API 結構會被映射為一棵頁面樹，並為各頁建立對應的內容結構：模組頁、套件頁、類別頁、索引頁等；每頁再細分為標題、說明段落、成員列表、範例程式碼、注意事項等內容節點。例如：</p><pre>Pages / Content 結構示意<br>├─ ModulePage<br>│  ├─ PackagePage<br>│  │  ├─ ClassPage<br>│  │  │  ├─ Content: 標題<br>│  │  │  ├─ Content: 說明文字<br>│  │  │  ├─ Content: 成員列表<br>│  │  │  └─ Content: 範例 / 注意事項…<br>│  │  └─ IndexPage…<br>└─ …</pre><p>此層負責將 API 清單轉換為具體的文件結構：決定頁面切分、頁面階層與導覽路徑，以及各頁內容區塊的組織與順序，而不是將這些決策交由輸出格式或樣式層自行推斷。</p><p>每一個 Content 節點皆具備一個 <strong>DCI（Dokka Content Identifier）</strong>。DCI 用於識別該內容節點，並攜帶一組相關 DRI，以標示此內容節點所對應或涉及的 API。藉由 DCI 與 DRI 之間的關聯，文件層內容可以準確映射回 API 層節點：自任一內容節點即可追溯其關聯的 Documentables 節點。</p><ul><li><strong>Page / Content</strong> 是「可調整的文件結構與內容區塊」──用於決定有哪些頁面、頁面之間如何導覽，以及同一頁內各內容區塊的構成與順序。</li><li><strong>DCI</strong> 是「操作內容節點時使用的識別基礎」──一方面用於定位特定內容節點，另一方面透過其中的 DRI 集合標示該內容節點所涉及的 API。</li></ul><p>在插件中，凡是涉及頁面拆併、導覽調整、內容區塊順序變更，或於既有內容前後插入自訂段落等需求，皆是透過操作 Page / Content 模型與相應的 DCI 來達成：以 DCI 鎖定目標內容節點，必要時再透過其中的 DRI 集合關聯到對應的 API。</p><h3>結語：概念之後的實作</h3><p>本文聚焦在 Dokka 的概念層：將其視為一條由 Input、Documentables、Pages、Output 構成的文檔生成 Pipeline。<br>中間兩層資料模型（Documentables／Page＋DRI／DCI）則用來描述 Dokka 如何在內部對應 API 結構與文檔頁面。</p><h3>刻意簡化的邊界</h3><p>本文專注在 Dokka 是什麼、它試圖解決什麼以及其設計哲學，不怎麼涉及具體 API 與實作說明，目標是建立理解 Dokka 的心智模型，而不是手把手的教學範例，這也是為何連 Gradle 等設定都不曾提及。</p><p>然而概念終究要落到實作。若想真正理解如何使用 Dokka，下面也整理了可以繼續往下探索的資料方向。</p><h3>實務樣貌與後續探索建議</h3><p>在本文的抽象框架之上，可以粗略將四層分工與幾個核心 extension point 對應如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*y2F83lhiFMhwJy4gcWYf_w.png" /></figure><h4>Input 來源層</h4><ul><li>SourceToDocumentableTranslator：將 Input（來源檔案）解析並轉換為初始的 Documentables 模型。</li></ul><h4>Documentables API 語意結構層</h4><ul><li>PreMergeDocumentableTransformer：在不同來源／SourceSet 合併之前，先對各自的 Documentables 做預處理（如過濾、標記、調整結構）。</li><li>DocumentableMerger：將多個 DModule 合併為單一的 Documentables 模型，整合跨來源的 API 視圖。</li><li>DocumentableTransformer：在合併後的 Documentables 上進一步轉換與補強，例如處理繼承關係、補上額外標記或重新組織 API 結構。</li></ul><h4>Pages 頁面與內容層</h4><ul><li>DocumentableToPageTranslator：將 Documentables（API 結構）轉換為初始的 Pages／Content 樹，決定每個 API 對應到什麼頁面與基本內容框架。</li><li>PageTransformer：在 Pages 層對頁面與內容做調整，例如合併或拆分頁面、插入額外區塊、改變內容順序與結構。</li></ul><h4>Output 最終輸出層</h4><ul><li>Renderer：定義如何將 Pages／Content 渲染為實際檔案，包含要產生哪些檔案、使用何種標記結構，以及如何寫出到輸出目錄。</li></ul><h3><strong>來源與延伸閱讀</strong></h3><ul><li>Dokka 官方文件（1.9.20）：<a href="https://kotlin.github.io/dokka/1.9.20/">https://kotlin.github.io/dokka/1.9.20/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93aa61ce964b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[《軟體設計的哲學》讀書筆記：Ch. 15–END]]></title>
            <link>https://medium.com/@weelow/%E8%BB%9F%E9%AB%94%E8%A8%AD%E8%A8%88%E7%9A%84%E5%93%B2%E5%AD%B8-%E8%AE%80%E6%9B%B8%E7%AD%86%E8%A8%98-ch-15-end-0b775bb161dd?source=rss-50c584f94be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b775bb161dd</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Barr]]></dc:creator>
            <pubDate>Sun, 02 Nov 2025 08:09:56 GMT</pubDate>
            <atom:updated>2025-11-02T08:13:45.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5lO0URYSR-N8VjWz" /></figure><p><a href="https://medium.com/@ohmylove347/%E8%BB%9F%E9%AB%94%E8%A8%AD%E8%A8%88%E7%9A%84%E5%93%B2%E5%AD%B8-%E8%AE%80%E6%9B%B8%E7%AD%86%E8%A8%98-ch-1-7-e311ea27c343">《軟體設計的哲學》讀書筆記：Ch. 1–7</a><br><a href="https://medium.com/@ohmylove347/%E8%BB%9F%E9%AB%94%E8%A8%AD%E8%A8%88%E7%9A%84%E5%93%B2%E5%AD%B8-%E8%AE%80%E6%9B%B8%E7%AD%86%E8%A8%98-ch-8-14-5d4e925e3b01">《軟體設計的哲學》讀書筆記：Ch. 8–14</a><br><strong>《軟體設計的哲學》讀書筆記：Ch. 15–END</strong></p><h3>第15章 先寫註解</h3><blockquote>比起完成才添加，開發時就編寫注釋往往能有更好的文檔與設計。</blockquote><h4>15.1 遲到的註解不是好註解</h4><p>拖到最後寫註解易變成敷衍與重述程式；設計記憶已模糊、重要語義遺漏機率高，最終常乾脆不寫。</p><h4>15.2 先寫註解</h4><p>新類先寫「類的介面註解」；為關鍵公開方法先寫「介面註解＋簽名、留空本體」並小幅迭代；再補關鍵成員變數的宣告與註解；最後實作方法並視需要加實作註解。新增方法/變數時，先補註解再寫本體。</p><h4>15.3 註解是設計工具</h4><p>註解是捕捉抽象的唯一完整途徑；越早寫越能檢視與調整抽象。紅旗：若一個方法/變數需要很長的註解才能說清，通常表示抽象淺、邊界不對或分解有誤。介面註解應「短且完整」；若必須詳述實作細節才能讓人用對，則介面太複雜或太貼近實作。</p><h4>15.4 早期註解很有趣</h4><p>在塑形抽象與結構的早期撰寫註解，能以最少文字表達完整語義；找出更簡單的註解本身就是對設計品質的測試與回饋。</p><h4>15.5 早期註解是否昂貴？</h4><p>撰寫註解通常僅占總開發時間小比例；先寫註解可讓抽象在落碼前更穩定，減少後續重寫程式的成本，整體可能更快。</p><h4>15.6 結論</h4><p>把「先寫註解」納入流程：讓註解與程式同步完成、以註解檢驗抽象與介面深度，最終得到更好的文件、設計與開發體驗。</p><h4>心得</h4><p>註解可以是架構設計的筆記，他直接參與設計本身，而不是完成後 review 時麻煩的額外添加；註解應該能在任何時候都代表當時的想法，並透過審視註解幫助分析設計的好壞。讓註解、設計與實現的演進「同步」總是更好的</p><p>但是大人時代變了，AI 的時代裡語意分析不再是件麻煩的事，當有良好的上下文與指令，註解幾乎可以在任何時候被輕易添加，就像自動類型推斷，AI 添加註解就像是自動 意圖/語意 推斷一樣。當然還不完美，但當不再是一行行寫註解時，整個流程一定會有有非同小可的改變，或許這章的建議得重新衡量了。</p><h3>第16章 修改現有的程式碼</h3><blockquote>如何在演進中避免複雜性潛入</blockquote><h4>16.1 保持戰略性</h4><p>修改既有程式碼時，不採「最小改動就好」的戰術思維；以設計最終應長成的樣子為目標，必要時先重構再改動；在現實限制下仍力求每次修改讓設計變更好而非更差。</p><p>心得：最小改動的目的是「避免完全理解整體」的低風險作法，本質上是時間與設計成本的 tradeoff，但會讓理解成為成本的本質是系統本就複雜 or 當初設計失敗。</p><h4>16.2 維護註解：讓註解靠近程式碼</h4><p>介面註解放在方法本體旁最易同步更新；實作註解按最小涵蓋範圍分散到各階段/區塊，頂端可放一段「整體策略」；註解離程式越遠，內容就應越抽象(且越不易因改動而失效)。</p><h4>16.3 註解屬於程式碼，不是提交紀錄</h4><p>變更緣由、細微問題等未來可能需要的資訊必須寫回程式碼；提交訊息可重述一份，但不能只留在提交紀錄裡。</p><h4>16.4 維護註解：避免重複</h4><p>每個設計決策只在單一最自然的位置記錄（如變數宣告處），其餘地方以短參照指出來源；不要在另一模組重寫本模組的決策；已存在於外部文件的內容以連結引用、勿複製。</p><h4>心得</h4><p>和單一可信數據源概念類似，重複的複雜性類似於 2.2 的「變更放大」。</p><h4>16.5 維護註解：檢查差異</h4><p>提交前快速掃過本次差異，確認所有受影響註解已更新；同時可抓到遺留除錯碼、未處理的 TODO 等。</p><h4>16.6 高階註解更易維護</h4><p>較抽象、描述整體行為而非細節的註解，較不易因微小程式變動而失真；但需要精確的地方仍應具體（見第13章原則）。</p><h3>第17章 一致性</h3><blockquote>一致性創造認知槓桿：理解一處理解多處</blockquote><h4>17.1 一致性的範例</h4><p>相似事相似作，不相似事不同作；在命名、編碼風格、介面多實作、設計模式、不變式等層面維持一致，形成認知槓桿與可預測性。</p><h4>17.2 如何確保一致性</h4><ul><li><strong>文件化</strong>：將總體規範文檔化。</li><li><strong>工具化</strong>：將檢查自動化最早發現問題。</li><li><strong>評審化</strong>：確保落實規範，也能幫助成員熟悉。</li><li><strong>在地化</strong>：遵循所在檔案/模組的既有慣例。</li><li><strong>勿輕改舊約</strong>：「更好的想法不是不一致性的藉口」；除非能全域升級，否則寧守一貫。</li></ul><h4>17.3 過猶不及</h4><p>把異質事物硬套同一做法（共用錯誤名稱、濫用不適配的模式）會製造混淆與複雜；一致性的價值建立在「看起來像 X 就真是 X」。</p><h4>17.4 結論</h4><p>一致性是一種投資：先付出制定／自動化／教育的成本，換來行為更顯而易見、理解更快、錯誤更少。</p><h3>第18章 程式碼應該是顯而易見的</h3><blockquote>「理解程式碼」這句話的本質只是在抽象的的表面絲滑的滑行。</blockquote><blockquote>軟體的設計應該便於閱讀，而不是便於編寫。</blockquote><blockquote>模糊性是複雜性的主因之一，當重要資訊無法顯而易見容易導致模糊性問題。</blockquote><h4>18.1 讓程式碼更明顯的做法</h4><p>好名稱與一致性是首要；提升文檔的易讀性(e.g. 用空白與空行凸顯結構)；無法避免不明顯之處時，以註解補上讀者判斷所需的關鍵資訊。</p><h4>18.2 讓程式碼不明顯的常見來源（與對策）</h4><p>依賴抽象導致追蹤與理解成本：e.g. 事件驅動，使控制流分散→在各 handler 的介面註解明確標示「何時被呼叫」。</p><p>缺少定義的通用類型：e.g. 泛型容器（如 Pair），掩蓋語義→改用具名結構/類別d</p><p>宣告與實作型別不一致：e.g. List vs ArrayList，誤導→宣告與配置對齊；</p><p>違反讀者預期的行為：e.g. main 結束但背景執行緒仍繼續→於介面與使用點明示。判斷紅旗：若無法快速讀懂其意與行為，即屬不明顯。</p><h4>18.3 結論</h4><p>用「資訊」觀點衡量顯而易見：讓讀者擁有足夠資訊就能正確猜中。</p><ol><li>減少所需資訊，e.g. 抽象、去特例。</li><li>借力既有認知，e.g. 遵循慣例與期望。</li><li>呈現關鍵資訊，e.g. 好名稱＋策略性註解。</li></ol><h3>第20章 設計性能</h3><h4>20.1 如何思考性能</h4><p>避免兩極（過度微優化 vs 完全忽略）；用基本成本感做「自然高效且仍簡潔」的選擇（網路、IO、動態分配、快取未命中昂貴），以微基準建立常識；複雜度的增量性可能讓複雜且高效的實作帶來反效果，除非效能不可接受，否則簡單做法更優先。</p><h4>20.2 修改前後的量測</h4><p>先量測找出少數真正耗時的熱點並建立基準，再動手；改完必須重測驗證，無顯著提升就回退（除非改動讓設計更簡）。</p><h4>20.3 圍繞關鍵路徑設計</h4><p>想像「理想關鍵路徑」＝常態下必執行的最少程式碼，讓實際設計儘量貼近它；把特殊情況前置於單一判斷，常態路徑不再被分支干擾，測試也可從單一呼叫確認特殊情況；移除淺層與多餘呼叫。</p><h4>20.4 示例要義（RAMCloud Buffer）</h4><p>以關鍵路徑重構：單方法處理、單測試排除特例、刪除透傳層，必要時加入極少的新狀態以簡化熱路徑；結果約 2× 加速、程式量 -20%。</p><h4>20.5 結論</h4><p>乾淨設計與高性能相容；複雜常因多做了無關或重複工作而變慢。多數情況先把系統寫得簡潔就夠快；少數需要優化時，抓住最關鍵路徑並讓其「最簡」。</p><h3>第21章 確定甚麼是重要的</h3><p>總是強調重要的事物讓其明顯，並隱藏不重要的事物</p><h4>21.1 確定甚麼失重要的</h4><p>確定何謂重要即是尋找槓桿，即「可演繹的預測」，e.g. 通用介面、不變量；選項的比較能更好確認何謂重要；堅持「最重要/不重要」的假設並構建系統並反思，從中吸取經驗與學習。</p><h4>21.2 盡量減少重要的事物</h4><p>重要資訊代表必要的認知負擔，盡量減少其位置與數量，e.g. 預設參數、底層處理。</p><h4>21.3 如何強調重要的事物</h4><ol><li>更顯眼：e.g. 文檔、名成員參數。</li><li>重複：讓關鍵概念反覆出現。</li><li>中心性：越重要則要越接近中心，e.g. 操作系統中的驅動介面。</li></ol><h4>21.4 錯誤</h4><ol><li>誤認為重要：增加不必要的複雜性與認知負擔。</li><li>誤認為不重要：資訊隱藏與模糊性。</li></ol><h4>21.5 更廣泛的思考</h4><p>專注重要同樣也是人生哲學，不要浪費在不重要與沒意義的事物上。品味(good taste)即是區分重要與不重要的能力。</p><h3>第22章 結論</h3><blockquote>本書只談一件事：複雜性；它讓系統難以構建與維護，且常導致變慢。</blockquote><h4>根因與紅旗</h4><p>根因包括依賴與模糊；紅旗包含資訊洩漏、不必要的錯誤情況、與過於籠統的命名。</p><h4>通用手法</h4><p>追求深且稍微通用的模組、把錯誤定義到不存在、介面文件與實作文件分離，以獲得更簡單的系統。</p><h4>代價</h4><p>早期會增加工作量；在學會設計技術前，進度體感更慢，若只想「先跑起來」，設計看似阻礙。</p><h4>回報</h4><p>良好設計的投資很快回本，總是能超越戰術性設計：早期定義清楚的模組可重複使用、清楚文件節省日後擴充時間；熟練後，做好設計其實不比草率設計更慢。</p><h4>結語</h4><p>把更多時間花在「設計」這件有趣的事上；設計能力提升 ⇒ 更快產出更高品質軟體，且更少錯，開發也更享受過程。</p><h3>總結</h3><h4>設計原則小結</h4><ol><li>複雜性是增量的：細節亦重要。</li><li>能跑起來還不夠。</li><li>持續做小額設計投資。</li><li>模組應該「深」。</li><li>介面要讓「最常見用法」最簡單。</li><li>介面簡單比實作簡單更重要。</li><li>通用模組更深。</li><li>將通用與專用的程式碼分離。</li><li>不同層要有不同的抽象。</li><li>降低複雜性。</li><li>用定義讓錯誤／特例「消失」。</li><li>重要決策「設計兩次」。</li><li>註解要描述程式碼中看不出的資訊。</li><li>為「易讀」而設計，不是為「易寫」。</li><li>開發的增量應是抽象，不是功能。</li><li>分離重要與不重要，並強調重要。</li></ol><h4>危險信號總結</h4><ol><li>淺模組：介面不比實作簡多少。</li><li>過度暴露：功能存在不必要的認知負擔。</li><li>資訊洩漏：同一設計決策出現在多個模組。</li><li>時序分解（以執行順序而非隱藏知識來劃分。</li><li>透傳方法（只轉呼叫、不做事。</li><li>重複：不重要的程式反覆出現。</li><li>專用／通用混雜（未乾淨分離。</li><li>聯體方法：兩方法強耦合、難獨立理解。</li><li>註解重述程式碼。</li><li>介面文件摻入實作細節。</li><li>含糊的名稱。</li><li>難取的名稱。</li><li>難以描述：要寫很長才能把語義講清。</li><li>不顯而易見的程式碼：讀者難以快速看懂其意與行為。</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b775bb161dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[《軟體設計的哲學》讀書筆記：Ch. 8–14]]></title>
            <link>https://medium.com/@weelow/%E8%BB%9F%E9%AB%94%E8%A8%AD%E8%A8%88%E7%9A%84%E5%93%B2%E5%AD%B8-%E8%AE%80%E6%9B%B8%E7%AD%86%E8%A8%98-ch-8-14-5d4e925e3b01?source=rss-50c584f94be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d4e925e3b01</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Barr]]></dc:creator>
            <pubDate>Sun, 02 Nov 2025 08:08:20 GMT</pubDate>
            <atom:updated>2025-11-02T08:13:50.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VvaeMNQxW5J0yxKW" /></figure><p><a href="https://medium.com/@ohmylove347/%E8%BB%9F%E9%AB%94%E8%A8%AD%E8%A8%88%E7%9A%84%E5%93%B2%E5%AD%B8-%E8%AE%80%E6%9B%B8%E7%AD%86%E8%A8%98-ch-1-7-e311ea27c343">《軟體設計的哲學》讀書筆記：Ch. 1–7</a><br><strong>《軟體設計的哲學》讀書筆記：Ch. 8–14</strong><br><a href="https://medium.com/@ohmylove347/%E8%BB%9F%E9%AB%94%E8%A8%AD%E8%A8%88%E7%9A%84%E5%93%B2%E5%AD%B8-%E8%AE%80%E6%9B%B8%E7%AD%86%E8%A8%98-ch-15-end-0b775bb161dd">《軟體設計的哲學》讀書筆記：Ch. 15–END</a></p><h3>第8章 降低複雜性</h3><blockquote>核心：把複雜性往下拉；「介面簡單」比「實作簡單」更重要</blockquote><h4>8.1 示例：編輯器文本類</h4><p>不要讓下層介面映射上层行為（如特定按鍵/操作）；以少量、通用的基本能力（插入/刪除等）承載需求，將場景與策略留在上層，讓存儲類更深更穩。</p><h4>8.2 示例：配置參數</h4><p>少給「旋鈕」，優先自動化與合理預設；只有當外部確實需要控制且語義穩定時才曝露參數，並把參數留在需要決策的那層，避免把選項下放成為下層的負擔與耦合點。</p><h4>8.3 做過了頭</h4><p>並非所有複雜性都應下沉，判準是「是否屬於此模組的核心職責且能由它穩定處理」。</p><p>合理情況：</p><ol><li>降低的複雜性與類別的現有功能密切相關</li><li>降低複雜性讓其他部分得到大量簡化</li><li>降低複雜性可以簡化類別的介面</li></ol><h4>8.4 結論</h4><p>讓自己辛苦一點，減少用戶的辛苦。</p><h3>第9章 合併好還是分開更好？</h3><h4>9.1 共享知識 → 合併</h4><p>若兩部分依賴同一份知識／格式／規則，應放在同一處，避免重複與洩漏並讓結構更短更簡單。</p><h4>9.2 能簡化介面 → 合併</h4><p>合併可消去中間介面，讓常見行為自動化並提供合理預設；非常見控制點才額外開口。</p><h4>9.3 為消除重複 → 合併或重構</h4><p>重複常是抽象錯位的紅旗。</p><p>把重複抽到單一位置（函式或更深方法）；若僅一兩行或需複雜簽名，抽取效益有限</p><h4>9.4 通用與專用 → 分開</h4><p>通用機制下沉成一個模組；專用行為上提到使用該機制的層。若同一類同時含通用與專用，應拆成上下兩層（下層機制、上層策略）。</p><h3>9.5–9.6 示例</h3><p>概念不夠緊密時不要硬合，把互不緊密的概念綁在一起只會讓使用與實作更繞，應分離成各自聚焦的單元。</p><ul><li><strong>淺封裝應內聯</strong><br>僅做轉呼叫或無實質抽象的薄包裝會徒增介面與跳轉成本，應移除或內聯到呼叫點。</li><li><strong>機制與專用處理要解耦</strong><br>像撤銷/重做這類機制應獨立，專用操作與分組策略留在上層；以分層協作而非彼此糾纏。</li></ul><h4>9.7 拆分與合併方法</h4><p>長度不是唯一指標；深方法（功能多但介面簡）即使較長也合理。可獨立理解的子任務抽成私有子方法；若兩個對外方法總是成對呼叫或需在其間傳遞狀態，應合併成一個更深的方法。</p><h4>9.9 不同意見：《無暇的程式碼》</h4><p>短方法必然比長方法易讀，但足夠短後繼續減少則觸及邊界效應，閱讀函數的成本存在固定成本(註解和文檔等等)。深度比長度重要，深度才決定複雜性的隱藏程度。</p><h4>結論</h4><p>評估「在一起／分開」的單一標尺是是否降低整體複雜度、邊界更清晰、洩漏更少；共享知識與介面簡化傾向合併，通用/專用混雜與重複傾向分離。</p><h3>第10章 定義不存在的錯誤</h3><h4>10.1 為何異常會增加複雜性</h4><p>異常打斷正常控制流、處理代價高、易引發次生異常；樣板繁瑣、難測難復現又少執行，難以開發時確驗證。</p><h4>10.2 異常過多</h4><p>過度防禦導致把可預期狀況都當錯誤丟出；其實是在把問題往上游踢、讓介面更肥更淺（異常也是介面的一部分，會跨層傳播）。先想清楚「呼叫者能做比你更好的處置嗎？」再決定要不要丟，重點是減少需要處理異常的位置。</p><h4>10.3 透過定義把錯誤消除</h4><p>調整語義，讓正常行為涵蓋原本的異常（例如把「刪除 X」改定義為「確保 X 不存在」）；如此便無需回報錯誤、介面更簡更深。</p><h4>10.4–10.5 示例要旨</h4><p>把「無法立即刪除檔案」改成「標記刪除、稍後完成」，或讓子字串超界自動裁切；核心是以更自然的語義定義，消去例外分支與特判。減少缺陷的方式是讓軟體更簡單。</p><h4>10.6 屏蔽異常（masking）</h4><p>在低層偵測並處理（如 TCP 自動重送、NFS 在伺服器恢復前讓請求等待），讓上層無感；這會拉低整體異常處理面積、讓類更深。</p><h4>10.7 聚合異常（aggregation）</h4><p>讓多種錯誤往上冒泡到單一高層處理點，以一個處理器產生一致的錯誤回應；與 masking 相反，聚合偏向高層集中處置，兩者共同目標都是「減少處理點」、「通用取代專用」。</p><h4>10.8 直接崩潰？</h4><p>對少見且難以補救的錯誤（如 OOM），立即終止並輸出診斷往往更實際；是否可接受視應用而定（例如複製儲存系統仍需恢復機制，不能簡單崩潰）。</p><h4>10.9 過猶不及</h4><p>僅在模組外不需該資訊時才定義/屏蔽掉錯誤；若外部確實需要（如網路通訊的失敗資訊），就必須暴露異常，否則無法構建健壯上層。</p><h4>10.10 結論</h4><p>消減異常處理點是降複雜的主軸：能用語義改寫就把錯誤「定義消失」，否則盡量在低層屏蔽，或在高層聚合。整體更簡單，錯誤更少。</p><h3>第11章 設計兩次</h3><blockquote>設計軟體很難，第一次的想法通常不是最好；對每個主要決策都提出多個選項再比較。</blockquote><p>先為介面構想幾種風格（彼此差異要大），只需草擬關鍵方法即可；即使自覺只有一種合理作法，也要刻意想第二種，用以對照弱點。</p><p>介面對上層的易用性最重要；其次比較：是否更簡單、是否更通用、是否更利於高效實現。</p><p>以觀察到的問題反推新的方案；紅旗：若高層還需額外拼裝和補操作，代表介面未對齊實際任務，應調整抽象。</p><p>「設計兩次」可用於：介面選型、實現選型（例如不同資料結構策略，實現側更重簡單與效能）、以及更高層的功能取捨與系統分解。</p><p>小模組花 1–2 小時探索備選，相對後續數天數週的實作成本很低，卻常帶來顯著更好的設計；模組越大，探索時間與回報也越大。</p><p>別執著於「第一次就對」(尤其是聰明人)；問題本來就難，多想一兩種設計不代表不聰明與自我否定，反而能避免表現受限、也更好合作。</p><p>反覆構思與比較會訓練你識別好設計的要素，長期讓你更快排除差方案、聚焦真正好的方案。</p><h4>結論</h4><p>計兩次能提升品質與個人設計力；雖然存在成本與心理門檻，但比起有機會選出最佳備選，也可能綜合其優點創造更好的新設計，是弊大於利的好習慣。</p><h3>第12章 為什麼要寫註解？有四個理由</h3><h4>12.1 「好程式碼會自我說明」？</h4><p>這是迷思。程式只能形式化一小部分介面（如簽名），大量非正式語義（方法做什麼、回傳值含義、設計動機、使用時機）無法寫進程式；若逼使用者讀實作，就沒有抽象，還會誘發大量淺方法，原因是為了讓程式碼更容易閱讀需要拆分得更細降低每個方法的厚度。</p><h4>12.2 「沒時間寫註解」？</h4><p>把註解視為長期投資：寫好註解通常僅是總開發時間的小幅增加，卻能顯著提升可維護性；類與方法的頂層註解最好作為設計流程的一部分一併完成。</p><h4>12.3 「註解會過時、誤導」？</h4><p>可控。避免重複文件、讓註解貼近對應程式碼，並在 Code Review 時順手修正陳舊註解；程式有大改時才需要大幅更新文件。</p><h4>12.4 「我看到的註解都沒價值」？</h4><p>常見，但可解。學會方法後，寫出有用、可維護的註解並不難；後續章節提供框架與準則。</p><h4>12.5 寫好註解的效益</h4><p>註解的總體思路是捕捉設計者腦中程式無法表達的資訊（從低階硬體癖性到高階設計理由）；未來修改與理解時能更快更準，不必重新推導原本知識，並降低認知負擔與不知道的未知、釐清依賴與消除模糊。把寫註解融入設計流程，能反過來改善設計本身。</p><h4>12.6 不同觀點：注釋就是失敗</h4><p>Uncle Bob 在 clean code 中說：「註解的本質上程式碼意圖表達失敗的補救，是表達能力缺失的體現。」雖然良好的設計能夠減少注釋，但程式語言的語法設計存在表達性的天然限制，必然存在無法被良好表達的資訊，因此資訊複雜時注釋是必要，而不是表達能力不夠。若是融合文檔的長命名，反而會讓每次的調用都輸入「文檔」而不是「方法」。將註解視為能力缺失則會讓設計師有迴避註解的不良態度。</p><h3>第13章 註解應該描述程式碼中不明顯的內容</h3><h4>13.1 選擇註解約定</h4><p>統一工具/格式並貫徹執行；優先覆蓋介面註解與資料成員註解；其餘含實作註解、跨模組註解，原則是「幾乎所有類/方法/公開欄位」都有對應說明。</p><h4>13.2 不要重複程式碼</h4><p>只寫從程式本身看不出的資訊；勿重述名稱或逐行翻譯；自檢：離開實作仍理解嗎？能，則註解有價值；否則刪。</p><h4>13.3 低階註解：補上精確語義</h4><p>補充單位、範圍含/不含邊界、null/空值語義、所有權/生命週期/資源釋放責任、可變性/別名化、不變式（必要時含執行緒安全假設）。</p><h4>13.4 高階註解：提供直覺與意圖</h4><p>高層註解的意義是提供抽象的概念框架，交代要做什麼與為什麼在此做（背景、取捨、假設），省略步驟；放在主要區塊/迴圈/分支起始處以引導閱讀。</p><h4>13.5 介面文檔＝定義抽象</h4><p>與實作註解分離；介面僅寫使用者需要知道的：行為總述、每個參數/回傳與前置/後置條件、副作用、可能的例外、可感知的效能/併發語義；不暴露內部表示、線路格式等細節。</p><h4>13.6 實作註解：寫「做什麼/為什麼」，不是「怎麼做」</h4><p>僅為難點/關鍵區塊加短述（意圖、原因、陷阱、替代方案為何棄用），必要時標註缺陷連結/議題編號以避免重述細節。</p><h4>13.7 跨模組設計決策</h4><p>把決策放在自然中心（如狀態列舉、協定定義）；無中心則集中於設計筆記檔，並在相關程式碼留極短參照指向入口。(不過當前有許多能進行文檔連結的注釋各式，現在問題應該不大)</p><h4>13.8 結論</h4><p>註解的任務是揭露不明顯而又與正確性/可用性相關的事；若需要長篇註解才能說清，多半表示抽象或命名應先改善。</p><h3>第14章 所選的名稱</h3><blockquote>名稱就是一種文檔</blockquote><h4>14.1 示例：名稱錯誤會導致錯誤</h4><p>不要讓同一名稱承載多個語義；為不同概念用不同名，小小含糊會累積成大成本與隱蔽 bug。</p><h4>14.2 創造心智圖像</h4><p>目標是「看名知義」：名稱本身就能讓讀者在腦中勾勒它是什麼、不是什麼的抽象形式；用「獨立觀察測試」檢查是否不看宣告也能猜對。</p><h4>14.3 名稱應精確</h4><p>兩要素：精確與一致。避免泛詞（如 count、x/y、status）；布林以謂詞命名（描述主語/謂語本身）；參數名應考慮是純函數還是依賴內部狀態(selection vs range)。若很難取到精確直觀且不冗長的名字，通常是抽象不夠乾淨的紅旗。</p><h4>14.4 一致使用名稱</h4><p>為常見概念選定專用名稱並始終如一。三個要求：「通用名稱只用於指定目標」、「通用名稱絕不用於任何指定外的目標」且「確保目標足夠狹窄且名稱與行為行為必須匹配 。相似變數用可區分前綴（如 srcFile, dstFile）；迴圈變數維持慣例（外層 i、內層 j）。</p><h4>14.5 避免多餘的字詞</h4><p>無法提供有用資訊與明確資訊的詞只會導致混亂(如 xxObject)。匈牙利命名法在變量前添加類型前綴，在能自動提供類型資訊的現代化開發環境下，已經沒有必要了。類別的成員變量不必添加類別本身作為前綴(如類別 File 中的成員 fileBlock)</p><h4>14.6 不同觀點：Go 風格</h4><p>短名並非原罪；關鍵在讀者是否易讀、系統內語義是否一致。可讀性由閱讀者決定而非編寫者。生命與使用的距離越遠、名應越長；有任何抱怨就改長/短一點。</p><h4>14.7 結論</h4><p>好名字讓「第一次猜測就對」，屬於會回本的投資：多花一點時間選名，未來更易維護、也更少錯。熟練後取好名幾乎不多耗時。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d4e925e3b01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IntelliJ & Android Studio 自訂檢查警告]]></title>
            <link>https://medium.com/@weelow/intellij-android-studio-%E8%87%AA%E8%A8%82%E6%AA%A2%E6%9F%A5%E8%AD%A6%E5%91%8A-04aa23e1ac98?source=rss-50c584f94be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/04aa23e1ac98</guid>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[intellij]]></category>
            <dc:creator><![CDATA[Barr]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 03:46:59 GMT</pubDate>
            <atom:updated>2025-10-08T03:47:18.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uVgLpRTNMAjnPZTW" /><figcaption>Photo by <a href="https://unsplash.com/@pankajpatel?utm_source=medium&amp;utm_medium=referral">Pankaj Patel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>不知道大家有沒有寫過類似的 code？</p><pre>fun f(list: List&lt;MyData&gt;): MyClass {<br>    val data = list[0]<br>    return data.toMyClass()<br>}</pre><p>這種再正常不過的寫法，卻潛藏著問題，<strong>就是 </strong><strong>list[0]</strong><br>如果 list 剛好是空的，會發生 IndexOutOfBoundsException，App 就崩潰了。明明這是很嚴重的問題，怎麼 IDE 一點提示都沒有呢？</p><p>但其實絕大多數語言都不會警告，少數有的是 Swift, Rust 的 get 方法，但使用 [] 取值也不會報錯，也就是說這其實是軟體界的標準，這是正常的。況且這種用法如果會警告的話那整個 code 都是警告，干擾也太大了吧。</p><p>但當我們的項目就是不允許這種問題呢？</p><p>在 AS 中，IDE 常常能幫助我們檢查潛在錯誤，舉個例子</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*OxbYI-mUeOEOks71TvoZqw.png" /></figure><p>這邊有一段底是黃色的警告，提醒你出了什麼問題，還能幫你修改，這麼好用的功能能自定義嗎？</p><h3>SSR(Structural Search and Replace)</h3><blockquote>結構化搜索與替換，基於語法樹（PSI）的樣板比對與重寫器。</blockquote><p>不是單純字串搜尋，而是用「範本 + 變數 + 約束」在 AST 層找出程式片段，並可用「替換範本」產生 Quick Fix / 自動重寫，能夠即時標示與提供修正做類型約束、語境限定、大小寫/遞迴、自動格式化與匯入等。<br>IDE 之所以能提醒與警告，就是利用它。</p><h4><strong>三要素</strong></h4><ol><li><strong>Pattern（搜尋樣板）</strong>：例如 $list$[$i$]、$xs$.first()、$recv$.$fn$($arg$)</li><li><strong>Variables（變數）+ Constraints（約束）</strong>：對變數指定型別、名稱、正則、是否含階層等</li><li><strong>Replacement（替換樣板）</strong>：例如 $list$.getOrNull($i$)、$xs$.firstOrNull()</li></ol><h3>運作機制</h3><h4><strong>解析與建模</strong></h4><p>原始碼先被解析為語法樹與語意模型；之後的所有比對與改寫都在這個結構層運作（非字串搜尋）。</p><h4><strong>樣板編譯</strong></h4><p>你寫的搜尋樣板會被轉成語法層級的匹配模式，可理解為「在語法樹上走訪的規則」。</p><h4><strong>匹配與命中</strong></h4><p>系統逐檔逐節點地比對樣板，找出語意對齊的片段（而不是僅僅長得像的字串）。</p><h4><strong>變數綁定</strong></h4><p>樣板中的占位符（$var）會被對齊到實際片段（接收者、參數、名稱…）；同名占位符必須指向同一實體，確保一致性。</p><h4><strong>約束過濾</strong></h4><p>在樣板之外，還會套用類型/名稱/階層/語境等限制，把命中縮窄到「我們真正想動的那一群」。</p><h4><strong>改寫生成</strong></h4><p>命中後依替換樣板產生新片段；系統會維持語法正確與語意連貫（不是簡單字串替換）。</p><h4><strong>風格與相依整理</strong></h4><p>完成改寫後，自動套用程式碼風格；必要時處理名稱解析與相依（例如匯入/名稱縮短），讓結果符合專案慣例。</p><h4><strong>呈現與執行模式</strong></h4><p>結果可在編輯器即時標示，也可批次掃描並一鍵修復；是否出現「一鍵修正」按鈕，取決於規則是否含替換描述（呈現層行為）。</p><h3>XML 規則（結構解剖）</h3><p>本質上 SSR 就是寫些 XML 而已，規則也蠻簡單的</p><pre>Inspection Profile：整體檢查設定<br>└─ SSBasedInspection：結構化搜尋檢查（＝ inspection_tool@class）<br>   ├─ enabled：是否啟用<br>   ├─ level：警示等級<br>   ├─ enabled_by_default：是否預設啟用<br>   ├─ replaceConfiguration：可替換規則（多條）<br>   │   ├─ name：規則顯示名稱<br>   │   ├─ text：搜尋樣板，含 $vars$<br>   │   ├─ replacement：替換樣板（同名 $vars$；存在即提供 Quick Fix）<br>   │   ├─ problemDescriptor：警告訊息文字<br>   │   ├─ suppressId：對應 @Suppress 的識別字<br>   │   ├─ type：語言標記<br>   │   ├─ pattern_context：樣板語境<br>   │   ├─ recursive：是否遞迴匹配<br>   │   ├─ reformatAccordingToStyle：是否依風格自動排版<br>   │   ├─ shortenFQN：是否自動短化完整限定名／調整匯入<br>   │   ├─ （可選）case_sensitive / caseInsensitive：大小寫匹配控制<br>   │   └─ constraint：對樣板變數的約束（0..n）<br>   │       ├─ name：被約束的變數名稱（須對應樣板中的 $var$）<br>   │       ├─ nameOfExprType：型別限制（可使用正則）<br>   │       └─ exprTypeWithinHierarchy：是否包含型別階層匹配<br>   └─ searchConfiguration：純提示規則（可選；結構同上，但不含 replacement）</pre><p>在有了概念之後，我們來試著寫一個 list[...] → list.getOrNull(...)<br>對應到上面的規則，把每個部份一一填上即可。</p><pre>&lt;component name=&quot;InspectionProjectProfileManager&quot;&gt;<br>  &lt;profile version=&quot;1.0&quot;&gt;<br>    &lt;option name=&quot;myName&quot; value=&quot;Project_SSR&quot; /&gt;<br>    &lt;inspection_tool class=&quot;SSBasedInspection&quot; enabled=&quot;true&quot; level=&quot;WARNING&quot; enabled_by_default=&quot;true&quot;&gt;<br>      &lt;replaceConfiguration<br>          name=&quot;List index → getOrNull&quot;<br>          suppressId=&quot;UnsafeCollectionAccess&quot;<br>          problemDescriptor=&quot;Use getOrNull(index).&quot;<br>          text=&quot;$list$[$i$]&quot;<br>          type=&quot;Kotlin&quot; pattern_context=&quot;expression&quot; recursive=&quot;true&quot;<br>          reformatAccordingToStyle=&quot;true&quot; shortenFQN=&quot;false&quot;<br>          replacement=&quot;$list$.getOrNull($i$)&quot;&gt;<br>        &lt;constraint name=&quot;list&quot; nameOfExprType=&quot;kotlin\.collections\.List.*&quot; exprTypeWithinHierarchy=&quot;true&quot;/&gt;<br>        &lt;!-- optional: &lt;constraint name=&quot;i&quot; nameOfExprType=&quot;kotlin.Int&quot;/&gt; --&gt;<br>        &lt;constraint name=&quot;i&quot;/&gt;<br>      &lt;/replaceConfiguration&gt;<br>    &lt;/inspection_tool&gt;<br>  &lt;/profile&gt;<br>&lt;/component&gt;</pre><p>這樣我們就有了一份 Project_SSR.xml 檔，接著以下步驟</p><ul><li>將檔案放到 .idea/inspectionProfiles/Project_SSR.xml 這個位置</li><li>到 Settings -&gt; Editor -&gt; Inspections，Profile 選 Project SSR</li><li>重新應用看是否生效，沒有的話 Invalidate Cache 即可</li></ul><h3>總結</h3><ul><li>SSR = <strong>AST 樣板匹配 + 替換</strong>，非單純字串比對。</li><li>元件：<strong>Pattern / Variables / Constraints / Replacement</strong>。</li><li>設定落地：SSBasedInspection → 多個 replaceConfiguration，各自有 text 與 replacement。</li><li>成功關鍵：<strong>放寬但準確</strong>的型別/方法名約束、<strong>覆蓋語法變體</strong>、pattern_context=”expression”。</li><li>邊界：<strong>不看資料流</strong>、<strong>型別解析受 IDE/Kotlin 版本影響</strong>。</li><li>抑制：統一 suppressId，你的 UnsafeCollectionAccess 已可一鍵管理。</li></ul><p>我把 Collection 相關的例外風險操作都整理起來，希望幫助到有需要的人。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/424b2d5c04ed4f8ca1cc2e222237525d/href">https://medium.com/media/424b2d5c04ed4f8ca1cc2e222237525d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04aa23e1ac98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[《軟體設計的哲學》讀書筆記：Ch. 1–7]]></title>
            <link>https://medium.com/@weelow/%E8%BB%9F%E9%AB%94%E8%A8%AD%E8%A8%88%E7%9A%84%E5%93%B2%E5%AD%B8-%E8%AE%80%E6%9B%B8%E7%AD%86%E8%A8%98-ch-1-7-e311ea27c343?source=rss-50c584f94be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e311ea27c343</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-design]]></category>
            <dc:creator><![CDATA[Barr]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 10:29:41 GMT</pubDate>
            <atom:updated>2025-11-02T08:13:55.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bZ1zJB7VA20XXsMw" /></figure><p>純筆記，心得感想什麼的以後再另外整理<br>不得不說真的是本很棒的書<br>感謝作者 John Ousterhout</p><p><strong>《軟體設計的哲學》讀書筆記：Ch. 1–7</strong><br><a href="https://medium.com/@ohmylove347/%E8%BB%9F%E9%AB%94%E8%A8%AD%E8%A8%88%E7%9A%84%E5%93%B2%E5%AD%B8-%E8%AE%80%E6%9B%B8%E7%AD%86%E8%A8%98-ch-8-14-5d4e925e3b01">《軟體設計的哲學》讀書筆記：Ch. 8–14</a><br><a href="https://medium.com/@ohmylove347/%E8%BB%9F%E9%AB%94%E8%A8%AD%E8%A8%88%E7%9A%84%E5%93%B2%E5%AD%B8-%E8%AE%80%E6%9B%B8%E7%AD%86%E8%A8%98-ch-15-end-0b775bb161dd">《軟體設計的哲學》讀書筆記：Ch. 15–END</a></p><h3>第一章：導言</h3><p>程式設計的最大限制是人的認知能力有限，認知負擔來源自複雜性<br>複雜性的解決有兩種方法：<br>1. 簡化：用更簡單更好理解的方式設計，解決複雜性本身。<br>2. 封裝：將複雜性隱藏，降低理解所需的最低資訊下界。<br>複雜性是增量的：每個帶有複雜性的獨立單元可以互相影響，結果是複雜性可能增加。</p><h3>第二章：複雜性的本質</h3><h4>2.1 複雜性的本質：與軟體系統結構有關、使人難以理解和修改系統的所有因素。</h4><p>我的理解：與系統交互所需的資訊量<br>粗略的複雜度公式：<br>總體複雜度 = 每個部分的複雜度 × 開發者花在該部分上的時間比例<br>因此隔離複雜性幾乎擁有等同于消除複雜性的功效</p><h4>2.2 複雜性的表現</h4><ol><li>變更放大：任何必須顯式維護的依賴關係。<br>ex. 每個網頁都自行定義了相同的背景色，若要修改背景色每個網頁都要修改。</li><li>認知負擔：與系統交互所消耗的心力/腦力。<br>ex. C 的手動記憶體管理比 Java 的 GC 來得更消耗心力理解</li><li>不知道的未知：存在本身都未被意識到的風險與問題。<br>這是三種複雜性的表現中最糟糕的，因為必須「錯誤發生才能被確認」<br>有點類似寫測試，無法窮舉的測試就是失敗的測試</li></ol><h4>2.3 複雜性的原因</h4><ol><li>依賴關係：系統組件間相互耦合的網路。 它會放大任何改動的影響與成本。</li><li>模糊性：關鍵資訊（介面契約、實現細節、命名等）未被明示，散落在隱式契約中。增加認知負擔且讓測試覆蓋困難。</li></ol><h4>2.4 複雜性是增量的(同第一章)</h4><h4>2.5 結論：複雜性會給修改與使用帶來困難與風險。</h4><h3>第三章：能工作的程式是不夠的</h3><h4>3.1 戰術性程式設計：需求導向的設計</h4><p>為了滿足需求本身的直接做法，高效快速。<br>代價：後期容易產生「技術債」。</p><h4>3.2 戰略性程式設計：工程導向的設計</h4><p>將工程本身加入設計時的視角，最初就深度考慮。<br>代價：初期投入成本較高。</p><h4>3.3 投資多少？</h4><p>每個任務投入 10–20% 的成本設計／重構。<br>把他視作必要保養費，替未來省下可能增量的「維修費」。</p><h4>3.4 初創企業與投資</h4><p>因為資金與時間不夠，導致選擇戰術方式。<br>但 FB 的案例說明該方案行不通。<br>高階工程師的額外成本很有機會降低整體設計成本，所以初創也可以選擇戰略方式。</p><p>我不完全認同：業務的優先級高於工程。<br>時間與開發成本可能要了初創的命。<br>複雜性的增量性是能控制的。</p><h4>3.5 結論</h4><p>好的設計不是免費的，但終將回收成本。<br>不要低估戰術的成本。<br>也不要低估戰術的價值。</p><h3>第四章：模組應該深</h3><h4>4.1 模組化設計</h4><p>模組就是系統按功能或角色區分的獨立單元。<br>理想的模組應該彼此獨立，系統的複雜度就是最差模組的複雜度。<br>但理想無法達成，依賴必然存在，所以模組化設計的目的是降低依賴。<br>模組由介面與實現組成。<br>介面是與模組交互時所需理解的內容。<br>實現是模組的內部行為模型。</p><h4>4.2 介面包含哪些內容</h4><p>正式部分：可以用「機器／編譯器」或「形式化方法」驗證的內容。<br>例如：調用簽名、例外和錯誤契約等等。</p><p>非正式部分：程式語言以外或無法形式化驗證的額外資訊。<br>例如：文檔、說明和範例等等。</p><h4>4.3 抽象</h4><p>抽象是對實體的簡化，省略不重要的細節。<br>我的理解：對特徵的歸納。</p><p>錯誤的抽象：<br>包含無關細節 → 增加不必要的複雜，認知負擔提升。<br>遺漏重要細節 → 無法正確理解，產生不知道的未知。<br>設計抽象的本質是「了解甚麼是重要的」。</p><h4>4.4、4.5 深／淺模組</h4><p>把模組理解成一個矩形。<br>面積表示功能。<br>頂點表示介面的複雜度。<br>高度表示內部實現的複雜度。</p><p>深模組能良好地隱藏複雜性。<br>淺模組則會暴露複雜性。<br>雖然不是所有情況都能設計成深模組，但請盡可能讓模組「深」。</p><h4>4.6 類炎（classitis）</h4><p>小模組往往是淺模組。<br>過去在遇到新功能時，常推崇添加新類，而不是直接在原有模組上擴充功能。<br>這會導致單個類的功能雖然簡單，但整體系統的複雜性卻增加。<br>這種「類應該小」的做法被稱作「類炎」。<br>類炎應該被避免。</p><h4>4.8 結論</h4><p>模組會暴露介面並隱藏實作。<br>因此使用模組時的複雜性就是介面的複雜性。<br>深模組就是最好的做法。</p><h4>第5章：資訊隱藏（與洩漏）</h4><blockquote>這章和第四章有點重複，偏實作。</blockquote><h4>5.1 資訊隱藏</h4><p>模組應封裝代表設計決策的知識。<br>這些知識嵌入在模組的實作中，但不會出現在其介面中。<br>因此其他模組不可見。<br>資訊隱藏的最佳形式是將資訊完全隱藏在模組中。<br>這樣該資訊對模組的使用者無關且不可見。</p><h4>5.2 資訊洩漏</h4><p>同一份設計決策分散在多個模組。<br>後果是：在模組之間創建了依賴關係。<br>連鎖修改與不一致風險上升。<br>介面越肥，洩漏越多。</p><h4>5.3 時序分解</h4><p>我的理解是：無法被編譯器或形式化驗證的步驟順序限制。<br>意思是交互時必須遵守特定的規則。<br>這會洩漏非功能性的額外知識。<br>它會造成認知負擔和「不知道的未知」。</p><h4>5.8 類內的資訊隱藏</h4><p>在同一類內收斂對關鍵狀態與不變式的存取。<br>將子知識封裝於私有協作點。<br>效果：類內變更影響範圍縮小。<br>行為更可局部推理。</p><h4>5.9 過猶不及</h4><p>過度隱藏會拿走必要控制點。<br>隱藏不足會把細節推給呼叫者。<br>原則：讓「常見情境」最簡。<br>罕見情境提供明確但有限的擴展點。<br>例如：預設參數。<br>只有在「需要控制」時才會發現控制點存在。<br>同時保證了隱藏與擴展性。</p><h4>5.10 結論</h4><p>深模組仰賴資訊隱藏。<br>避免時序分解。<br>將同一知識集中於單處並以小表面積對外。<br>本章重在「如何做深」：封裝知識、收斂接觸面、少而穩的介面。</p><h4>第6章：通用模組更深</h4><blockquote>過度的專用性是造成軟體複雜性的最大原因。<br>通用 API 則讓更多資訊被隱藏，讓模組更深。</blockquote><h4>6.1 使類「有點通用」</h4><p>功能可貼近當前需求，但介面保持通用與情境無關。<br>這通常帶來更簡、更深的介面，且兼顧未來重用。<br>就算不復用，往往也更好。</p><h4>6.3 更通用的 API</h4><p>以少量、可組合的「基本操作」承載主要能力。<br>例如：通用的插入／刪除語義。<br>上層可以「自行組合」高階行為。<br>總體更乾淨、可重用。</p><h4>6.4 通用性帶來更好的資訊隱藏</h4><p>通用介面讓邊界更乾淨。<br>「誰需要知道什麼」被清楚切分。<br>細節留在需要它的那一層。<br>這降低了認知負擔與耦合。</p><h4>6.5 要問自己的問題</h4><p>識別設計是否在通用與專用間平衡：<br>滿足當前需求的最少介面是什麼？<br>此方法能在多少情境被重用？<br>用它滿足今天的需求是否容易，且不致參數爆炸？</p><h4>6.6 將專用性向上／下推</h4><p>專用性無法完全消除。<br>但可以通過將其向上或向下推，來乾淨地分離。<br>向上：外部應用層。<br>向下：底部實作層。<br>選擇的判斷，是由與專用性的貼近或綁定的位置決定。<br>例如：設備驅動適合向下推。<br>用戶介面操作適合向上推。</p><h4>6.8 消除程式碼中的特例</h4><p>特例式的程式碼難以理解，並且容易出現錯誤。<br>最好的設計是自動處理邊緣情況。<br>特例不該被感知。<br>這能最大程度降低心智負擔。</p><h4>6.9 結論</h4><p>通用介面往往方法更少，但更深。<br>它能帶來更清晰的分隔。<br>讓模組「稍微通用」是降低整體系統複雜度的有效途徑。</p><h3>第7章：不同的層，不同的抽象</h3><blockquote>相鄰層若抽象相似，意味著分解出現問題。<br>層存在的價值在於抽象改變。</blockquote><h4>7.1 直通方法（Pass-through methods）</h4><p>只轉呼叫、幾乎不做事的方法會讓類變「淺」。<br>它會增加介面表面積與跨類依賴。<br>功能的介面應與其實作同處一類。<br>常見修正方式：<br>直接暴露下層。<br>重新分配職責。<br>合併類。</p><h4>7.2 什麼時候可以有重複介面</h4><p>重複簽名不等於錯。<br>只要每個方法各自提供實質且不同的功能即可。<br>例如：同層的 dispatcher 與其目標方法。<br>又例如：同介面多實作的驅動程式。<br>問題在於「不增功能的透傳」。</p><h4>7.3 裝飾器（Decorators）</h4><p>裝飾器跨層複製 API，容易充斥透傳。<br>這常導致淺類爆炸。<br>替代方法：<br>把通用的新功能直接加回基類。<br>與場景本身合併。<br>整併多個裝飾器為單一更深的裝飾器。<br>用獨立類代替裝飾器包裝。</p><h4>7.4 介面與實現</h4><p>不同層，不同抽象也適用於單一類。<br>介面抽象應與內部表示不同。<br>若兩者相似，類就很淺。<br>應把拆分、合併等低階表示轉換封裝在類內。<br>對外只暴露較高層語義的操作。</p><h4>7.5 直通變數（Pass-through variables）</h4><p>直通變數是指為了讓實作層可用，被層層傳遞的參數。<br>這會迫使中間過程「知道它」。<br>使耦合與修改面積膨脹。<br>可用上下文物件（context）集中參數，統一管理。</p><h4>7.6 結論</h4><p>層的價值取決於是否帶來抽象的改變。<br>如果不同層擁有相同抽象（例如直通方法），很可能他們沒有提供足夠的收益，來補償他們所展示的額外結構。<br>移除直通方法與直通變數。<br>謹慎使用裝飾器。<br>讓介面抽象與內部表示脫鉤。<br>才能形成深層且可演進的分層設計。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e311ea27c343" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>