<?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 Nizar Naufal on Medium]]></title>
        <description><![CDATA[Stories by Nizar Naufal on Medium]]></description>
        <link>https://medium.com/@nizarnfl21?source=rss-f5e5e426c63f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*d6zcUUtb1v4FUNcpW0l5VQ.jpeg</url>
            <title>Stories by Nizar Naufal on Medium</title>
            <link>https://medium.com/@nizarnfl21?source=rss-f5e5e426c63f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:18:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nizarnfl21/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[Why It’s Time to Leave EncryptedSharedPreferences Behind (and How to Do It)]]></title>
            <link>https://medium.com/@nizarnfl21/why-its-time-to-leave-encryptedsharedpreferences-behind-and-how-to-do-it-04bc4660c971?source=rss-f5e5e426c63f------2</link>
            <guid isPermaLink="false">https://medium.com/p/04bc4660c971</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[google-tink]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Nizar Naufal]]></dc:creator>
            <pubDate>Fri, 12 Dec 2025 03:20:04 GMT</pubDate>
            <atom:updated>2025-12-12T03:22:03.436Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XdTRQAtiPpoMnqwnn22VHA.png" /></figure><p>Android moved forward. Your local storage should too.<br>For years, <strong>EncryptedSharedPreferences</strong> filled the gap for simple secure storage, but as apps grow more complex and as Google’s roadmap evolves it’s no longer the right foundation for long-term, reliable, encrypted persistence</p><p>This guide walks you through:</p><ul><li>Why EncryptedSharedPreferences is outdated</li><li>The modern secure-storage stack (DataStore + Proto + Tink)</li><li>How encryption with Google Tink actually works</li><li>How to migrate seamlessly</li><li>How to choose the right <strong>Tink Key Template</strong> (AES128 vs 256, 4KB vs 1MB)</li></ul><p>In contrast, <strong>DataStore</strong> brings predictable updates, Kotlin-first APIs, and a strong foundation supported by Google’s current roadmap.</p><h3>2. What the New Stack Looks Like</h3><p>A modern secure storage stack relies on three components:</p><ul><li><strong>DataStore</strong> for asynchronous, reliable persistence</li><li><strong>Protobuf</strong> for schema-based versioning, backward compatibility, and explicit structure.</li><li><strong>Google Tink (StreamingAead) </strong>Encryption at rest using Android Keystore-backed keys.</li></ul><p>These three pieces work together to deliver encrypted, typed, corruption-resistant storage something you can rely on for years without revisiting the architecture.</p><p><strong>2.5. Why DataStore With Protobuf (Not Preferences DataStore)</strong></p><p>When migrating away from EncryptedSharedPreferences, you might think:</p><blockquote><em>Why not just use Preferences DataStore?</em></blockquote><p>Because it’s still just key-value storage. Proto DataStore is <em>real modeling</em>, with strong advantages:</p><p>Strong Typing: No more string keys. No silent typos. You interact with userName, isLoggedIn, etc.</p><p>Schema + Versioning: Add new fields, and old data still works.<br> You know exactly what your storage contains.</p><p>Perfect fit for encryption: Proto produces <strong>predictable binary output</strong>, which is ideal for Tink’s streaming encryption.</p><p>If you want to modernize, modernize fully:<br> <strong>Proto DataStore is the long-term, future-proof choice.</strong></p><h3>3. The Encryption Layer (CryptoManager)</h3><p>DataStore stores bytes.<br> Tink makes sure those bytes are encrypted the moment they touch disk.</p><pre>class CryptoManager(context: Context) {<br><br>    init { TinkConfig.register() }<br><br>    private val aead = AndroidKeysetManager.Builder()<br>        .withSharedPref(context, &quot;POKE_DEX_KEYSET&quot;, &quot;pokedex_pref&quot;)<br>        .withKeyTemplate(KeyTemplates.get(&quot;AES128_GCM_HKDF_4KB&quot;))<br>        .withMasterKeyUri(&quot;android-keystore://master_key&quot;)<br>        .build()<br>        .keysetHandle<br>        .getPrimitive(StreamingAead::class.java)<br>    fun encrypt(out: OutputStream) = aead.newEncryptingStream(out, ByteArray(0))<br>    fun decrypt(input: InputStream) = aead.newDecryptingStream(input, ByteArray(0))<br>}</pre><p>This keeps your DataStore file encrypted at rest, without managing keys manually.</p><p><strong>3.5 Understanding Tink Key Templates (and Choosing the Right One)</strong></p><p>This is the part almost every article skips.</p><p>Your encryption strength, performance, and I/O behavior all depend on which <strong>key template</strong> you select:</p><pre>.withKeyTemplate(KeyTemplates.get(&quot;AES128_GCM_HKDF_4KB&quot;))</pre><p>This template tells Tink:</p><ul><li>The algorithm (AES-GCM)</li><li>The key strength (128/256 bits)</li><li>HKDF key derivation</li><li>The chunk size for streaming encryption</li></ul><p>Below are the key options relevant for Android local storage.</p><p>Commonly Recommended Templates</p><p><strong>1. AES128_GCM_HKDF_4KB</strong></p><p><strong>Google’s default. Balanced for 95% of apps.</strong></p><ul><li>Chunk size: 4 KB</li><li>Fast on all devices</li><li>Great for small/medium protobuf data</li><li>Low battery and CPU cost</li></ul><p><strong>2. AES256_GCM_HKDF_4KB</strong></p><p>Same characteristics as above, but with <strong>256-bit keys</strong>.<br>Choose if you want stronger encryption with minimal performance difference.</p><p>3. AES128_GCM_HKDF_1MB</p><p>Optimized for large files:</p><ul><li>Chunk size: 1 MB</li><li>Fewer chunk boundaries</li><li>Faster for large reads/writes</li><li>Slightly slower on low-end devices during first write</li></ul><p><strong>4. AES256_GCM_HKDF_1MB</strong></p><p>Maximum key strength and large chunk size.<br>For enterprise apps or large binary data.</p><h3>4. Protobuf Serializer: The Heart of DataStore IO</h3><p>DataStore always reads/writes through a serializer.<br> Yours simply encrypts on write and decrypts on read.</p><pre>class UserPreferencesSerializer(<br>    private val cryptoManager: CryptoManager<br>) : Serializer&lt;UserPreferences&gt; {<br><br>    override val defaultValue: UserPreferences = UserPreferences.getDefaultInstance()<br><br>    override suspend fun readFrom(input: InputStream): UserPreferences {<br>        return try {<br>            val decryptedStream = cryptoManager.decrypt(input)<br>            UserPreferences.parseFrom(decryptedStream)<br>        } catch (e: Exception) {<br>            throw CorruptionException(&quot;Cannot read encrypted user preferences&quot;, e)<br>        }<br>    }<br><br>    override suspend fun writeTo(t: UserPreferences, output: OutputStream) {<br>        val encryptedStream = cryptoManager.encrypt(output)<br>        t.writeTo(encryptedStream)<br>        withContext(Dispatchers.IO) {<br>            encryptedStream.flush()<br>        }<br>    }<br>}</pre><h3>5. The Migration Step: Bring Over SharedPrefs Once</h3><p>DataStore supports automatic migrations; you only define the mapping.</p><pre>fun provideEncryptedUserPreferencesDataStore(<br>    context: Context,<br>    cryptoManager: CryptoManager<br>): DataStore&lt;UserPreferences&gt; {<br><br>    return DataStoreFactory.create(<br>        serializer = UserPreferencesSerializer(cryptoManager),<br>        migrations = listOf(<br>            SharedPreferencesMigration(<br>                context,<br>                &quot;pokedex_prefs&quot;<br>            ) { sharedPrefs, currentData -&gt;<br>                currentData.toBuilder()<br>                    .setIsLoggedIn(sharedPrefs.getBoolean(&quot;is_logged_in&quot;, false) ?: false)<br>                    .setUserName(sharedPrefs.getString(&quot;username&quot;, &quot;&quot;) ?: &quot;&quot;)<br>                    .build()<br>            }<br>        ),<br>        produceFile = {<br>            context.dataStoreFile(&quot;user_prefs.pb&quot;)<br>        }<br>    )<br>}</pre><p>This runs one time: the first moment your DataStore loads.</p><h3>6. The Final Result: Clean, Typed, Encrypted Storage</h3><p>Protobuf defines the data model:</p><pre>message UserPreferences {<br>  string userName = 1;<br>  bool isLoggedIn = 2;<br>}</pre><p>And a small manager class keeps the rest of your app clean:</p><pre>class DataStoreManager(private val dataStore: DataStore&lt;UserPreferences&gt;) {<br>    <br>    val isLoggedIn = dataStore.data.map { it.isLoggedIn }<br>    <br>    suspend fun setLoggedIn(value: Boolean) =<br>        dataStore.updateData { it.toBuilder().setIsLoggedIn(value).build() }<br>    suspend fun clearData() =<br>        dataStore.updateData { it.toBuilder().clear().build() }<br>}</pre><h3>7. The Bottom Line</h3><p>If you are still using EncryptedSharedPreferences, 2026 is the right moment to move forward.</p><p>With DataStore, Protobuf, and Tink:</p><ul><li>Your data is encrypted at rest</li><li>Your schema is versioned and future-proof</li><li>Your storage is asynchronous and corruption-resistant</li><li>Your migration path is smooth</li></ul><p>This isn’t just an upgrade. It’s the modern baseline for secure local persistence on Android.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04bc4660c971" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Structuralist Blueprint for Modern Android: ResultState Orchestration, Layered Design, and…]]></title>
            <link>https://medium.com/@nizarnfl21/a-structuralist-blueprint-for-modern-android-resultstate-orchestration-layered-design-and-bc8c9a6213b0?source=rss-f5e5e426c63f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc8c9a6213b0</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Nizar Naufal]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 06:18:00 GMT</pubDate>
            <atom:updated>2025-12-11T06:18:00.482Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Structuralist Blueprint for Modern Android: ResultState Orchestration, Layered Design, and Deterministic ViewModel Flows</h3><p>Modern Android architecture has reached a point where technical correctness alone is not enough. What differentiates mature engineering today is <em>structural reasoning</em> a lens borrowed from modern systems theory, software philosophy, and organizational design. This article explores how ResultState-driven architectures unify domain logic beneath uncertainty, and why adopting layered structures informed by thinkers like <strong>Simon Brown</strong> (Software Architecture for Developers), <strong>Eric Evans</strong> (Domain-Driven Design), and <strong>Kepner Tregoe</strong> problem analysis leads to predictable, resilient mobile systems.</p><p>To ground the concepts, the examples use a real implementation: a paginated Pokémon list powered by a Kotlin ViewModel, a domain-level GetPokemonListUseCase, and a ResultState-backed loader pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LG_gQVZivtNTXAr2LIMl9g.png" /></figure><h3>1. Why Modern Architecture Needs Philosophical Structure</h3><p>Contemporary engineering teams are overloaded with patterns MVVM, Clean Architecture, MVI, redux like state machines, unidirectional flow, reactive streams. What experienced architects eventually realize is that the patterns are simply expressions of a deeper principle:</p><p><strong>A software system is a social system with deterministic rules. Structure determines behavior.</strong></p><p>This echoes concepts from:</p><ul><li><strong>Structuralism (Lévi-Strauss) </strong>meaning emerges from relationships between components.</li><li><strong>Systems Thinking (Meadows) </strong>systems behave based on flows, feedback loops, and boundaries.</li><li><strong>Eric Evans’ DDD </strong>domain models encode meaning and invariants within bounded contexts.</li><li><strong>Simon Brown’s C4 Model</strong> layering is communication clarity, not ceremony.</li></ul><p>The architecture proposed in this article is not just “Clean Architecture”; it is <strong>structuralized mobile engineering</strong>, where layers exist for cognitive and operational clarity:</p><ul><li><strong>Domain Layer </strong>timeless truth, pure logic</li><li><strong>Data Layer</strong> uncertain reality, adapters to external chaos</li><li><strong>Presentation Layer</strong> user-facing orchestration under uncertainty</li><li><strong>System Layer</strong> event loops, schedulers, runtime state, workers</li></ul><p>At the heart of this architecture sits a concept borrowed from decision analysis:</p><p><strong>A system must express both success and failure symmetrically.</strong></p><p>This is where <strong>ResultState</strong> enters.</p><h3>2. The Role of ResultState as a Decision Boundary</h3><p>Traditional apps manage loading, error, and success states through scattered booleans. Scaling such systems inevitably leads to:</p><ul><li>inconsistent UI state</li><li>repetitive error handler</li><li>fragile refresh logic</li><li>accidental infinite-loading states</li><li>unclear boundaries across layers</li></ul><p>ResultState addresses this by introducing a <strong>single semantic unit</strong> for representing uncertainty in computation:</p><pre>Loading → Success → Error</pre><p>This mirrors the <strong>Kepner–Tregoe problem-analysis cycle</strong>:</p><ol><li><strong>What is happening?</strong> (Loading)</li><li><strong>What is the result?</strong> (Success)</li><li><strong>What prevented the expected result?</strong> (Error)</li></ol><p>ResultState becomes the language of the architecture.</p><h3>3. A Modern Layered Architecture (with Diagram)</h3><p>Below is a breakdown aligned with modern architectural literature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*Q83GLPIUptBdF-7EXcqEiA.png" /></figure><h3>The design principles:</h3><ul><li><strong>Presentation</strong> holds state, not <em>business logic</em></li><li><strong>Domain</strong> holds business logic, not state</li><li><strong>Data</strong> holds mutability and side effects</li><li><strong>Models </strong>holds request, response, mappers</li><li><strong>ResultState</strong> flows downward → upward with strict guarantees</li><li><strong>Paging</strong> becomes a transform operation, not a side effect</li><li><strong>ViewModels</strong> are orchestration engines, not computation engines</li></ul><h3>4. The Use Case: The Authority of Business Logic</h3><p>In this design, Use Cases are the primary units of domain logic. They:</p><ul><li>Decide <em>when</em> and <em>how</em> the repository is called.</li><li>Manage loading states.</li><li>Apply pagination rules.</li><li>Produce a stable ResultState output for the UI.</li></ul><p>Example:</p><pre>class GetPokemonListUseCaseImpl(private val repository: PokemonRepository) :<br>    GetPokemonListUseCase {<br><br>    override fun invoke(<br>        refreshing: Boolean,<br>        previous: PagingResult&lt;PokemonResult&gt;?,<br>    ): Flow&lt;ResultState&lt;PagingResult&lt;PokemonResult&gt;&gt;&gt; = <br>        UseCaseDelegate.paginateFlow(<br>            previous = if (refreshing) null else previous,<br>        ) {<br>            repository.fetchPokemonList()<br>                .toResultStateSuccess {<br>                    it.map(<br>                        previousItems = if (refreshing) null else previous?.items<br>             )<br>         }<br>    }<br>}</pre><p>This highlights several design philosophies:</p><p><strong>4.1 The Use Case is the “Policy Layer”</strong></p><p>As described in <em>Clean Architecture</em>, a Use Case should contain the <strong>application specific business rules</strong>:</p><ul><li>How we fetch.</li><li>How we merge pagination.</li><li>Rules for refreshing.</li><li>Error handling conventions.</li></ul><p><strong>4.2 The Use Case returns a reactive, structured UI state</strong></p><p>Instead of throwing exceptions, we always emit:</p><ul><li>Loading</li><li>Success</li><li>Error</li><li>Idle (pagination-specific)</li></ul><p>This aligns with Fowler’s view on “notification patterns” vs exception-driven control flow.</p><h3>5. The PaginateResponse: A Functional Core for Paging</h3><p>Your PaginateResponse is a textbook example of domain aligned modeling.</p><pre>data class PaginateResponse&lt;out T : Response&lt;R&gt;, R : Result&gt;(<br>    @SerializedName(&quot;results&quot;) val data: List&lt;T&gt;? = null,<br>    @SerializedName(&quot;count&quot;) val count: Int = 0,<br>    @SerializedName(&quot;next&quot;) val next: String? = null,<br>    @SerializedName(&quot;previous&quot;) val previous: String? = null,<br>) : BaseResponse&lt;T, R&gt; {<br>    <br>    fun toResultStateSuccess(transform: (PaginateResponse&lt;T, R&gt;) -&gt; PagingResult&lt;R&gt;): ResultState&lt;PagingResult&lt;R&gt;&gt; {<br>        return ResultState.Success(transform(this))<br>    }<br>    fun map(previousItems: List&lt;R&gt;? = null): PagingResult&lt;R&gt; {<br>        val combined = mutableListOf&lt;R&gt;().apply {<br>            previousItems?.let { addAll(it) }<br>            data?.map { it.map() }?.let { addAll(it) }<br>        }<br>        return PagingResult(<br>            count = count,<br>            next = next.orEmpty(),<br>            previous = previous.orEmpty(),<br>            items = combined<br>        )<br>    }<br>}</pre><p>This structure embodies two architectural philosophies:</p><p><strong>1. Pure transformation over mutable orchestration</strong></p><p>Mapping sits in the domain layer, not the ViewModel.</p><p><strong>2. Paging as a deterministic function</strong></p><p>State flows remain consistent regardless of refresh, scroll, or retry.</p><h3>6. Pagination-Specific Flow: A Dedicated State Machine</h3><p>Because pagination has unique behaviors, we isolate that logic:</p><pre>fun &lt;T&gt; paginateFlow(<br>    previous: PagingResult&lt;T&gt;?,<br>    delay: Long = 1000L,<br>    errorDelay: Long = 4000L,<br>    block: suspend () -&gt; ResultState&lt;PagingResult&lt;T&gt;&gt;<br>): Flow&lt;ResultState&lt;PagingResult&lt;T&gt;&gt;&gt; = flow {<br>    try {<br>        val hasNext = !previous?.next.isNullOrEmpty()<br>        if (previous == null || hasNext) {<br>            emit(ResultState.Loading(previous))<br>            val response = block()<br>            neutralize(<br>                value = response,<br>                previous = response.data,<br>                delay = delay<br>            )<br>        } else {<br>            emit(ResultState.Idle(previous))<br>        }<br>    } catch (e: Throwable) {<br>        neutralize(<br>            value = e.toResultStateError(),<br>            previous = previous,<br>            delay = errorDelay<br>        )<br>    }<br>}</pre><p>This isolates:</p><ul><li>Load more vs refresh</li><li>Idle (no more pages) vs Loading next page</li><li>Combining old and new data</li><li>API pagination inconsistency shielding</li></ul><p>This is directly influenced by <strong>Martin Fowler’s “Domain Logic Patterns”</strong>, especially the “Transaction Script” versus “Domain Model” discussion:<br> pagination is a reusable domain procedure, so you encapsulate it once and reuse everywhere.</p><h3>7. The ViewModel: A Structural Orchestrator (Adjusted Version)</h3><p>Below is the revised <strong>architecturally aligned ViewModel</strong>, rewritten for clarity, predictability, and ResultState symmetry.</p><pre>internal class HomeViewModel(<br>    private val getListPokemonUseCase: GetPokemonListUseCase<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(HomeState())<br>    val state = _state.asStateFlow()<br>    <br>    fun onEvent(event: UiEvent) {<br>        when (event) {<br>            is HomeEvent.OnGetAllData -&gt; loadPokemonList()<br>            is HomeEvent.OnSearch -&gt; searchPokemon(event.query)<br>        }<br>    }<br><br>    private fun loadPokemonList() {<br>        viewModelScope.launch {<br>            _state.update { it.copy(pokemonList = ResultState.Loading()) }<br>            getListPokemonUseCase(<br>                refreshing = false,<br>                previous = _state.value.pokemonList.dataOrNull()?.items<br>            ).collect { result -&gt;<br>                when (result) {<br>                    is ResultState.Success -&gt; handlePagingSuccess(result)<br>                    is ResultState.Error -&gt; handleError(result)<br>                    else -&gt; Unit<br>                }<br>            }<br>        }<br>    }<br>    private fun handlePagingSuccess(result: ResultState.Success&lt;PagingResult&lt;PokemonEntry&gt;&gt;) {<br>        val entries = result.data?.items.orEmpty().map { entry -&gt;<br>            val number = entry.url?.trimEnd(&#39;/&#39;)?.takeLastWhile { it.isDigit() }<br>            val imageUrl =<br>                &quot;https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/$number.png&quot;<br>            PokemonResult(<br>                id = entry.id,<br>                name = entry.name?.replaceFirstChar { c -&gt;<br>                    if (c.isLowerCase()) c.titlecase(Locale.ROOT) else c.toString()<br>                }.orEmpty(),<br>                url = imageUrl<br>            )<br>        }<br>        val combined = _state.value.pokemonList.dataOrNull()?.items.orEmpty() + entries<br>        val paging = PagingResult(<br>            count = result.data?.count ?: 0,<br>            next = result.data?.next.orEmpty(),<br>            previous = result.data?.previous.orEmpty(),<br>            items = combined<br>        )<br>        _state.update {<br>            it.copy(<br>                pokemonList = ResultState.Success(paging),<br>                isSearching = false,<br>                isSearchStarting = true<br>            )<br>        }<br>    }<br>    private fun handleError(result: ResultState.Error) {<br>        _state.update {<br>            it.copy(<br>                pokemonList = ResultState.Error(<br>                    code = result.code,<br>                    message = result.message<br>                )<br>            )<br>        }<br>    }<br>}</pre><h3>Why this version is architecturally superior:</h3><ul><li><strong>Behavior is decomposed into semantic handlers</strong> (handlePagingSuccess, handleError).</li><li><strong>State never mutates directly</strong>; transitions occur as structural steps.</li><li><strong>Paging logic stays deterministic</strong> and independent of UI.</li><li><strong>ResultState symmetry</strong> ensures consistent UX behavior across pagination, reloads, and search.</li></ul><p>This is precisely what modern software architecture literature advocates:<br> <strong>Separation of concerns through semantic boundaries.</strong></p><h3>8. Closing: What Makes This a “Modern” Architecture?</h3><p>The architecture in this article is modern not because of the frameworks used but because it:</p><ul><li>treats uncertainty as a first-class architectural concern</li><li>favors structural clarity over convenience</li><li>aligns with systemic thinking and DDD principles</li><li>avoids accidental complexity in ViewModels</li><li>isolates paging transformations as pure functions</li><li>uses ResultState as a universal contract</li><li>encourages predictable state machines</li><li>respects Clean Architecture boundaries without over-engineering</li></ul><p>Modern architecture is not a pattern; it is a philosophy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*piQnWILN-Kw2spDVR4-Agw.png" /></figure><p><strong>Software should behave predictably even under unpredictable conditions.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc8c9a6213b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Struggling with Software Design? Master These Essential Patterns!]]></title>
            <link>https://medium.com/@nizarnfl21/struggling-with-software-design-master-these-essential-patterns-2d31110b8ca7?source=rss-f5e5e426c63f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d31110b8ca7</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Nizar Naufal]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 16:46:59 GMT</pubDate>
            <atom:updated>2025-03-22T21:18:51.432Z</atom:updated>
            <content:encoded><![CDATA[<p>In software development, ensuring that a system is scalable and maintainable is crucial. This article explores insights from software engineering materials, particularly from <strong>The Hong Kong University of Science and Technology</strong>, focusing on <strong>Design Patterns</strong>, which offer proven solutions to recurring software design challenges.</p><h3>What Are Design Patterns?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*PxNsFUYeu7OM3JyJ88b3rA.jpeg" /></figure><p>Design patterns are structured solutions that address common coding problems. They are categorized as follows:</p><h4><strong>Creational Patterns</strong>: Object Creation Strategies for Flexibility and Efficiency</h4><ul><li><strong>Singleton</strong> → Ensures only one instance of a class exists, useful for managing global resources like database connections.</li><li><strong>Factory</strong> → Centralizes object creation to avoid exposing instantiation logic, improving flexibility.</li><li><strong>Builder </strong>→ Constructs complex objects step by step, making code more readable and maintainable</li><li><strong>Prototype</strong> → Clones existing objects instead of creating new ones, reducing initialization cost.</li><li><strong>Abstract Factory </strong>→ Creates families of related objects without specifying concrete classes, ensuring consistency.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*0q8oLtEyz03VEyQ2RToHoA.png" /></figure><h4><strong>Structural Patterns</strong>: Organizing Code for Modularity and Maintainability</h4><ul><li><strong>Adapter</strong> → Bridges incompatible interfaces so they can work together.</li><li><strong>Bridge</strong> → Separates abstraction from implementation, making systems more flexible.</li><li><strong>Composite</strong> → Treats groups of objects like individual ones, useful for hierarchical structures.</li><li><strong>Decorator</strong> → Dynamically adds functionality to objects without modifying their structure.</li><li><strong>Façade</strong> → Provides a simple interface to a complex system, improving usability.</li><li><strong>Flyweight</strong> → Reduces memory usage by sharing common object data.</li><li><strong>Proxy</strong> → Controls access to an object, adding features like caching and lazy loading.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*B_W1gySemFvkmj4iYdRh5Q.png" /></figure><h4><strong>Behavioral Patterns:</strong> Manage Object Interactions and Responsibility Distribution</h4><ul><li><strong>Observer</strong> → Allows multiple objects to react to state changes in another object.</li><li><strong>Strategy</strong> → Enables selecting an algorithm at runtime without modifying client code.</li><li><strong>Command</strong> → Encapsulates requests as objects, allowing undo/redo functionality.</li><li><strong>Mediator</strong> → Reduces dependencies between objects by introducing a central coordinator.</li><li><strong>Chain of Responsibility</strong> → Passes a request through handlers until one processes it.</li><li><strong>State</strong> → Changes object behavior dynamically based on its internal state.</li><li><strong>Visitor</strong> → Separates algorithms from objects, making it easy to add new operations.</li><li><strong>Iterator</strong> → Provides a way to traverse a collection without exposing its internal details.</li></ul><h4><strong>Concurrency Patterns</strong>: Handle Multi-Threaded Operations Efficiently</h4><ul><li><strong>Thread Pool</strong> → Reuses a pool of threads to handle multiple tasks efficiently.</li><li><strong>Monitor Object</strong> → Ensures only one thread accesses a critical section at a time.</li><li><strong>Reactor</strong> → Handles multiple asynchronous events using a single event loop.</li><li><strong>Read-Write Lock</strong> → Allows multiple reads but restricts writes to one thread at a time.</li></ul><h3>Why Design Patterns Matter</h3><p>Throughout my studies at <strong>The Hong Kong University of Science and Technology</strong>, I discovered how <strong>design patterns improve software quality</strong> and <strong>prevent common pitfalls</strong>. Many developers overlook them at first, but their benefits include:</p><p>✅ <strong>Improved Code Readability</strong> → Developers can understand code intent quickly.<br> ✅ <strong>Faster Development</strong> → Reusing established patterns saves development time.<br> ✅ <strong>Better Scalability</strong> → Structured code is easier to expand without breaking existing functionality.<br> ✅ <strong>Avoiding Anti-Patterns</strong> → Prevents poorly structured, difficult-to-maintain code.</p><h3>Case Study: The Mediator Pattern</h3><p>One example discussed in software engineering is <strong>The Mediator Pattern</strong>, useful in systems where multiple components need to communicate while minimizing direct dependencies.</p><h4>Advantages of the Mediator Pattern</h4><p>✅ <strong>Decoupled Colleagues</strong> → Objects no longer communicate directly, making them independent.<br> ✅ <strong>Improved Readability &amp; Maintenance</strong> → Centralized logic makes it easier to understand and modify.<br> ✅ <strong>Simplified Communication</strong> → Reduces complexity by converting many-to-many relationships into one-to-many.<br> ✅ <strong>Less Subclassing</strong> → Changes in communication logic only affect the mediator, not individual components.the mediator class, rather than altering multiple interconnected classes.</p><h4>Disadvantages of the Mediator Pattern</h4><p>⚠️ <strong>Increased Complexity</strong> → The mediator itself can become overly complex if it handles too many interactions.</p><h3>Kotlin Implementation:</h3><pre>interface Mediator {<br>    fun notify(sender: String, event: String)<br>}<br><br>class SmartHomeMediator : Mediator {<br>    private val devices = mutableMapOf&lt;String, SmartDevice&gt;()<br>    <br>    fun registerDevice(name: String, device: SmartDevice) {<br>        devices[name] = device<br>    }<br>    <br>    override fun notify(sender: String, event: String) {<br>        when (event) {<br>            &quot;AlarmTriggered&quot; -&gt; devices[&quot;Heater&quot;]?.action(&quot;TurnOn&quot;)<br>            &quot;Morning&quot; -&gt; devices[&quot;CoffeeMachine&quot;]?.action(&quot;Start&quot;)<br>        }<br>    }<br>}</pre><p>By using a <strong>Mediator</strong>, devices communicate indirectly, making the system easier to manage and extend.</p><h3>Exploring Other Key Design Patterns</h3><h3>Proxy Pattern: Managing Access and Optimizing Resource Usage</h3><p>The <strong>Proxy Pattern</strong> is used when direct access to an object needs to be <strong>controlled or optimized</strong>. Instead of interacting with the actual object immediately, a <strong>proxy acts as a middle layer</strong> that decides when and how the real object should be created or accessed.</p><h4>Example Use Case: Image Viewer</h4><p>An image viewer application should <strong>only load high-resolution images when necessary</strong>, rather than loading all at once.</p><pre>interface Image {<br>    fun display()<br>}<br><br>// The real object that takes time to initialize<br>class RealImage(private val filename: String) : Image {<br>    init {<br>        println(&quot;Loading image: $filename&quot;) // Simulating a costly operation<br>    }<br>    override fun display() {<br>        println(&quot;Displaying image: $filename&quot;)<br>    }<br>}<br><br>// Proxy that defers the creation of RealImage<br>class ImageProxy(private val filename: String) : Image {<br>    private var realImage: RealImage? = null<br><br>    override fun display() {<br>        if (realImage == null) {<br>            realImage = RealImage(filename) // Object is created only when needed<br>        }<br>        realImage?.display()<br>    }<br>}<br><br>// Usage<br>fun main() {<br>    val image1: Image = ImageProxy(&quot;photoku.jpg&quot;)<br>    val image2: Image = ImageProxy(&quot;photomu.png&quot;)<br><br>    println(&quot;Accessing images...&quot;)<br>    image1.display() // Loads and displays image<br>    image2.display() // Loads and displays image<br>}</pre><h4>Benefits of the Proxy Pattern</h4><p>✅ <strong>Optimized Performance</strong> → The real object is only created when necessary, reducing memory and processing overhead.<br> ✅ <strong>Access Control</strong> → Proxy can act as a security layer, restricting unauthorized access.<br> ✅ <strong>Lazy Loading</strong> → Objects are loaded <strong>on demand</strong>, preventing unnecessary instantiation.</p><h4>Potential Downsides</h4><p>⚠️ <strong>Increased Complexity</strong> → Adds an extra layer, which may complicate debugging.<br> ⚠️ <strong>Delay in Object Access</strong> → Since the real object is created when first needed, there might be a slight performance hit during the first request.</p><p>The <strong>Proxy Pattern</strong> is widely used in <strong>virtual proxies (lazy loading), protection proxies (access control), and remote proxies (network communication)</strong>.</p><h3>Singleton Pattern</h3><p>The <strong>Singleton Pattern</strong> ensures that only <strong>one instance</strong> of a class exists throughout an application. This is useful for <strong>shared resources</strong> that should not be duplicated, such as <strong>database connections, logging systems, or configuration settings.</strong></p><p>A database connection should be <strong>shared</strong> rather than created multiple times. Opening multiple connections unnecessarily can slow down the system and waste resources. With Singleton, the connection is <strong>created once</strong> and reused whenever needed.</p><h4>Example Use Case: Database Connection Manager</h4><p>A database connection should be <strong>shared</strong> rather than created multiple times. Opening multiple connections unnecessarily can slow down the system and waste resources. With Singleton, the connection is <strong>created once</strong> and reused whenever needed.</p><pre>object DatabaseConnection {<br>    init {<br>        println(&quot;Initializing database connection...&quot;)<br>    }<br>    <br>    fun connect() {<br>        println(&quot;Connected to database&quot;)<br>    }<br>}<br><br>// Usage<br>fun main() {<br>    val db1 = DatabaseConnection<br>    val db2 = DatabaseConnection<br><br>    db1.connect()<br>    db2.connect()<br><br>    println(db1 === db2) // true -&gt; Both references point to the same instance<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*G1QCX0d_ucMRbK6pV1TXqQ.jpeg" /><figcaption>same but different :P</figcaption></figure><h4>Key Takeaways</h4><p>✅ <strong>Prevents Multiple Instances</strong> → Ensures only one object is created, reducing redundancy.<br> ✅ <strong>Easy to Access</strong> → Provides a globally accessible instance without requiring manual instantiation.<br> ✅ <strong>Thread-Safe in Kotlin</strong> → The object declaration handles thread safety automatically.</p><h4>When to Be Careful</h4><p>⚠️ <strong>Overuse Can Lead to Tight Coupling</strong> → If used excessively, Singleton can make components too dependent on a global state.<br> ⚠️ <strong>Challenging to Mock in Tests</strong> → Since there is only one instance, testing or replacing it in unit tests may require additional setup.</p><p>This pattern is <strong>ideal for managing shared system-wide resources</strong> but should be used wisely to avoid making the code too dependent on a global state.</p><h3>Bridge Pattern</h3><p>The <strong>Bridge Pattern</strong> is used to <strong>separate abstraction from implementation</strong>, allowing both to change independently. Instead of tightly coupling an abstraction to a specific implementation, this pattern introduces a <strong>middle layer</strong> that makes it easier to extend functionality without modifying existing code.</p><h4>Example Use Case: Remote Control for Multiple Devices</h4><p>A remote control should work with <strong>different types of devices</strong>, such as a <strong>TV, radio, or speaker</strong>. Without the Bridge Pattern, we would need separate remote controls for each device, leading to duplicated code. By applying this pattern, we can create a <strong>flexible remote control</strong> that works with any device.</p><pre>// Common interface for all devices<br>interface Device {<br>    fun turnOn()<br>    fun turnOff()<br>}<br><br>// Specific device implementations<br>class TV : Device {<br>    override fun turnOn() { println(&quot;TV is ON&quot;) }<br>    override fun turnOff() { println(&quot;TV is OFF&quot;) }<br>}<br><br>class Radio : Device {<br>    override fun turnOn() { println(&quot;Radio is ON&quot;) }<br>    override fun turnOff() { println(&quot;Radio is OFF&quot;) }<br>}<br><br>// Remote control abstraction<br>abstract class RemoteControl(protected val device: Device) {<br>    abstract fun powerButton()<br>}<br><br>// Concrete remote control implementation<br>class BasicRemote(device: Device) : RemoteControl(device) {<br>    private var isOn = false<br><br>    override fun powerButton() {<br>        if (isOn) {<br>            device.turnOff()<br>        } else {<br>            device.turnOn()<br>        }<br>        isOn = !isOn<br>    }<br>}<br><br>// Usage<br>fun main() {<br>    val tvRemote = BasicRemote(TV())<br>    val radioRemote = BasicRemote(Radio())<br><br>    tvRemote.powerButton() // Turns TV ON<br>    radioRemote.powerButton() // Turns Radio ON<br>}</pre><h3>System Analysis and Design: Retrospective</h3><p>A <strong>strong software system</strong> is built on <strong>solid design principles</strong>. At <strong>The Hong Kong University of Science and Technology</strong>, I explored essential aspects of <strong>System Analysis and Design</strong> that contribute to scalable and maintainable software.</p><h3>Key Concepts</h3><p>📌 <strong>Architectural Design</strong> → Structures the system using loosely coupled subsystems to improve modularity and scalability.<br> 📌 <strong>Class Analysis</strong> → Organizes objects into boundary, control, and entity classes for clear responsibility assignment.<br> 📌 <strong>Class Design</strong> → Defines attributes, operations, and applies design patterns for better maintainability.</p><h3>Anti-Patterns: What to Avoid</h3><h3>Spaghetti Code</h3><p>Spaghetti code is a term used to describe an unstructured, difficult-to-maintain codebase where functions and dependencies are tangled, making debugging and modifications extremely challenging. This often happens when a project evolves without proper architectural planning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*_erzU9e6BEJ1wuhgP9Vpqw.jpeg" /></figure><h4>Example of Spaghetti Code in Kotlin:</h4><pre>fun processOrder(order: String) {<br>    if (order == &quot;Pizza&quot;) {<br>        println(&quot;Processing pizza order&quot;)<br>    } else if (order == &quot;Burger&quot;) {<br>        println(&quot;Processing burger order&quot;)<br>    } else if (order == &quot;Pasta&quot;) {<br>        println(&quot;Processing pasta order&quot;)<br>    }<br>    // More if-else statements...<br>}</pre><p><strong>Solution:</strong> Implement <strong>modular design</strong> with structured methods or use <strong>Factory Pattern</strong> to simplify object creation.</p><h3>God Class</h3><p>A <em>God Class</em> is a class that has too many responsibilities, making the code difficult to manage and maintain. It violates the <strong>Single Responsibility Principle (SRP)</strong> by handling multiple concerns in a single unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYaUL01QARneVZod0DuWHw.png" /></figure><h4>Example of a God Class in Kotlin:</h4><pre>class OrderManager {<br>    fun createOrder() { println(&quot;Creating order&quot;) }<br>    fun processPayment() { println(&quot;Processing payment&quot;) }<br>    fun sendNotification() { println(&quot;Sending notification&quot;) }<br>    fun updateInventory() { println(&quot;Updating inventory&quot;) }<br>}</pre><p><strong>Solution:</strong> Break down responsibilities into separate classes, such as PaymentProcessor, NotificationService, and InventoryManager.</p><h4>Refactored Code:</h4><pre>class PaymentProcessor {<br>    fun processPayment() { println(&quot;Processing payment&quot;) }<br>}<br><br>class NotificationService {<br>    fun sendNotification() { println(&quot;Sending notification&quot;) }<br>}<br>class InventoryManager {<br>    fun updateInventory() { println(&quot;Updating inventory&quot;) }<br>}</pre><p>By applying <strong>Single Responsibility Principle</strong>, the system becomes more modular and maintainable.</p><h3>Conclusion</h3><p>Throughout my studies at <strong>The Hong Kong University of Science and Technology</strong>, I realized that mastering design patterns is key to writing scalable, maintainable, and efficient software. Applying them properly enhances software quality and prevents common pitfalls. What patterns do you use in your projects? Let’s discuss! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d31110b8ca7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tech Evolves, So Does Anxiety: A Dev’s Survival Guide(A Personal Reflection)]]></title>
            <link>https://medium.com/@nizarnfl21/tech-evolves-so-does-anxiety-a-devs-survival-guide-a-personal-reflection-9692e16ed9b0?source=rss-f5e5e426c63f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9692e16ed9b0</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[tech-shift]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[reflections-of-life]]></category>
            <dc:creator><![CDATA[Nizar Naufal]]></dc:creator>
            <pubDate>Fri, 21 Mar 2025 17:38:26 GMT</pubDate>
            <atom:updated>2025-03-21T18:43:28.839Z</atom:updated>
            <content:encoded><![CDATA[<p>Technology moves fast — sometimes a little <em>too</em> fast. One day, you’re happily coding in your favorite framework, and the next, you’re questioning your entire existence because a new “must-learn” tech just dropped. Sound familiar? Welcome to the never-ending cycle of <em>tech shift anxiety</em>.</p><p>If you’re a developer, you’ve probably spent countless hours worrying about whether you’re using the “right” tech stack, whether your skills will be obsolete tomorrow, or if switching from native to Kotlin Multiplatform Or Flutter will cause an existential crisis. This guide isn’t here to magically erase your worries (if only!), but it will help you navigate them with some practical advice and a few laughs along the way.</p><h3>Step 1: Accept That Change Is the Only Constant</h3><p>Here’s the thing — technology <em>will</em> change. There’s no stopping it. Instead of resisting, embrace it. Every seasoned developer has faced multiple shifts in their career. Java to Kotlin. Objective-C to Swift. Native to cross-platform. REST to GraphQL. And yet, the industry marches on.</p><p>The key is to focus on <em>principles</em> rather than just tools. If you understand core programming concepts — data structures, algorithms, system design, and software architecture — you’ll be able to adapt to new languages and frameworks much faster. The syntax may change, but logic remains the same.</p><h3>Step 2: Stop Trying to Learn Everything at Once</h3><p>Raise your hand if you’ve ever opened 10 tabs comparing Jetpack Compose, SwiftUI, Kotlin Multiplatform, Flutter, and React Native — only to end up closing them all because your brain overheated. We’ve all been there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*MMxuxbtYD3e2c6mzN3tyyw.jpeg" /></figure><p>Instead of overwhelming yourself, <strong>prioritize learning what’s actually relevant to you</strong>. If you’re a mobile developer, do you really need to panic over the latest or new framework? Probably not. Stick to your lane and expand when necessary.</p><h3>Practical Tips:</h3><ul><li>Follow industry trends, but don’t chase every hype cycle.</li><li>Invest in deep learning of one core language/framework before branching out.</li><li>If you’re forced to switch tech stacks, focus on <em>transferable knowledge</em> (e.g., state management concepts, design patterns).</li></ul><h3>Step 3: Build, Break, and Rebuild</h3><p>The best way to learn isn’t by hoarding Udemy, Coursera courses — it’s by <strong>doing</strong>. Start small projects, experiment, break things, and learn from it. Reading about Flutter, Kotlin Multiplatform, React Native, is nice, but building an actual app? That’s where the real learning happens.</p><h3>Project Ideas to Ease the Tech Transition:</h3><ul><li>If you’re moving from native Android or native iOS to Flutter or Kotlin Multiplatform, try building a small to-do app in both.</li><li>Switching to Swift? Recreate a simple Android app using SwiftUI.</li><li>Switching to Flutter? Recreate a simple Android And iOS app using Dart.</li><li>Switching to Kotlin Multiplatform? Recreate a simple Android And iOS app using Kotlin</li></ul><p>The goal isn’t to become an expert overnight but to get comfortable with the transition.</p><h3>Step 4: Don’t Ditch Your Existing Skills Too Quickly</h3><p>Just because a new framework is trending doesn’t mean you should abandon what you already know. There’s always a balance between <strong>adopting new tech</strong> and <strong>leveraging existing expertise</strong>.</p><h3>Smart Transitioning Strategies:</h3><ul><li><strong>Gradual migration:</strong> If you’re shifting to a new stack, integrate it <em>slowly</em> rather than rewriting everything from scratch.</li><li><strong>Side projects:</strong> Use new tech on the side before bringing it into your main work.</li><li><strong>Interoperability:</strong> Many languages/tools can work together (e.g., Kotlin can coexist with Java, Swift with Objective-C, Flutter with native).</li></ul><h3>Step 5: Engage with the Developer Community (aka, You’re Not Alone)</h3><p>When in doubt, turn to <strong>other developers</strong>. Whether it’s Stack Overflow, Reddit, Twitter, or Discord, there’s always someone who has faced the same struggles. Learning from others’ experiences can save you time, frustration, and possibly a keyboard-smashing incident.</p><h3>Where to Connect:</h3><ul><li><strong>Reddit:</strong> r/androiddev, r/iOSProgramming, r/learnprogramming</li><li><strong>Discord Communities:</strong> Various tech-specific servers (Flutter, React, KMM, etc.)</li><li><strong>Twitter:</strong> Follow industry leaders and join the discussion</li><li><strong>Conferences &amp; Meetups:</strong> Online and offline events are great for networking</li></ul><h3>Final Words: Keep Moving Forward (With Coffee, Lots of Coffee)</h3><p>Tech anxiety is real, but it doesn’t have to control you. As long as you focus on continuous learning, build real projects, and engage with the community, you’ll always stay ahead — regardless of which shiny new framework appears next week.</p><p>So, take a deep breath. Keep coding. And remember: <strong>every developer has at least one horror story about spending hours debugging, only to realize they forgot a semicolon.</strong></p><p>You’re doing great. Now go write some code. 🚀</p><blockquote><strong><em>Survival Tips:</em></strong><em> </em>If all of this feels overwhelming, remember: even AI needs retraining. If it can relearn, so can you! And if all else fails… well, there’s always the option of becoming an catfish farmer ( biasanya kami ada lelucon seperti yaudah ternak lele adalah pilihan terakhir )🤣</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*HTg-aHgDwYatC061DFg-GA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9692e16ed9b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Your ViewModels: A Deep Dive into Event-Driven Architecture for Android]]></title>
            <link>https://medium.com/@nizarnfl21/streamlining-your-viewmodels-a-deep-dive-into-event-driven-architecture-for-android-7ec0837235b4?source=rss-f5e5e426c63f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ec0837235b4</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Nizar Naufal]]></dc:creator>
            <pubDate>Thu, 17 Oct 2024 09:21:24 GMT</pubDate>
            <atom:updated>2024-12-04T07:31:35.249Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll explore how to maintain clean and efficient ViewModels using event-driven architecture, particularly for Jetpack Compose applications.</p><h3>Prerequisites</h3><p>Before diving in, it’s essential to have:</p><ul><li>A foundational understanding of Android architecture.</li><li>Basic knowledge of Kotlin Flows.</li></ul><p>Now, let’s break down some key concepts necessary for managing ViewModels effectively.</p><h3>Core Concepts: Actions, Events, and States</h3><p>To keep your ViewModel clean and maintainable, it’s crucial to understand the distinctions between actions, events, and states:</p><h3>Actions</h3><p>Actions represent user interactions or inputs, such as typing in a text field, clicking a button, or toggling a switch. By encapsulating these user interactions into a sealed class or enum, you centralize the logic for handling them, making it easier to manage.</p><h3>Events</h3><p>Events signify one-time outputs from the ViewModel to the UI. These could include showing a toast, navigating to a different screen, or displaying an error message. Utilizing a Channel or SharedFlow for events allows the UI to respond without needing constant observation.</p><h3>States</h3><p>States reflect the current condition of the UI at any moment. They store all necessary data for the UI, such as loading indicators, form fields, and error messages. Using StateFlow or LiveData to manage states ensures that the UI stays in sync with the latest data.</p><h3>How It All Works Together</h3><p>Let’s illustrate these concepts with a practical example involving a sign-in process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*EY_Z_-z1qSV-k-jM3Z7RJw.jpeg" /></figure><h3>Practical Example: AddressViewModel</h3><pre>@HiltViewModel<br>class AddressViewModel @Inject constructor(private val userRepository: UserRepository) : ViewModel() {<br>  private val _state = MutableStateFlow(AddressState())<br>    val state get() = _state.asStateFlow()<br>    private val _uiEvents = Channel&lt;AddressEvent&gt;()<br>    val uiEvents = _uiEvents.receiveAsFlow()<br>    fun onEvent(uiEvent: UiAction) {<br>        when (uiEvent) {<br>            is AddressActions.OnFetchAddress -&gt; {<br>                onSetLoading()<br>                onFetchAddress()<br>            }<br>            is AddressActions.OnSetLatLong -&gt; onSetLatLong(<br>                latitude = uiEvent.latitude,<br>                longitude = uiEvent.longitude,<br>            )<br>        }<br>    }<br>    private fun onFetchAddress() = viewModelScope.launch {<br>        when (val response = userRepository.getAddress()) {<br>            is ResultState.Success -&gt; {<br>                val addressData = response.data.address<br>                _state.update {<br>                    it.copy(<br>                        isLoading = false,<br>                        address = addressData<br>                    )<br>                }<br>            }<br>            is UnAuthorizationError -&gt; {<br>                _state.update { it.copy(isLoading = false) }<br>                _uiEvents.send(AddressEvent.OnUnauthorized(isUnauthorized = true))<br>            }<br>            is InternalServerError -&gt; {<br>                _state.update { it.copy(isLoading = false) }<br>                _uiEvents.send(AddressEvent.OnTimeout(isTimeout = true))<br>            }<br>            else -&gt; {<br>                val messageError = (response as ResultState.Error).message<br>                _state.update { it.copy(isLoading = false) }<br>                _uiEvents.send(<br>                    AddressEvent.OnError(<br>                        isError = true,<br>                        errorMessage = messageError<br>                    )<br>                )<br>            }<br>        }<br>    }<br>    private fun onSetLatLong(latitude: Double, longitude: Double) = viewModelScope.launch {<br>        _state.update {<br>            it.copy(<br>                latitude = latitude,<br>                longitude = longitude<br>            )<br>        }<br>    }<br>}</pre><h3>Address State</h3><pre>data class AddressState(<br>    val isLoading: Boolean = false,<br>    val latitude: Double = 0.0,<br>    val longitude: Double = 0.0,<br>    val address: Address = Address()<br>)</pre><h3>Address Actions</h3><pre>sealed class AddressActions : UiAction {<br>    object OnFetcnAddress : AddressActions()<br>    data class OnSetLatLong(<br>        val latitude: Double,<br>        val longitude: Double<br>    ) : AddressActions()<br>}</pre><h3>Address Event</h3><pre>sealed class AddressEvent {<br>    data class OnSuccess(val isSuccess: Boolean) : AddressEvent()<br>    data class OnError(val isError: Boolean, val errorMessage: String) : AddressEvent()<br>    data class OnUnauthorized(val isUnauthorized: Boolean) : AddressEvent()<br>    data class OnTimeout(val isTimeout: Boolean) : AddressEvent()<br>}</pre><h3>Workflow Breakdown</h3><ol><li><strong>User Interaction Triggers an Action</strong>: When a user interacts with the UI (like entering text or clicking a button), it triggers an action that is sent to the ViewModel via a unified function, such as onEvent. This approach simplifies your UI code, allowing you to manage all interactions through a single function rather than multiple lambdas in child composables.</li><li><strong>UI State Updates</strong>: After processing the action, the ViewModel updates the state, and the UI observes these changes to re-render itself accordingly. This ensures that the UI reflects the latest data accurately. For example, you can update the loading state to show a loader after the sign-in action is triggered.</li></ol><pre>private fun onFetchAddress() = viewModelScope.launch {     <br>    // Get Address logic here...<br>    _state.update { it.copy(isLoading = false) <br>  }<br>}</pre><p><strong>3. Events Are Emitted</strong>: If an action requires a one-time UI response (such as an error message), the ViewModel emits an event that the UI can handle and display. This keeps events distinct from states, as events are transient and don’t need to be stored.</p><pre>private fun onFetchAddress() = viewModelScope.launch {    <br>      // Get Address logic here...<br>     is UnAuthorizationError -&gt; {<br>         _state.update { it.copy(isLoading = false) }<br>         _uiEvents.send(AddressEvent.OnUnauthorized(isUnauthorized = true))<br>     }<br> }</pre><h3>Why Adopt This Approach?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*H-3xOv9jI1jM7eaK" /></figure><ul><li><strong>Centralized Logic</strong>: Handling all user interactions through a single onEvent function centralizes the logic, making your code easier to maintain and understand.</li><li><strong>Simplified UI Code</strong>: Rather than passing multiple lambdas for different UI interactions, you only need to pass one lambda that triggers onEvent, simplifying your UI structure.</li><li><strong>Scalability</strong>: As your app grows, this pattern allows for easy addition of new actions, states, and events without complicating your ViewModel, making it suitable for complex UIs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ec0837235b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrasi ke Gradle Convention Plugin]]></title>
            <link>https://medium.com/@nizarnfl21/migrasi-ke-gradle-convention-plugin-53656cb0f07e?source=rss-f5e5e426c63f------2</link>
            <guid isPermaLink="false">https://medium.com/p/53656cb0f07e</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Nizar Naufal]]></dc:creator>
            <pubDate>Sat, 18 May 2024 16:49:17 GMT</pubDate>
            <atom:updated>2024-05-18T16:58:15.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*P6DL-EqPpHmjMiZ1JNjEfw.png" /></figure><p>Mengelola dependensi dalam proyek multi-modul menjadi kompleks dan sulit jika tidak dilakukan dengan benar. Dalam artikel ini, kita akan mengeksplorasi plugin Gradle Convention, yang membantu mengelola dependensi secara modular. Ini dilakukan dengan memindahkan logika konfigurasi build ke dalam plugin Gradle Convention dan menambahkan plugin yang diperlukan sesuai kebutuhan. Dengan cara ini, logika build tetap terpusat, perubahan di masa depan menjadi lebih mudah, dan semuanya dilakukan menggunakan bahasa pemrograman Kotlin.</p><p>Mari kita ambil contoh: Ketika kita membuat proyek multi-modul di mana Jetpack Compose diperlukan dalam submodul, kita perlu mendefinisikan properti dan dependensi berikut di file <strong>build.gradle</strong> setiap modul.</p><pre>dependencies {<br>    implementation(libs.bundles.uiDependencies)<br>    implementation(libs.bundles.composeDependencies)<br>    implementation(libs.bundles.lifecycleDependencies)<br>    implementation(libs.bundles.dataDependencies)<br>    implementation(libs.bundles.networkDependencies)<br>    implementation(libs.bundles.koinDependencies)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*JuhMOLERrYeoUP0jI7vPSw.png" /><figcaption>Project Level settings.gradle.kts</figcaption></figure><p>Pertama, kita perlu menyiapkan modul logika build di project level.</p><p>Konfigurasi tingkat proyek: Mari kita buat folder build-logic di proyek utama. Folder ini akan berisi semua skrip plugin konvensional yang akan kita buat. Di file settings.gradle.kts tingkat proyek, kita akan menyertakan build-logic dalam blok pluginManagement dengan mengidentifikasinya sebagai modul build.</p><pre>pluginManagement {<br>    includeBuild(&quot;build-logic/convention&quot;)<br>    repositories {<br>        google()<br>        mavenCentral()<br>        gradlePluginPortal()<br>    }<br>}<br>dependencyResolutionManagement {<br>    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)<br>    repositories {<br>        google()<br>        mavenCentral()<br>        maven(&quot;https://jitpack.io&quot;)<br>    }<br>}<br><br>rootProject.name = &quot;ShopMe&quot;<br>include(&quot;:app&quot;)</pre><p>Kedua, buatlah direktori convention di dalam modul <strong>build-logic</strong>, lalu buat file <strong>build.gradle.kts</strong> di dalam folder convention dan aktifkan <strong>kotlin-dsl</strong> dengan menambahkan plugin yang diperlukan seperti di bawah ini.</p><pre>plugins {<br>    `kotlin-dsl`<br>}<br><br>group = &quot;id.technzr.privateconventionplugin&quot;</pre><p>Untuk lebih lengkapnya ada di <a href="https://github.com/NizarNaufal/PrivateConventionPlugin"><strong>github</strong></a> untuk konfigurasi di <strong>build-logic</strong></p><h3>Creating gradle convention plugin</h3><p>Kita akan menggunakan contoh Compose ke dalam <strong>build-logic</strong> yang mendasar. Untuk mencapai itu, kita harus melakukan hal-hal berikut.</p><pre>internal fun Project.configureAndroidCompose(<br>    commonExtension: CommonExtension&lt;*, *, *, *&gt;,<br>) {<br>    commonExtension.apply {<br>        buildFeatures {<br>            compose = true<br>        }<br><br>        composeOptions {<br>            kotlinCompilerExtensionVersion = ConventionVersion.androidxComposeCompiler<br>        }<br><br>        dependencies {<br>            add(&quot;implementation&quot;, platform(ConventionDependency.androidxComposeBom))<br>            ConventionBundle.composeDependencies.forEach {<br>                add(&quot;implementation&quot;, it)<br>            }<br>            add(&quot;androidTestImplementation&quot;, platform(ConventionDependency.androidxComposeBom))<br>        }<br>    }<br>}</pre><p>Sekarang kita akan membuat plugin konvensi Gradle di <strong>src/main/kotlin</strong> di dalam modul build-logic, dan memberinya nama AndroidLibraryComposeConventionPlugin.</p><pre>class AndroidLibraryComposeConventionPlugin : Plugin&lt;Project&gt; {<br>    override fun apply(project: Project) {<br>        with(project) {<br>            with(pluginManager) {<br>                apply(&quot;com.android.library&quot;)<br>                apply(&quot;org.jetbrains.kotlin.android&quot;)<br>            }<br><br>            extensions.configure&lt;LibraryExtension&gt; {<br>                compileSdk = ConventionVersion.compileSdk.toInt()<br><br>                defaultConfig {<br>                    minSdk = ConventionVersion.minSdk.toInt()<br>                    testInstrumentationRunner = &quot;androidx.test.runner.AndroidJUnitRunner&quot;<br>                    consumerProguardFiles(&quot;consumer-rules.pro&quot;)<br>                }<br><br>                configureAndroidCompose(this)<br>            }<br>        }<br>    }<br>}</pre><p>Setelah <strong>AndroidLibraryComposeConventionPlugin</strong> dibuat, kita perlu menetapkan pluginId unik saat mendaftarkannya di dalam file build.gradle.kts seperti yang ditunjukkan di bawah ini.</p><pre>gradlePlugin {<br>    plugins {<br>       register(&quot;androidApplicationCompose&quot;) {<br>            id = &quot;technzr.android.application.compose&quot;<br>            implementationClass = &quot;AndroidApplicationComposeConventionPlugin&quot;<br>        }<br>       register(&quot;androidLibraryCompose&quot;) {<br>            id = &quot;technzr.android.library.compose&quot;<br>            implementationClass = &quot;AndroidLibraryComposeConventionPlugin&quot;<br>        }<br>    }<br>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F26666502&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fid%2Fview%2Fandroid-bugdroid-confused-huh-gif-26666502&amp;image=https%3A%2F%2Fmedia.tenor.com%2FVjsZ54DmWQAAAAAF%2Fandroid-bugdroid.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d5d4f3ec845889c82c4ddd763775c35/href">https://medium.com/media/5d5d4f3ec845889c82c4ddd763775c35/href</a></iframe><p>Nah , Selanjutnya bagaimana cara untuk menggunakannya ???</p><p>Kembali ke Project Level didalam module app <strong>build.gradle.kts</strong></p><pre>plugins {<br>    id(&quot;technzr.android.application.compose&quot;)<br>    id(&quot;com.google.gms.google-services&quot;)<br>    id(&quot;com.google.firebase.crashlytics&quot;)<br>    id(&quot;com.google.firebase.appdistribution&quot;)<br>}</pre><p>Mudah Bukan untuk penggunaan Gradle Convention Plugin</p><p>Manfaat dari penggunaan <strong>Gradle Convention Plugin</strong>:</p><ol><li>Konfigurasi build ditempatkan di satu tempat pusat yang membuatnya lebih mudah dikelola.</li><li>Dapat digunakan kembali untuk konfigurasi build umum sehingga kita tidak perlu menambahkan logika konfigurasi yang sama di setiap build.gradle.kts secara terpisah.</li><li>Lebih mudah untuk melakukan perubahan. Perubahan dilakukan di satu tempat pusat dan akan diterapkan di semua modul yang menggunakannya.</li><li>File build.gradle.kts akan memiliki kode dan logika yang lebih sedikit sehingga lebih sederhana dan lebih mudah dipahami.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FTfFDiw5gBuEns4ykJl%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Frickandmorty-season-1-adult-swim-rick-and-morty-TfFDiw5gBuEns4ykJl&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExbWNiNXZ5ZDY2eHI4dTdvdGdwNXlzZncwbmRzcWsyN3ZoY2NoazI2eiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FTfFDiw5gBuEns4ykJl%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/566a3d915b362efc872aa513814b5972/href">https://medium.com/media/566a3d915b362efc872aa513814b5972/href</a></iframe><p>Dan ini lah final project yang sudah di buat , jangan lupa untuk star di github saya , Terima kasih</p><p><a href="https://github.com/NizarNaufal/PrivateConventionPlugin">GitHub - NizarNaufal/PrivateConventionPlugin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53656cb0f07e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deteksi Jank UI dengan Profiler Android Studio]]></title>
            <link>https://medium.com/@nizarnfl21/deteksi-jank-ui-dengan-profiler-android-studio-c3844fe5c02a?source=rss-f5e5e426c63f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3844fe5c02a</guid>
            <category><![CDATA[android-studio]]></category>
            <dc:creator><![CDATA[Nizar Naufal]]></dc:creator>
            <pubDate>Sat, 18 May 2024 16:07:40 GMT</pubDate>
            <atom:updated>2024-05-18T16:07:40.268Z</atom:updated>
            <content:encoded><![CDATA[<p>Android merender antarmuka pengguna (UI) dengan membuat bingkai dari aplikasi Anda dan menampilkannya di layar. Untuk memastikan bahwa interaksi pengguna dengan aplikasi Anda lancar, aplikasi Anda harus merender setiap frame dengan kecepatan refresh yang ditentukan oleh setiap perangkat–misalnya, Pixel 6 memungkinkan rendering maksimal 90 frame per detik, yang berarti bahwa setiap frame memerlukan untuk dirender di bawah 11ms. Jika aplikasi Anda mengalami perenderan UI yang lambat, kerangka kerja Android terpaksa melewati bingkai. Ketika ini terjadi, pengguna merasakan gangguan visual yang tidak terduga dan mengganggu, juga dikenal sebagai jank.</p><h3>Mendeteksi jank di Android 12 dan yang lebih tinggi</h3><p>Untuk perangkat yang menggunakan Android 12 (API level 31) atau yang lebih tinggi, rekaman aktivitas akan ditampilkan di jalur <strong>Janky frames</strong> pada panel <strong>Display</strong> di CPU Profiler.</p><p>Untuk mendeteksi jank,</p><ol><li>Di Android Studio, pilih <strong>View &gt; Tool Windows &gt; Profiler</strong> atau klik <strong>Profile</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/0*8LdwPAxZiBHdGC3F" /></figure><p>2. Jika diminta oleh dialog <strong>Select Deployment Target</strong>, pilih perangkat tujuan deployment aplikasi untuk pembuatan profil.</p><p>3. Klik <strong>CPU</strong> untuk membuka CPU Profiler.</p><p>4. Pilih <strong>System Trace</strong> dari menu konfigurasi di CPU Profiler dan klik <strong>Record</strong>.</p><p>5. Anda akan melihat jalur <strong>Janky frames</strong> di bagian <strong>Display</strong>. Secara default, Profiler hanya menampilkan frame yang mengalami jank sebagai target untuk diselidiki. Dalam setiap frame yang mengalami jank, bagian berwarna merah menandai durasi frame yang melebihi batas waktu renderingnya.</p><p>dalam kasus project pribadi saya ini terdapat jank pada frames :</p><ul><li>Green Frames :<br>yang dianggap normal tidak ada jank.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*_E-ZvrOQrt1dkqXBiru7DA.png" /></figure><ul><li>Red Frames :<br>yang dianggap jank karena proses aplikasi berjalan lebih lama dari yang diharapkan dan melewatkan tenggat waktu durasi frames yang diharapkan. red frames yang dapat ditindaklanjuti biasanya.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*yFawQotmZKqWjYfBgNYv4A.png" /></figure><ul><li>Yellow Frames :<br>Frame yang dianggap sebagai buffer stuffing, artinya aplikasi terus mengirimkan frame ke sistem sebelum frame sebelumnya disajikan. Hal ini biasanya disebabkan oleh frame sebelumnya yang tersendat dan tidak banyak yang dapat dilakukan developer terkait frame kuning.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*Z28hX55QSLVuswsSA2GMEA.png" /><figcaption>yellow frames</figcaption></figure><p>Dan jika Anda ingin memeriksa perpustakaan baru kami untuk mendeteksi dan melaporkan “jank” di aplikasi produksi Anda yang berjalan di perangkat pengguna, kunjungi <a href="https://developer.android.com/reference/androidx/metrics/performance/JankStats">dokumentasi</a> JankStats!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3844fe5c02a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>