<?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[Clean Android Dev - Medium]]></title>
        <description><![CDATA[Welcome to this brand-new publication dedicated to Android, Kotlin, and Kotlin Multiplatform development! If you’re diving into Android, Kotlin, or Kotlin Multiplatform development and want to ensure your code is as clean as it can be, you’ve come to the right place! - Medium]]></description>
        <link>https://medium.com/clean-android-dev?source=rss----55056bc45674---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Clean Android Dev - Medium</title>
            <link>https://medium.com/clean-android-dev?source=rss----55056bc45674---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:28:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/clean-android-dev" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Modeling ViewModel State in Android: A Guide to Clean, Scalable Patterns]]></title>
            <link>https://medium.com/clean-android-dev/modeling-viewmodel-state-in-android-a-guide-to-clean-scalable-patterns-d42932ade940?source=rss----55056bc45674---4</link>
            <guid isPermaLink="false">https://medium.com/p/d42932ade940</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 08:08:05 GMT</pubDate>
            <atom:updated>2024-11-04T09:16:14.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3nU2fwxJNvRImqX86dj0dw.png" /></figure><p>Poorly designed models create a cascade of complications for every component that depends on them. In the case of presentation models, when these don’t align with the screen’s actual needs, other components (like ViewModels) are forced to work around them, resulting in bloated, hard-to-maintain classes filled with hacks and workarounds. This lack of alignment introduces ambiguity and confusion, leading to unclear, error-prone code that is costly to maintain.</p><p>Here are two of the most popular ways to model the ViewModel state:</p><pre>// Approach 1<br>data class ScreenState(<br>    val isLoading: Boolean,<br>    val isError: Boolean,<br>    val data: Data?<br>)</pre><pre>// Approach 2<br>sealed interface ScreenState {<br>    data object Loading : ScreenState<br>    data object Error : ScreenState<br>    data class Content(val data: Data) : ScreenState<br>}</pre><p>Both approaches have significant limitations and often require extensive workarounds. Today, we’ll analyze the pros and cons of each, and then I’ll introduce you to a third, simpler approach that aims to work effectively in all scenarios.</p><h3>Approach 1: Plain Data Class</h3><pre>data class ProductListScreenState(<br>    val isLoading: Boolean,<br>    val isError: Boolean,<br>    val productResults: ProductResults?<br>)<br><br>data class ProductResults(<br>    val products: List&lt;Product&gt;, <br>    val canLoadMore: Boolean<br>)</pre><p>Imagine a Product List Page where data is fetched from a remote source. During loading, a spinner shows, and if there’s an error, an error view with a retry option displays. This is a common Loading-Content-Error scenario.</p><pre>// Use case<br>fun interface GetProductResults {<br>    suspend operator fun invoke(startIndex: Int): Result&lt;ProductResults&gt;<br>}<br><br>// ViewModel<br>class ProductListViewModel(<br>    private val getProductResults: GetProductResults<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(<br>        ProductListScreenState(<br>            isLoading = true, <br>            isError = false, <br>            productResults = null<br>        )<br>    )<br>    val state = _state.asStateFlow()<br><br>    fun loadProducts() {<br>        _state.update {<br>            ProductListScreenState(<br>                isLoading = true, <br>                isError = false, <br>                productResults = null<br>            )<br>        }<br>        viewModelScope.launch {<br>            getProductResults(startIndex = 0).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        ProductListScreenState(<br>                            isLoading = false,<br>                            isError = false,<br>                            productResults = results<br>                        )<br>                    }<br>                },<br>                onFailure = {<br>                    _state.update {<br>                        ProductListScreenState(<br>                            isLoading = false,<br>                            isError = true,<br>                            productResults = null<br>                        )<br>                    }<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>This approach has several flaws:</p><ol><li>The model allows for conflicting states: both isLoading and isError can be set to true simultaneously, causing the UI to show both loading and error views at once.<br>Now, imagine adding more states to the screen, like isRefreshing or isPaginating. This setup could result in 2⁴ possible boolean combinations for a screen that actually has only five distinct states—leaving nine invalid combinations.</li><li>Each time the ViewModel sets a state, we have to ensure every other boolean is set to false, which introduces a lot of boilerplate code.<br>Additionally, when adding a new state, we need to refactor all state-setting code to include the new boolean, further increasing maintenance overhead.</li><li>In the view layer (whether in Compose or standard Android views), developers may be misled by the model and feel compelled to double-check the ViewModel implementation to understand which states are truly possible.</li></ol><h4>Why not use an enum?</h4><pre>data class ProductListScreenState(<br>    val displayState: DisplayState,<br>    val productResults: ProductResults?<br>)<br><br>enum class DisplayState {<br>    LOADING, CONTENT, ERROR<br>}</pre><pre>class ProductListViewModel(<br>    private val getProductResults: GetProductResults<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(<br>        ProductListScreenState(<br>            displayState = DisplayState.LOADING, <br>            productResults = null<br>        )<br>    )<br>    val state = _state.asStateFlow()<br><br>    fun loadProducts() {<br>        _state.update {<br>            ProductListScreenState(<br>                displayState = DisplayState.LOADING, <br>                productResults = null<br>            )<br>        }<br>        viewModelScope.launch {<br>            getProductResults(startIndex = 0).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        ProductListScreenState(<br>                            displayState = DisplayState.CONTENT,<br>                            productResults = results<br>                        )<br>                    }<br>                },<br>                onFailure = {<br>                    _state.update {<br>                        ProductListScreenState(<br>                            displayState = DisplayState.ERROR,<br>                            productResults = null<br>                        )<br>                    }<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>This is certainly a big improvement!</p><p>However, while this helps prevent some of the conflicting states, it’s only a partial solution. The enum doesn’t guarantee that productResults aligns with the displayState. For example, CONTENT should imply that productResults is non-null, but nothing enforces that here. Similarly, we could accidentally assign a LOADING or ERROR state with a non-null productResults.</p><p>In short, while the enum avoids many conflicts, it doesn’t fully handle mutually exclusive states, especially when those states need to hold additional data.</p><h4><strong>Shouldn’t You Write Unit Tests?</strong></h4><p>Regardless of the approach used, a complete test suite is essential for catching any issues within the ViewModel logic. Your unit tests should verify that displayState aligns correctly with the presence or absence of productResults. Tests should catch cases where the CONTENT state is accidentally paired with a null productResults, or where LOADING or ERROR states carry data that shouldn’t be there.</p><p>However, even with unit tests, this state model can be misleading when rendering the UI. Developers might still need to frequently double-check the ViewModel implementation to understand how the state is managed, leading to broken encapsulation and increased time spent reading code. This constant need for context-switching and verification erodes the clarity and maintainability of the code, making it more challenging for developers to work confidently within the UI layer.</p><h3>Approach 2: Sealed Interface</h3><pre>sealed interface ProductListScreenState {<br>    data object Loading : ProductListScreenState<br>    data object Error : ProductListScreenState<br>    data class Content(val productResults: ProductResults) : ProductListScreenState<br>}</pre><pre>class ProductListViewModel(<br>    private val getProductResults: GetProductResults<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow&lt;ProductListScreenState&gt;(<br>        ProductListScreenState.Loading<br>    )<br>    val state = _state.asStateFlow()<br><br>    fun loadProducts() {<br>        _state.update { ProductListScreenState.Loading }<br>        viewModelScope.launch {<br>            getProductResults(startIndex = 0).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        ProductListScreenState.Content(<br>                            productResults = results<br>                        )<br>                    }<br>                },<br>                onFailure = {<br>                    _state.update {<br>                        ProductListScreenState.Error<br>                    }<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>In this approach, we use sealed interfaces to ensure that conflicting states are impossible. Each state — Loading, Error, and Content—is represented explicitly, making the UI model readable and straightforward to render in the UI.</p><p>This approach works elegantly for the typical Loading-Content-Error scenario, but it introduces a major limitation: <strong>sharing data across states</strong>.</p><p>Consider an example where we want to display a user-specific welcome message in the action bar. If the user is logged in, we display &quot;Welcome back, {Full Name}”; if not, we simply display Welcome back. <br>This message should appear consistently across all states — whether the UI is in Loading, Content, or Error.</p><p>Assume we retrieve the full name via the following use case:</p><pre>fun interface ObserveUserFullName {<br>    operator fun invoke(): StateFlow&lt;String&gt;<br>}</pre><p>This use case, returns a StateFlow that emits the full name if the user is logged in and an empty string if logged out, allowing the UI to update in real time as the user’s authentication status changes.</p><p>With our current approach, we’re forced to handle this data separately and manually merge it with the current state:</p><pre>sealed interface ProductListScreenState {<br>    val fullName: String<br><br>    data class Loading(override val fullName: String) : ProductListScreenState<br>    data class Error(override val fullName: String) : ProductListScreenState<br>    data class Content(<br>        override val fullName: String, <br>        val productResults: ProductResults<br>    ) : ProductListScreenState<br>}</pre><pre>class ProductListViewModel(<br>    private val getProductResults: GetProductResults,<br>    private val observeUserFullName: ObserveUserFullName<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow&lt;ProductListScreenState&gt;(<br>        ProductListScreenState.Loading(observeUserFullName().value)<br>    )<br>    val state = _state.asStateFlow()<br>    <br>    init {<br>        observeUserFullName().onEach { fullName -&gt;<br>            updateStateWithFullName(fullName)<br>        }.launchIn(viewModelScope)<br>    }<br>    <br>    private fun updateStateWithFullName(fullName: String) {<br>        _state.update {<br>            when (val currentState = _state.value) {<br>                is ProductListScreenState.Loading -&gt; {<br>                    ProductListScreenState.Loading(fullName = fullName) <br>                }<br>                is ProductListScreenState.Content -&gt; {<br>                    ProductListScreenState.Content(<br>                        fullName = fullName,<br>                        productResults = currentState.productResults<br>                    )<br>                }<br>                is ProductListScreenState.Error -&gt; {<br>                    ProductListScreenState.Error(fullName = fullName)<br>                }<br>            }<br>        }<br>    }<br><br>    fun loadProducts() {<br>        _state.update { <br>            ProductListScreenState.Loading(fullName = observeUserFullName().value) <br>        }<br>        viewModelScope.launch {<br>            getProductResults(startIndex = 0).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        ProductListScreenState.Content(<br>                            fullName = observeUserFullName().value,<br>                            productResults = results<br>                        )<br>                    }<br>                },<br>                onFailure = {<br>                    _state.update {<br>                        ProductListScreenState.Error(fullName = observeUserFullName().value)<br>                    }<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>This requires considerably more code. In contrast, Approach 1 (using a data class) allowed us to leverage the copy() function to update fields efficiently. Here, however, we must check the current state explicitly and then update accordingly—adding complexity that can become unwieldy as we add more states to the screen.</p><h3>[FINAL] Approach 3: Data class wrapping sealed interface</h3><p>Each approach has its strengths and limitations:</p><ul><li>The plain data class approach suffers from readability issues and the risk of conflicting states.</li><li>The sealed interface approach, while clearer and conflict-free, has trouble sharing data across states.</li></ul><p><em>From this, we can deduce that </em><strong><em>data classes work well for fields that should always be present</em></strong><em>, while </em><strong><em>sealed interfaces are ideal for mutually exclusive fields</em></strong><em>.</em></p><p><strong>Solution:</strong></p><pre>data class ProductListScreenState(<br>    val fullName: String,<br>    val displayState: DisplayState<br>)<br><br>sealed interface DisplayState {<br>    data object Loading : DisplayState<br>    data object Error : DisplayState<br>    data class Content(val productResults: ProductResults) : DisplayState<br>}</pre><p>This solution uses a data class to wrap all the data that needs to be shared across states, along with a sealed interface, DisplayState, for state-specific data.</p><p>(I named the parent state ScreenState and the child state DisplayState, but I bet you can come up with better names!)</p><p>With this model in place, the ViewModel is greatly simplified and easier to manage:</p><pre>class ProductListViewModel(<br>    private val getProductResults: GetProductResults,<br>    private val observeUserFullName: ObserveUserFullName<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(<br>        ProductListScreenState(<br>            fullName = observeUserFullName().value,<br>            displayState = DisplayState.Loading<br>        )<br>    )<br>    val state = _state.asStateFlow()<br><br>    init {<br>        observeUserFullName().onEach { fullName -&gt;<br>            _state.update { it.copy(fullName = fullName) }<br>        }.launchIn(viewModelScope)<br>    }<br><br>    fun loadProducts() {<br>        _state.update {<br>            it.copy(displayState = DisplayState.Loading)<br>        }<br>        viewModelScope.launch {<br>            getProductResults(startIndex = 0).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        it.copy(displayState = DisplayState.Content(results))<br>                    }<br>                },<br>                onFailure = {<br>                    _state.update {<br>                        it.copy(displayState = DisplayState.Error)<br>                    }<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>As you can see, we can update only the fields that need to be changed, thanks to the copy method from data classes, while also preventing any possible conflicting states.</p><h4>How will this scale?</h4><p>Let’s make things more complex to test whether this data modeling approach truly holds up:</p><ol><li>We don’t want to reload data when the device rotates.</li><li>We introduce a pull-to-refresh action; while refreshing, we show the current products with a secondary loading indicator at the top of the screen. If refreshing fails, we display the regular full-screen error view.</li><li>We add pagination; while paginating, we show the current products with a secondary loading indicator at the bottom of the screen. If pagination fails, we display an error view at the bottom of the list, allowing the user to retry.</li></ol><p>The updated state model now looks like this:</p><pre>data class ProductListScreenState(<br>    val fullName: String,<br>    val displayState: DisplayState? = null<br>)<br><br>sealed interface DisplayState {<br>    data object Loading : DisplayState<br>    data object Error : DisplayState<br>    data class Content(<br>        val productResults: ProductResults,<br>        val contentDisplayState: ContentDisplayState? = null<br>    ) : DisplayState<br>}<br><br>sealed interface ContentDisplayState {<br>    data object Refreshing : ContentDisplayState<br>    data object Paginating : ContentDisplayState<br>    data object PaginationError : ContentDisplayState<br>}</pre><p>Here, displayState is nullable: when it’s null, we should load the initial data; otherwise, any additional loading requests should be ignored.</p><p>Refreshing and Paginating are sub-states of Content, meaning we can only refresh or paginate when the screen is already displaying the list of products. Naturally, any request made while we’re not in the Content state should be ignored!</p><p>Here’s the ViewModel:</p><pre>class ProductListViewModel(<br>    private val getProductResults: GetProductResults,<br>    observeUserFullName: ObserveUserFullName<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(<br>        ProductListScreenState(<br>            fullName = observeUserFullName().value,<br>            displayState = DisplayState.Loading<br>        )<br>    )<br>    val state = _state.asStateFlow()<br><br>    init {<br>        observeUserFullName().onEach { fullName -&gt;<br>            _state.update { it.copy(fullName = fullName) }<br>        }.launchIn(viewModelScope)<br>    }<br><br>    fun loadProducts() {<br>        if (_state.value.displayState == null) {<br>            _state.update {<br>                it.copy(displayState = DisplayState.Loading)<br>            }<br>            fetchProducts()<br>        }<br>    }<br><br>    fun refresh() {<br>        onContentDisplayState { content -&gt;<br>            _state.update {<br>                it.copy(<br>                    displayState = content.copy(<br>                        contentDisplayState = ContentDisplayState.Refreshing<br>                    )<br>                )<br>            }<br>            fetchProducts()<br>        }<br>    }<br><br>    fun paginate() {<br>        onContentDisplayState { content -&gt;<br>            val productResults = content.productResults<br>            if (productResults.canLoadMore) {<br>                _state.update {<br>                    it.copy(<br>                        displayState = content.copy(<br>                            contentDisplayState = ContentDisplayState.Paginating<br>                        )<br>                    )<br>                }<br>                paginateProducts(productResults.products.size)<br>            }<br>        }<br>    }<br><br>    private fun fetchProducts() {<br>        viewModelScope.launch {<br>            getProductResults(startIndex = 0).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        it.copy(displayState = DisplayState.Content(results))<br>                    }<br>                },<br>                onFailure = {<br>                    _state.update {<br>                        it.copy(displayState = DisplayState.Error)<br>                    }<br>                }<br>            )<br>        }<br>    }<br><br>    private fun paginateProducts(startIndex: Int) {<br>        viewModelScope.launch {<br>            getProductResults(startIndex).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        it.copy(displayState = DisplayState.Content(results))<br>                    }<br>                },<br>                onFailure = {<br>                    onContentDisplayState { content -&gt;<br>                        _state.update {<br>                            it.copy(<br>                                displayState = content.copy(<br>                                    contentDisplayState = ContentDisplayState.PaginationError<br>                                )<br>                            )<br>                        }<br>                    }<br>                }<br>            )<br>        }<br>    }<br><br>    private fun onContentDisplayState(block: (content: DisplayState.Content) -&gt; Unit) {<br>        val displayState = _state.value.displayState<br>        if (displayState is DisplayState.Content) {<br>            block(displayState)<br>        }<br>    }<br>}</pre><p>Pretty straightforward! Let’s break it down step by step.</p><pre>fun loadProducts() {<br>        if (_state.value.displayState == null) {<br>            _state.update {<br>                it.copy(displayState = DisplayState.Loading)<br>            }<br>            fetchProducts()<br>        }<br>    }</pre><p>The loadProducts function now checks if the displayState is null. This can only happen the first time we open the screen. When we rotate the device, the ViewModel will ignore the request to load the data again.</p><p>I made displayState nullable, but I could have also introduced a new DisplayState, let&#39;s say Idle, and checked against it instead. <br>I opted for the option that requires less code.</p><pre>fun refresh() {<br>        onContentDisplayState { content -&gt;<br>            _state.update {<br>                it.copy(<br>                    displayState = content.copy(<br>                        contentDisplayState = ContentDisplayState.Refreshing<br>                    )<br>                )<br>            }<br>            fetchProducts()<br>        }<br>    }</pre><p>The refresh function checks if we are in the Content state. If we are, it sets the displayState to Content/Refreshing and loads the data again; if not, it ignores the request.</p><pre>fun paginate() {<br>        onContentDisplayState { content -&gt;<br>            val productResults = content.productResults<br>            if (productResults.canLoadMore) {<br>                _state.update {<br>                    it.copy(<br>                        displayState = content.copy(<br>                            contentDisplayState = ContentDisplayState.Paginating<br>                        )<br>                    )<br>                }<br>                paginateProducts(productResults.products.size)<br>            }<br>        }<br>    }</pre><p>The paginate function checks if we are in the Content state. If we are, it sets the displayState to Content/Paginating and loads the next set of products; if not, it ignores the request. If pagination fails, Content/PaginationError is set.</p><p>Refreshing, Paginating, and PaginationError states are child states of Content. Hence, I added a contentDisplayState field inside Content to make these child states mutually exclusive while keeping the shared data productResults as part of the Content data class. This is the same concept applied to the ScreenState, which is now applied again to a child state.</p><p>I made this contentDisplayState nullable so that I could separate a pure content state from a Paginating/Refreshing state. Again, I could have introduced another contentDisplayState object, but the nullable option required less code.</p><h3>Conclusion</h3><p>In this article, we examined various approaches to modeling ViewModel state in Android. Rather than sticking to a single pattern, it’s beneficial to leverage the strengths of multiple patterns and mix them together, as we have seen. This mixed approach not only enhances maintainability and readability but also allows you to adapt your state management to future requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d42932ade940" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clean-android-dev/modeling-viewmodel-state-in-android-a-guide-to-clean-scalable-patterns-d42932ade940">Modeling ViewModel State in Android: A Guide to Clean, Scalable Patterns</a> was originally published in <a href="https://medium.com/clean-android-dev">Clean Android Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to “Safely” Migrate from Retrofit to Ktor]]></title>
            <link>https://medium.com/clean-android-dev/how-to-safely-migrate-from-retrofit-to-ktor-428fd6b6d330?source=rss----55056bc45674---4</link>
            <guid isPermaLink="false">https://medium.com/p/428fd6b6d330</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 20:44:17 GMT</pubDate>
            <atom:updated>2024-10-01T21:01:38.467Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GO6LKncawmfGPViEUuuDXw.jpeg" /></figure><p>Retrofit has long been a cornerstone of Android development, offering a straightforward, efficient, and dependable way to manage network requests. With its clean API, seamless integration with libraries like Moshi and Gson, and robust support for REST APIs, Retrofit has made it easy for developers to build network-driven applications. For years, it has been the go-to choice for those seeking to implement clean, maintainable networking code.</p><p>However, as the development landscape evolves, many developers are now looking toward Ktor. A major factor driving this shift is the rising popularity of Kotlin Multiplatform (KMP), which enables seamless development across Android, iOS, and other platforms thanks to Ktor’s multiplatform support. Yet, KMP isn’t the only reason for the switch; many developers are drawn to Ktor for its modern design, offering enhanced flexibility and a more streamlined approach to handling network requests.</p><p>Ktor’s coroutine-based architecture, customizable features, and fully Kotlin-centric design present a compelling alternative for those who appreciate a more native solution tailored for Kotlin development.</p><p>So, whether you’re looking to embrace Kotlin Multiplatform (KMP) or prefer Ktor for its design philosophy, this guide is here to assist you every step of the way!</p><p>You can access the sample code for the migration guide <a href="https://github.com/DenisBronx/RetrofitToKtorGuide/tree/migrated-to-ktor">here</a>.</p><h3>Step 1: Ensure Your Code is Well-Tested</h3><p>To successfully migrate your code from Retrofit to Ktor, it’s essential to ensure that you avoid introducing any regressions. Different frameworks operate in unique ways, often obscuring certain details from developers.</p><p>For example, did you know that in Ktor, you can’t parse JSON request or response bodies unless the appropriate header such as Content-Type: application/json is included in the request or response? This is a crucial detail that can impact the functionality of your application during the migration process.</p><p>It’s perfectly normal to encounter challenges and run into issues when working with a new library, especially if you don’t have much experience with it yet. Adapting to a different framework can be daunting, but don’t let that discourage you.</p><p>The best way to ensure a smooth migration is to cover your code with unit tests. With unit tests in place, you can identify issues immediately, rather than relying on manual testing on a device. This approach allows you to play around with the new library while receiving instant feedback, creating efficient feedback loops that facilitate your learning and development process.</p><h4>Testing with NetMock</h4><p><em>If your code is already fully tested and your tests are decoupled from implementation details, you can skip this step. Otherwise, keep reading!</em></p><p>When writing tests, it’s essential to ensure they are as decoupled as possible from both implementation details and frameworks. This decoupling enables you to refactor your code with minimal changes to your test code. If you find that modifications in your production code necessitate extensive changes to your tests, it’s a sign that your tests may be overly coupled and could hinder your refactoring efforts.</p><p>The ideal solution for testing network requests and responses, as well as the data layer as a whole, is to use <strong>NetMock</strong>.</p><p><a href="https://github.com/DenisBronx/NetMock">GitHub - DenisBronx/NetMock</a></p><p>This framework-independent library sets up its own localhost server, redirecting your network requests to it, allowing you to provide custom stub responses. Best of all, <strong>NetMock is extremely simple to use</strong>, making it an excellent choice for ensuring your network interactions are effectively tested without being tied to a specific framework. With NetMock, you can create robust and adaptable tests that streamline your development process.</p><h4>Now, let’s dive into the code!</h4><p>Imagine we have the following code that uses Retrofit to retrieve all the GitHub repositories of a specified organization, provided that the organization exists:</p><pre>interface GithubProjectApiService {<br>    @Headers(&quot;Content-Type: application/json&quot;)<br>    @GET(&quot;orgs/{organisation}/repos&quot;)<br>    suspend fun getProjectsForOrganisation(<br>        @Path(&quot;organisation&quot;) organisation: String<br>    ): Response&lt;List&lt;JsonGithubProject&gt;&gt;<br>}<br><br>sealed class Answer&lt;out T, out E&gt; {<br>    data class Success&lt;out T&gt;(val data: T) : Answer&lt;T, Nothing&gt;()<br>    data class Error&lt;out E&gt;(val reason: E) : Answer&lt;Nothing, E&gt;()<br>}<br><br>class RealGithubProjectRepository(<br>    private val githubProjectApiService: GithubProjectApiService<br>) : GithubProjectRepository {<br>    override suspend fun getProjectsForOrganisation(<br>        organisation: String<br>    ): Answer&lt;List&lt;GithubProject&gt;, GetProjectsError&gt; {<br>        return try {<br>            val apiResponse = githubProjectApiService.getProjectsForOrganisation(organisation)<br>            return mapSuccess(apiResponse)<br>        } catch (t: Throwable) {<br>            Answer.Error(GetProjectsError.GenericError)<br>        }<br>    }<br><br>    private fun mapSuccess(<br>        apiResponse: Response&lt;List&lt;JsonGithubProject&gt;&gt;<br>    ): Answer&lt;List&lt;GithubProject&gt;, GetProjectsError&gt; {<br>        return if (apiResponse.isSuccessful) {<br>            val projects = apiResponse.body()<br>            if (projects != null) {<br>                Answer.Success(mapDtoList(projects))<br>            } else {<br>                Answer.Error(GetProjectsError.GenericError)<br>            }<br>        } else {<br>            mapError(apiResponse.code())<br>        }<br>    }<br><br>    private fun mapDtoList(dtoList: List&lt;JsonGithubProject&gt;): List&lt;GithubProject&gt; {<br>        return dtoList.map { jsonDto -&gt;<br>            GithubProject(<br>                jsonDto.id,<br>                jsonDto.name,<br>                jsonDto.fullName,<br>                jsonDto.description,<br>                jsonDto.owner.avatarUrl<br>            )<br>        }<br>    }<br><br>    private fun mapError(errorCode: Int): Answer&lt;List&lt;GithubProject&gt;, GetProjectsError&gt; {<br>        val error = if (errorCode == 404) {<br>            GetProjectsError.NoOrganizationFound<br>        } else {<br>            GetProjectsError.GenericError<br>        }<br>        return Answer.Error(error)<br>    }<br>}</pre><p>Next, we’ll integrate <strong>NetMock</strong> into the project to enable us to stub network requests and responses:</p><pre>testImplementation &quot;io.github.denisbronx.netmock:netmock-server:$version&quot;</pre><p>With NetMock set up, we can easily test and stub our requests and responses by simply writing:</p><pre>netMock.addMock(<br>    request = NetMockRequest(<br>        requestUrl = &quot;$BASE_URL/orgs/$ORGANIZATION/repos&quot;,<br>        method = Method.Get,<br>        mandatoryHeaders = mapOf(&quot;Content-Type&quot; to &quot;application/json&quot;)<br>    ),<br>    response = NetMockResponse(<br>        code = 200,<br>        mandatoryHeaders = mapOf(&quot;Content-Type&quot; to &quot;application/json&quot;),<br>        body = readFromResources(&quot;responses/github_projects_success.json&quot;)<br>    )<br>)</pre><p>To achieve full unit test coverage for the RealGithubProjectRepository, we would implement something like this:</p><pre>class RealGithubProjectRepositoryTest {<br><br>    @get:Rule<br>    val netMock = NetMockServerRule()<br><br>    private val okHttpClient = OkHttpClient.Builder().addInterceptor(netMock.interceptor).build()<br>    private val retrofit = Retrofit.Builder()<br>        .baseUrl(BASE_URL)<br>        .client(okHttpClient)<br>        .addConverterFactory(MoshiConverterFactory.create())<br>        .build()<br><br>    private val sut = RealGithubProjectRepository(retrofit.create&lt;GithubProjectApiService&gt;())<br><br>    @Test<br>    fun `EXPECT empty list of projects WHEN body is empty list`() = runTest {<br>        netMock.addMock(<br>            request = EXPECTED_REQUEST,<br>            response = NetMockResponse(<br>                code = 200,<br>                mandatoryHeaders = MANDATORY_HEADERS,<br>                body = &quot;[]&quot;<br>            )<br>        )<br><br>        val result = sut.getProjectsForOrganisation(ORGANIZATION)<br><br>        assertEquals(Answer.Success(emptyList&lt;GithubProject&gt;()), result)<br>    }<br><br>    @Test<br>    fun `EXPECT generic error WHEN error is 500`() = runTest {<br>        netMock.addMock(<br>            request = EXPECTED_REQUEST,<br>            response = NetMockResponse(<br>                code = 500,<br>                mandatoryHeaders = MANDATORY_HEADERS,<br>            )<br>        )<br><br>        val result = sut.getProjectsForOrganisation(ORGANIZATION)<br><br>        assertEquals(Answer.Error(GetProjectsError.GenericError), result)<br>    }<br><br>    @Test<br>    fun `EXPECT not found error WHEN error is 404`() = runTest {<br>        netMock.addMock(<br>            request = EXPECTED_REQUEST,<br>            response = NetMockResponse(<br>                code = 404,<br>                mandatoryHeaders = MANDATORY_HEADERS<br>            )<br>        )<br><br>        val result = sut.getProjectsForOrganisation(ORGANIZATION)<br><br>        assertEquals(Answer.Error(GetProjectsError.NoOrganizationFound), result)<br>    }<br><br>    @Test<br>    fun `EXPECT generic error WHEN response is successful but body is empty`() = runTest {<br>        netMock.addMock(<br>            request = EXPECTED_REQUEST,<br>            response = NetMockResponse(<br>                code = 200,<br>                mandatoryHeaders = MANDATORY_HEADERS,<br>                body = &quot;&quot;<br>            )<br>        )<br><br>        val result = sut.getProjectsForOrganisation(ORGANIZATION)<br><br>        assertEquals(Answer.Error(GetProjectsError.GenericError), result)<br>    }<br><br>    @Test<br>    fun `EXPECT generic error WHEN response is successful but body is not parseable`() = runTest {<br>        netMock.addMock(<br>            request = EXPECTED_REQUEST,<br>            response = NetMockResponse(<br>                code = 200,<br>                mandatoryHeaders = MANDATORY_HEADERS,<br>                body = &quot;null&quot;<br>            )<br>        )<br><br>        val result = sut.getProjectsForOrganisation(ORGANIZATION)<br><br>        assertEquals(Answer.Error(GetProjectsError.GenericError), result)<br>    }<br><br>    @Test<br>    fun `EXPECT mapped list of projects WHEN body is non empty list`() = runTest {<br>        netMock.addMock(<br>            request = EXPECTED_REQUEST,<br>            response = NetMockResponse(<br>                code = 200,<br>                mandatoryHeaders = MANDATORY_HEADERS,<br>                body = readFromResources(&quot;responses/github_projects_success.json&quot;)<br>            )<br>        )<br><br>        val result = sut.getProjectsForOrganisation(ORGANIZATION)<br><br>        assertEquals(Answer.Success(EXPECTED_GH_PROJECTS), result)<br>    }<br><br>    private companion object {<br>        const val BASE_URL = &quot;https://api.github.com&quot;<br>        const val ORGANIZATION = &quot;square&quot;<br>        val MANDATORY_HEADERS = mapOf(&quot;Content-Type&quot; to &quot;application/json&quot;)<br>        val EXPECTED_REQUEST = NetMockRequest(<br>            requestUrl = &quot;$BASE_URL/orgs/$ORGANIZATION/repos&quot;,<br>            method = Method.Get,<br>            mandatoryHeaders = MANDATORY_HEADERS<br>        )<br><br>        val EXPECTED_GH_PROJECTS = listOf(<br>            GithubProject(<br>                id = &quot;892275&quot;,<br>                name = &quot;retrofit&quot;,<br>                fullName = &quot;square/retrofit&quot;,<br>                description = &quot;A type-safe HTTP client for Android and the JVM&quot;,<br>                imageUrl = &quot;https://avatars.githubusercontent.com/u/82592?v=4&quot;<br>            ),<br>            GithubProject(<br>                id = &quot;1907635&quot;,<br>                name = &quot;JSONKit&quot;,<br>                fullName = &quot;square/JSONKit&quot;,<br>                description = &quot;Objective-C JSON&quot;,<br>                imageUrl = &quot;https://avatars.githubusercontent.com/u/82592?v=4&quot;<br>            )<br>        )<br>    }<br><br>}</pre><p>These tests cover the following scenarios:</p><ol><li>The API call is successful, but the organization has no repositories.</li><li>The service is unavailable.</li><li>The specified organization cannot be found.</li><li>A successful response returns an unexpected empty body.</li><li>A successful response yields an unexpected unparseable body.</li><li>A successful response returns valid results.</li></ol><p>For reference, <a href="https://github.com/DenisBronx/RetrofitToKtorGuide/blob/retrofit-implementation/app/src/test/resources/responses/github_projects_success.json">here’s the JSON response file</a> used for scenario 6.</p><p>As you can see, NetMock simplifies the process of stubbing requests and responses to just a few lines of code, making the test functions easy to read and understand.</p><h3>Step 2: Migrate from Retrofit to Ktor</h3><p>We’ve finally reached this exciting stage!</p><p>Now that our production code is fully tested, we can embark on the migration journey. What better way to illustrate this process than through a Git diff (full reference <a href="https://github.com/DenisBronx/RetrofitToKtorGuide/commit/deaa78d511a972a733df1268eecaabf711ecfea4">here</a>)?</p><p>As diligent TDD practitioners, let’s begin with the unit tests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brWD9Yaa6-9NS_9ZZ61JGQ.png" /></figure><p>As you can see, the changes in the tests are minimal — primarily limited to the setup. The only notable difference is that I had to trigger a parsing exception in a slightly different manner.</p><p>Next, let’s look at the repository migration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZfAgx9Kp1gSBf0BC_Y3WA.png" /></figure><p>Finally, here’s the updated DTO class used for parsing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RW5iRb6Ccp35ED1QTxx6Hg.png" /></figure><p>In this migration, I’ve also transitioned from Moshi to Kotlinx-Serialization (yes, you get a two-for-one benefit with this article!). The reason for this change is that Ktor does not support Moshi out of the box, and if the goal is to create a multiplatform project, Moshi is not suitable, as it only works with the JVM.</p><p>Once again, this migration between frameworks has been remarkably straightforward, thanks to our unit tests lowly coupled with implementation details.</p><h3>Step 3 (Bonus): Switch to NetMock Engine for Multiplatform</h3><p>If your only goal was to migrate safely, congratulations, you’re all set! Feel free to stop here.</p><p>However, if you’re aiming for a multiplatform setup, this next, straightforward step is essential. While <strong>netmock-server</strong> has served us well so far, it’s worth noting that, despite its framework independence, it is only compatible with the JVM.</p><p>But don’t worry! Switching to <strong>netmock-engine, </strong>the lightweight multiplatform variant built on top of the Ktor engine , is all you need to do.</p><p>Once again, what better way to demonstrate this migration than with a Git diff (full reference <a href="https://github.com/DenisBronx/RetrofitToKtorGuide/commit/4bf61bda93a08e18715d66828d9802b31c4cc19c">here</a>)?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7X_op_g3bF1rK63eOi_TYw.png" /></figure><p>As you can see, you simply need to replace netmock-server with netmock-engine in your Gradle configuration and update the initialization of the NetMock instance along with the Ktor HttpClient. And that’s it!</p><p>Now, all that’s left is to migrate the rest of your code to Kotlin Multiplatform (KMP), and you’ll be all set!</p><h3>Final Notes</h3><p>Migrating from Retrofit to Ktor can seem like a daunting task, but with the right approach and tools, it can be a smooth and rewarding experience. Throughout this guide, we’ve emphasized the importance of maintaining comprehensive unit tests that are decoupled from implementation details. This practice not only helps you safeguard against regressions during the migration but also enables you to adapt more easily to changes in your codebase.</p><p>Using <strong>NetMock</strong> has proven invaluable in our testing process. Its framework-independent design allows for efficient stubbing of network requests and responses, ensuring that your tests remain clear and concise. Transitioning to <strong>netmock-engine</strong> for a multiplatform setup further enhances your ability to develop applications that can run seamlessly across different platforms.</p><p>In summary, by following these steps — thoroughly testing your existing code, executing a careful migration, and leveraging tools like NetMock — you can confidently transition to Ktor while ensuring your application remains robust and maintainable. <br>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=428fd6b6d330" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clean-android-dev/how-to-safely-migrate-from-retrofit-to-ktor-428fd6b6d330">How to “Safely” Migrate from Retrofit to Ktor</a> was originally published in <a href="https://medium.com/clean-android-dev">Clean Android Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing NetMock: Simplifying HTTP Request Testing in Java, Android, and Kotlin Multiplatform]]></title>
            <link>https://medium.com/clean-android-dev/introducing-netmock-simplifying-http-request-testing-in-java-android-and-kotlin-multiplatform-769aeabbb214?source=rss----55056bc45674---4</link>
            <guid isPermaLink="false">https://medium.com/p/769aeabbb214</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 15:01:26 GMT</pubDate>
            <atom:updated>2023-06-14T15:06:16.062Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s get rid of the complexities of simulating requests and responses in testing environments</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDZMKjADoAqP0hoAryN2fQ.png" /><figcaption>NetMock code</figcaption></figure><p>I am thrilled to introduce NetMock, a powerful and user-friendly library designed to streamline the mocking of HTTP requests and responses.</p><p>Testing HTTP requests can often present challenges for developers due to the complexity of simulating requests and responses in testing environments. This can result in increased time and resources spent on manual testing. Having faced similar struggles with existing HTTP libraries and cumbersome mocking tools, I took it upon myself to create a solution: NetMock.</p><p>NetMock is designed to integrate with Java, Android, and Kotlin Multiplatform seamlessly. With minimal setup, you can effortlessly create mocks that accurately mimic client requests and real endpoint responses. One of the key advantages of NetMock is its consistent approach to mocking HTTP requests and responses. This proves especially beneficial when working on projects employing different libraries or considering a transition from one library to another.</p><p>Another noteworthy aspect of NetMock is its user-friendly design. Unlike many other HTTP mocking tools, NetMock prioritizes ease of use. The library offers an intuitive interface and a straightforward setup process, catering to developers needing to be better-versed in HTTP libraries.</p><p>Whether you are a seasoned developer or just starting, NetMock is the perfect solution for simplifying your workflow and reducing the time and effort required to create robust, reliable software.</p><p>If you want to explore NetMock further, you can find the NetMock repository on GitHub at <a href="https://github.com/DenisBronx/NetMock">https://github.com/DenisBronx/NetMock</a>.</p><h3>Improving Testing Strategy for HTTP-Related Code</h3><p>As a professional software engineer, I firmly believe in the critical importance of comprehensive unit testing for all code. However, I have observed a common practice among developers to neglect unit testing in the network layer due to the challenges involved in mocking and testing this area. Instead, they often rely on end-to-end automated tests or manual testing.</p><p>In various projects, I have encountered an approach where HTTP-related code is isolated into separate components to enable independent testing of the remaining system. While this approach can lead to leaner repositories and test classes, it often results in neglecting the testing of the HTTP code itself, as it is considered challenging to test. As a consequence, crucial logic related to HTTP requests and JSON parsing still needs to be validated.</p><p>This issue is exemplified in projects that utilize the Retrofit library, which abstracts the HTTP-related logic through interfaces. Consider the following code snippet:</p><pre>interface GitHubService {<br>    @GET(&quot;users/{user}/repos&quot;)<br>    suspend fun listRepos(@Path(&quot;user&quot;) user: String): List&lt;RepoDto&gt;<br>}<br><br>class GitHubRepositoryImpl(<br>    private val githubService: GitHubService,<br>    private val repoMapper: RepoMapper<br>): GitHubRepository {<br>    override suspend fun listRepos(user: String): List&lt;Repo&gt; {<br>        val repoDtos = githubService.listRepos(user)<br>        return repoMapper.map(repoDtos)<br>    }<br>}</pre><p>While this approach can simplify repositories and test classes, it often omits crucial tests for the HTTP-related logic. Additionally, developers may create unnecessary components solely to simplify unit testing of repositories.</p><p>Unit testing aims to prevent and identify mistakes made by developers, ensuring that the code functions as intended. Without adequate tests, even simple errors, such as changing the path from users/{user}/repos to user/{user}/repos or renaming a field in RepoDto may go unnoticed, which is unacceptable in a professional project.</p><p>My critique is in no way targeted at the Retrofit library itself.</p><p>On the contrary, I consider it an exceptional and highly readable library.</p><p>Furthermore, I recognize the value of isolating HTTP-related code into separate components for improved organization and maintainability.</p><p>Rather, I intend to shed light on a flawed testing strategy I have observed in numerous projects. This strategy often needs to pay more attention to the comprehensive testing of the HTTP code, resulting in potential issues going unnoticed. By highlighting this concern, I encourage developers to prioritize thorough testing of their HTTP-related logic, thus ensuring their projects&#39; overall quality and reliability.</p><h3>Mocking Requests and Responses with NetMock</h3><pre>@Test<br>fun `your test`() = runTest {<br>    val user = &quot;some_user&quot;<br>    netMock.addMock(<br>        request = {<br>            method = Method.Get<br>            requestUrl = &quot;https://api.github.com/users/$user/repos&quot;<br>        },<br>        response = {<br>            code = 200<br>            body = readFromResources(&quot;responses/repo_list.json&quot;)<br>        }<br>    )<br><br>    val result = sut.listRepos(user)<br><br>    //...<br>}</pre><p>To mock requests and responses, you can utilize the simple API provided by NetMock.</p><p>By adding a mock to the queue of expected requests and responses, you can intercept and control the behavior of HTTP interactions during testing.</p><h4>Creating a NetMock instance</h4><p>NetMock offers two flavors: netmock-server and netmock-engine.</p><p>The netmock-server flavor is compatible with Java, Kotlin, and Android, and it is library-independent. It allows you to mock network requests by redirecting them to a localhost web server using <a href="https://github.com/square/okhttp/tree/master/mockwebserver">MockWebServer</a>. This flavor is perfect for developers working on non-Multiplatform projects who want to test their network requests without setting up a separate server.</p><p>The netmock-engine flavor, on the other hand, is specifically designed for developers using Ktor or working with Kotlin Multiplatform. It employs MockEngine under the hood instead of a localhost server, making it a lightweight and multiplatform option for those working with Ktor.</p><h4>Working with NetMockServer</h4><p>To add netmock-server to your project, add the following to your dependencies in build.gradle file:</p><pre>dependencies {<br>    testImplementation &quot;io.github.denisbronx.netmock:netmock-server:0.4.0&quot;<br>}</pre><p>Next, create a NetMockServer instance as follows:</p><pre>@get:Rule<br>val netMock = NetMockServerRule()</pre><p>NetMockServer starts a localhost server that will intercept your requests using <a href="https://github.com/square/okhttp/tree/master/mockwebserver">MockWebServer</a>. The NetMockServerRule handles the server’s lifecycle, automatically starting and shutting it down for each test.</p><p>Once the server is up and running, you can configure your code to point to the localhost base URL using netmock.baseUrl. <br>Here are examples of Retrofit and Ktor:</p><p>Retrofit example that uses localhost:</p><pre>@get:Rule<br>val netMock = NetMockServerRule()<br><br>private val service = Retrofit.Builder()<br>    .baseUrl(netMock.baseUrl)<br>    .build()<br>    .create(GitHubService::class.java)</pre><p>Ktor example that uses localhost:</p><pre>@get:Rule<br>val netMock = NetMockServerRule()<br>    <br>private val client = HttpClient(OkHttp) {<br>    defaultRequest {<br>        url(netMock.baseUrl)<br>    }<br>}</pre><p>Alternatively, you can add an interceptor using netmock.interceptor, which automatically redirects requests to localhost:</p><p>Retrofit example that uses a real URL:</p><pre>@get:Rule<br>val netMock = NetMockServerRule()<br><br>private val service = Retrofit.Builder()<br>    .baseUrl(&quot;https://api.github.com/&quot;)<br>    .client(OkHttpClient.Builder().addInterceptor(netMock.interceptor).build())<br>    .build()<br>    .create(GitHubService::class.java)</pre><p>Ktor example that uses a real URL:</p><pre>@get:Rule<br>val netMock = NetMockServerRule()<br>    <br>private val client = HttpClient(OkHttp) {<br>    engine {<br>        addInterceptor(netMock.interceptor)<br>    }<br>}</pre><p>An interceptor is recommended, as it allows you to work with real and dynamic URLs.</p><p>However, note that you’ll need a library compatible with OkHttp interceptors, such as OkHttp itself, Retrofit, or Ktor.</p><h3><strong>Final Thoughts</strong></h3><p>Apart from the initialization process, both flavors of NetMock are essentially identical. This means that transitioning between netmock-server and netmock-engine requires minimal modifications. This flexibility allows you to switch seamlessly between different libraries, such as transitioning from Retrofit to Ktor or vice versa, without modifying your tests.</p><p>Decoupling your testing framework from the underlying libraries can enhance your confidence in refactoring. When making changes, you only need to modify your production code while your tests remain intact. This approach significantly reduces the risk of introducing unintended side effects during refactoring and ensures that your tests accurately reflect the behavior of your code.</p><p>In summary,<strong> </strong>NetMock’s versatility empowers you to adapt your testing setup to different libraries and facilitates refactoring with ease, thereby bolstering the reliability and maintainability of your codebase.</p><p>Finally, I want to express my sincere gratitude to all the readers who have taken the time to explore this article. I hope the insights provided have shed light on the importance of comprehensive testing in the network layer.</p><p>Thank you once again for your attention, and happy testing with NetMock!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=769aeabbb214" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clean-android-dev/introducing-netmock-simplifying-http-request-testing-in-java-android-and-kotlin-multiplatform-769aeabbb214">Introducing NetMock: Simplifying HTTP Request Testing in Java, Android, and Kotlin Multiplatform</a> was originally published in <a href="https://medium.com/clean-android-dev">Clean Android Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The “Real” Clean Architecture in Android: Modularization]]></title>
            <link>https://medium.com/clean-android-dev/the-real-clean-architecture-in-android-modularization-e26940fd0a23?source=rss----55056bc45674---4</link>
            <guid isPermaLink="false">https://medium.com/p/e26940fd0a23</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[modularization]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 14:59:49 GMT</pubDate>
            <atom:updated>2023-04-05T12:33:52.882Z</atom:updated>
            <content:encoded><![CDATA[<h3>The “Real” Modularization in Android</h3><h4>An overview of the principles behind modularization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMo2FbipyXkr6BUOxjNr8Q.png" /><figcaption>Image by author</figcaption></figure><blockquote>“If the SOLID principles tell us how to arrange the bricks into walls and rooms, then the component principles tell us how to arrange the rooms into buildings.” ~ Robert C. Martin, Clean Architecture</blockquote><blockquote>Should you package by layer or by feature? Is there any other approach?</blockquote><blockquote>How can you boost your project’s compilation time?</blockquote><blockquote>How can your engineers work independently in cross-functional teams?</blockquote><p>With this article, I aim to answer these questions by extending <a href="https://medium.com/better-programming/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451">my previous article on SOLID principles.</a></p><pre><strong>Table of Contents</strong><br><br><a href="#898f">Component Cohesion Principles</a><br><a href="#d644">Component Coupling Principles</a><br><a href="#92de">Package Design Solutions</a><br><a href="#ad96">Encapsulation</a><br><a href="#6d12">The Main Component</a></pre><h4>Intro</h4><p>While SOLID principles can validate and detect code smells in a class or an interface, component principles can validate and detect code smells in a component.</p><blockquote>What is a component?</blockquote><p>A component is a group of files (classes, interfaces, files of functions, Android resources, etc.) that are grouped using one of the following strategies:</p><ol><li>Source code level (monolithic structure): in Java/Kotlin, we use packages</li><li>Binary/deployment level: in Java/Kotlin, we use modules that generate “jars” or “aars”</li><li>Service level: this would be a service or a microservice, where the communication happens through network packets</li></ol><p>Normally, you don’t use just one strategy. You mix these strategies according to your needs.</p><p><em>Since we don’t have services in Android, the article will be focused on Java/Kotlin modules.</em></p><h4>What is “good modularization”?</h4><p>A “good modularization” is a components’ structure in which modules are highly cohesive and lowly coupled.</p><blockquote>How can we say that modules are highly cohesive? <br>And how can we say that modules are lowly coupled?</blockquote><p>Modules are highly cohesive when they adhere to component cohesion principles.</p><p>Modules are lowly coupled when they adhere to component coupling principles.</p><h3>Component Cohesion Principles</h3><p><a href="https://medium.com/better-programming/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451">SOLID principles</a> are the foundation of clean architecture and can be adapted at the module level, thus creating a new set of principles (REP, CCP, and CRP).</p><h4>The Common Closure Principle (CCP)</h4><blockquote>“Gather into components those classes that change for the same reasons and at the same times.</blockquote><blockquote>Separate into different components those classes that change at different times and for different reasons.” — All remaining quotes by Robert C. Martin, <a href="https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164">Clean Architecture</a></blockquote><p>The CCP is the evolution of the <a href="https://medium.com/better-programming/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451#8684">SRP</a> at the module level, as I explained in my previous article.</p><p><em>A class should not change for different reasons -&gt; a component should not change for different reasons.</em></p><p>Classes that change for the same reasons should be grouped in a component, and classes that change for different reasons should be moved away from the component.</p><p>Maintainability is more important than reusability: whenever you work on a new feature, or there is a requirement change, you would rather have to touch a single module than many.</p><p>When we have to change only a single module, we are less likely to affect other team members, and we have fewer components to recompile, revalidate, and redeploy.</p><p>It is not realistic to always group every possible change in a single module (unless you work with a monolith 😈), so the goal of the principle is to minimize the number of modules that needs changing.</p><p>Pros: Optimal for maintenance as the impact of change is minimized.<br>Cons: The optimal approach for developing and maintaining the modules might not be optimal for releasing the modules to library users. Also, modules will tend to be bigger to isolate the number of modules to change.</p><h4>The Common Reuse Principle (CRP)</h4><blockquote>“Don’t force users of a component to depend on things they don’t need.”</blockquote><p>The CRP is the evolution of the <a href="https://medium.com/better-programming/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451#0d23">ISP</a> at the module level, as I explained in my previous article.</p><p><em>When interfaces are small, you don’t depend on methods you don’t need -&gt; when modules are small, you don’t depend on files you don’t need.</em></p><p>Classes are seldom reused in isolation. More typically, reusable classes collaborate with other classes that are part of the reusable abstraction. <br>The CRP states that these classes belong together in the same component.</p><p>It also states that classes not reused together should not be placed in the same component.</p><p>By doing so, an update on such classes won’t trigger a recompilation, redeployment, or release of modules that do not use them.</p><p>Pros: Smaller modules, as a module user you are less likely to be affected by changes you don’t care about.</p><p>Cons: More modules that require to be worked on during development.</p><h4>The Reuse/Release Equivalency Principle (REP)</h4><blockquote>“The granule of reuse is the granule of release.”</blockquote><p>The smallest thing you are willing to reuse is the smallest thing you are willing to release.</p><p>This is a very important principle for library devs.</p><p>Whenever you want to make a component available to others, you are required to have a release process, and for your component to not break your library users’ code over time, you are required to have release numbers.</p><p>By doing so, library users won’t have breaking changes unless they upgrade to the newer library versions.</p><p><em>Because all the classes in your module have the same release number, an update of a single class will require a new release of all the classes under the same module.</em></p><p>Sometimes, libraries come as a single library, and sometimes they come as a group of libraries (so you can decide what to import and what to exclude).</p><p>When working with a group of libraries, you may expect that because all these modules are reused together, they should all have the same release number to ensure compatibility.</p><p>Having the same release number means that when you need to update one module, you’ll also need to release all the other modules with the updated version number (even when these have not changed).</p><p>Let’s take <a href="https://github.com/square/retrofit">Retrofit</a> as an example.</p><pre>implementation &#39;com.squareup.retrofit2:retrofit:2.9.0&#39;<br>implementation &#39;com.squareup.retrofit2:converter-moshi:2.9.0&#39;</pre><p>When Retrofit developers add new functionalities to the Retrofit main library, they most likely also need to make the supporting converter libraries compatible with these new integrations, thus bumping the version name of all the library modules.</p><p><em>This might not always be the best approach, in particular when modules of the same group of libraries are not very cohesive.</em></p><p>Let’s now take <a href="https://github.com/firebase/firebase-android-sdk">Firebase</a> as an example.</p><p>Firebase libraries used to have matching release numbers in the past.</p><p>The problem with Firebase is that their set of libraries is very incohesive. <br>Think about the remote config library and the storage library: these two libraries are completely independent of each other and probably worked on by different dev teams.</p><p>A new integration in one of the two should not require the Firebase team to release a new version of the other library without changes.</p><p>What did the Firebase team end up doing?</p><p>They took advantage of Gradle 5.0 support for Maven <a href="https://docs.gradle.org/current/userguide/platforms.html">BoMs</a>, which allows managing different library versions as a single version.</p><p>By doing so, instead of releasing a new version of every single library, they release a new version of the BoM.</p><pre> // BoM<br> implementation platform(&#39;com.google.firebase:firebase-bom:$version&#39;)<br><br> // modules import without version<br> implementation &#39;com.google.firebase:firebase-core&#39;<br> implementation &#39;com.google.firebase:firebase-config&#39;<br> implementation &#39;com.google.firebase:firebase-storage&#39;</pre><p>If it weren’t for BoMs, they would have used <a href="https://developers.google.com/android/guides/setup#list-dependencies">Google Play Services’ approach</a>, aka an endless table of library versions (the least user-friendly).</p><p>Pros: Optimal for reusability, your modules are available to other teams, and the versioning makes new updates easier to manage.</p><p>Cons: It is more complicated to maintain the codebase as now you need to consider the module&#39;s release process.</p><p>Modules will tend to be bigger because by doing so, you can decrease the number of modules that need releasing.</p><h3>The Component Cohesion Tension Triangle</h3><figure><img alt="REP (group for reusers) to CCP (group for maintenance) — too many unneeded releases REP (group for reusers) to CCP (group for maintenance) — too many unneeded releases CCP (group for maintenance) to CRP (split to avoid unneeded recompilations/releases) — hard to reuse CRP (split to avoid unneeded recompilations/releases) to REP (group for reusers) — too many components changed caption: what is your right fit?" src="https://cdn-images-1.medium.com/max/998/1*TPl35E_0Q4Dgty3iLk-dSg.png" /><figcaption>Component Cohesion Tension Diagram</figcaption></figure><p>The diagram shows what happens when you abandon one principle in favor of the other two.</p><p>If it wasn’t clear already, the Component Cohesion Principles, unlike SOLID principles, don’t complement each other and require you to choose what is more important for your project.</p><p>While it is easy to make classes easy to maintain and reuse, the same cannot be said for modules.</p><p>The CCP and the REP are inclusive principles; they tend to make modules bigger, while the CRP is an exclusive principle as it tends to make modules smaller.</p><p>The CRP and the REP are principles focused on reuse. They tend to optimize the modules for those who are using them, while the CCP is focused on maintenance as it tends to optimize modules for those who are developing them.</p><p>It is very unlikely that you’ll manage to balance all three, so you should be prepared to give up or focus less on one of them.</p><p>Usually, a project falls under one of the following categories:</p><ol><li>App: when you are building an app, your main goal is to build things fast and have a project that compiles quickly with minimal unneeded recompilations. <br>If you fall under this category, you should always focus on CCP and CRP.</li><li>Library: when you are building a library, your goal won’t be static. On the contrary, it will change over time.<br>When you start the development of the library, your main focus should be on building the library fast. Then, over time, your focus should shift to how reusable the library is and compromise its maintenance.<br>If you fall under this category, you should focus on the right side of the triangle until your project is mature, then you should move to the left side over time as now you’ll be more and more accountable to your library users.</li></ol><p>Most projects’ modularization fails because engineers prioritize the wrong principle for their projects’ nature.</p><p>Other projects’ modularization fails because the component structure is static instead of evolving as requirements change.</p><h4>References</h4><p>* Clean Architecture, Chapter 13 (Component Cohesion)</p><h3>Components Coupling Principles</h3><p>We discussed the theory about how modules should be according to the Cohesion Principles.</p><p>We now need to discuss how the relationships between these modules should be.</p><h4>The Acyclic Dependencies Principle (ADP)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*iS63eL0ED-nQQIpj5O-iLw.png" /><figcaption>Example of Cyclic Dependency Principle</figcaption></figure><blockquote>“Allow no cycles in the components dependency graph.”</blockquote><p>If A depends on B, then B should not depend on A.</p><p>This is not only true for dependencies but also for transitive dependencies:<br>If A depends on B and B depends on C, then C should not depend on A either.</p><p>Some compilers allow for cycles in modules, and others try to ensure this doesn’t happen.</p><p>Regardless of the compiler or language used, you, as a developer, need to know how to break the dependency cycle as soon as you detect it.</p><p>A dependency cycle can be broken in two ways:</p><ol><li>Extracting the classes to reuse in a new module.</li><li>Using the <a href="https://medium.com/better-programming/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451#0793">Dependency Inversion Principle</a> (DIP, yes, SOLID again 😈) to “invert” the dependency.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-owR-stJXhd0-lyY4HbKYw.png" /></figure><p>Solution 1 is ideal when many modules require the shared logic and when a lot needs sharing.</p><p>Solution 2 is ideal when only a single module requires the shared logic and when there is not much to share.</p><h4>The Stable Dependencies Principle (SDP)</h4><blockquote>“Depend in the direction of stability.”</blockquote><blockquote>What would you make your module rather depend on? <br>A module that changes often or a module that never changes?</blockquote><p>We want our modules to depend on modules that never change.</p><p>Whenever a dependency in our module changes, our module needs to recompile, and we may have to deal with breaking changes.</p><blockquote>Which modules are stable?</blockquote><p>Stable modules are the ones that are hard to change.</p><p>Think about the Kotlin String class, how likely is the Kotlin team to change such a class? If they do change it, how many breaking changes would they have in the whole Kotlin language? That is a class that no developer sane of mind would ever change.</p><p>The ideal scenario for you is that your module depends on something as stable as that.</p><p>Unfortunately, we live in the real world, not the ideal one.</p><p>Most modules we use are not 100% stable, which is not necessarily bad.</p><p>A module that cannot change cannot also ever improve.</p><p>Not only that, if modules cannot change at all, we can never add new features as we can’t change the code.</p><blockquote>So, how do we redefine stability? <br>When is a module stable enough?</blockquote><p>A module is stable when it has few dependencies and many dependent modules, thus making it a responsible module.</p><p>If you look at your components dependency graph, you should see at the bottom the more stable (responsible) modules and at the top the more unstable (dependent) modules.</p><p>Because in your project, you’ll end up having both stable and unstable modules, the golden rule is that a module should depend on modules that are more stable than itself.</p><h4>The Stable Abstractions Principle (SAP)</h4><blockquote>“A component should be as abstract as it is stable.”</blockquote><p>The SDP defines that stable modules are hard to “change.”<br>This implies that adding new functionalities to stable modules is hard as you cannot easily modify the existing code…</p><p>But what about “extension”? Can I extend stable modules?</p><p>The <a href="https://medium.com/better-programming/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451#968a">Open-Closed Principle</a> (OCP, yes SOLID again 😈) gives us classes that are open to extension and closed to modification.</p><blockquote>How do I port this extensibility at the module level?</blockquote><p><em>A module is easy to extend when it is abstract. Hence it is composed mainly of interfaces and abstract classes.</em></p><p>When a module is full of interfaces, whenever you need to add something new, all you need to do is to provide a new concrete implementation to one of the abstractions.</p><p>This will prevent you from touching the stable modules’ source code just to adapt something for your module and potentially break the other dependent modules.</p><p>While stable modules should be more abstract than concrete to allow more flexibility, unstable modules should be more concrete than abstract to facilitate code changes.</p><p>Although you want stable modules to be very abstract to allow flexibility, a module that is 100% abstract is a module that is useless as there is no actual logic that you can reuse.</p><p>And obviously, a stable module that is 100% concrete is a module that is very painful to change.</p><p>The golden rule here is that a module should depend on the abstractions of its dependencies rather than the concretion.</p><p>You should be getting this for free if your classes adhere to the Dependency Inversion Principle.</p><h4>References</h4><p>* Clean Architecture, Chapter 14 (Component Coupling)</p><h3>Package Design Solutions</h3><p>If you got bored reading the above six principles, worry not, as now I’m going to get into the fun part.</p><p>Now that we know how to achieve high cohesion and low coupling, it is time to discuss which approaches work and which don’t.</p><p>Because app developers are the ones with the most trouble modularizing and because library developers don’t usually have to deal with a lot of modules, I will only focus on how to modularize an app (or this article will become even longer!).</p><h4>Package by layer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*aPpWYND8Djpxk-ICigLPIA.png" /><figcaption>Package by Layer Diagram</figcaption></figure><blockquote>In package by layer, you split the codebase into three broad modules, one for each layer. — Author</blockquote><p>This approach is quite easy to do but violates most of the abovementioned principles.</p><p>You’ll most likely have to modify all the modules whenever you work on a new feature<strong>.</strong></p><p>By doing so, you may end up breaking other features&#39; code, stepping on your teammates&#39; feet, and recompiling the whole dependency graph at any new iteration.</p><p>Modules will also be very big, as they will contain the layer logic of all the features in your app.</p><blockquote>Why is this approach so popular?</blockquote><p>If you’ve been reading Clean Architecture articles since the beginning of the hype, you would have noticed how most writers, when discussing modularization, constantly pushed for the Package by Layer approach, thinking that layers (Presentation-Domain-Data) should dictate the modules’ structure of their project.</p><p><em>If these writers had read the </em><a href="https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164"><em>Clean Architecture book</em></a><em> in the first place, they would have known that this approach was the one most advertised against.</em></p><p>The reason why this bad advice makes me upset is not just because devs used the wrong modularization approach as a consequence but also because it lead companies astray as they separated development teams by these layers.</p><blockquote>What if I want to swap a database for another database?<br>Isn’t it better to have to change a single module?</blockquote><p>I’ve heard this many times in support of this packaging approach, and the short answer is no, it is not better.</p><p>Firstly, it is not part of your day-to-day work to change your database. This may happen over the years but definitely not on a weekly basis.</p><p>Not to mention that this is very rare work for mobile developers (some unlucky devs had to change Sqlite with Realm and then back to Sqlite with Room, but this happened over many years).</p><p>Secondly, it is a bad idea to swap a database in a single blow. It is much better to migrate feature by feature your data to the new database so that you can gradually release your migration and limit the number of potential bugs that may come out.</p><h4>Package by feature</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCkDrQwMZ6ikfqVMmD4aEw.png" /><figcaption>Package by Feature Diagram</figcaption></figure><blockquote>In package by feature, you split the codebase into feature modules, one for each feature. — Author</blockquote><p>This approach brings many advantages, and it has been the most recommended approach for decades:</p><ul><li>When working on a feature, you change only one module, which is optimal for maintenance.</li><li>When you open your project, you know exactly what your project does as it screams at you what it is about (Screaming Architecture).</li><li>Each cross-functional team can work independently on a feature without stepping on another team’s feet.</li><li>Independent teams also mean independent modules, so you can get the most out of Gradle parallel compilation, which will decrease your overall compilation time other than requiring you to recompile only that single feature that changed.</li><li>You don’t lose layers, as layers can easily be implemented as packages inside the feature module.</li></ul><blockquote>So this is how I should modularize my app, right?</blockquote><p>Not really. This approach looks optimal for maintenance but has no reusability at all!</p><p>The cons of this approach are very expensive:</p><ul><li>If your feature module needs to reuse some code from another feature module, you’ll need to create a dependency on a very unstable module which would break the SDP, also because features will contain a lot of UI code, and UI code is very concrete; you’ll also break the SAP.</li><li>Feature modules contain presentation, domain, and data logic which results in big modules (CRP violation) containing code that often changes (UI) along with code that rarely changes (business logic).</li><li>Features depending on features often create big “Core Features” modules that revert your project gradually to a monolith.</li></ul><p>Package by feature works well in non-UI-heavy projects like backend or old frontend applications.</p><p>In a backend project, the controllers&#39; code (presentation layer) is usually thin and matches the use cases or services of the domain layer.</p><p>The backend can also rely on services (or microservices) rather than modules, so communication within the components does not require a service to know the internal structure of another service. Instead, the public API’s contract makes the whole components’ structure independent at compilation time.</p><p>In mobile or web frontend projects, “screens” are clusters of features.</p><p>Think of an e-commerce product detail page that allows you to add the product to the cart and the user’s wishlist.</p><p>These same actions can be performed on a product list page or the cart page, or the wishlist page.</p><blockquote>How can you split by feature in this case? <br>Are you going to group everything under a single feature?<br>Are you going to create a big shared feature module for sharing common code?<br>Are you going to duplicate a lot of your code so you can have independent modules?</blockquote><p>Any of these solutions are suboptimal and are not the answer to the problem.</p><p>Package by feature is not the right fit for UI-heavy projects, so don’t use it on professional Android projects (the same applies to iOS and Web).</p><h4>Package by component</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hb7f_lBmfRxqztUPkDm-Yg.png" /><figcaption>Package by Component Diagram of the PDP scenario</figcaption></figure><blockquote>In package by component, you split the codebase into UI modules and component modules (domain + data layer of a feature). — Author</blockquote><blockquote>Who should guide the modules of your app?</blockquote><p>Certainly not the UI logic as we saw in package by feature.<br>Use cases should guide your modularization just like they guide your development.</p><p>Use cases tell us what the app does and rarely change. They are also the only architectural component visible by the presentation layer.</p><p>The data layer exists only to support the domain layer. Hence a modification of the domain layer will often require a modification in the data layer to be compatible with the updated repository interface.</p><p>By splitting the codebase vertically and horizontally using use cases, we can achieve the reusability we didn’t have in package by feature.</p><p>Going back to the product detail page example (check the diagram). If I have a Cart Component module, a Wishlist Component module, and a PDP UI module, I can now reuse both cart and wishlist codes without depending on any UI detail for showing the cart or the wishlist screens.</p><p>And if the product team decides to introduce the add-to-cart functionality in the wishlist screen, we can just add the Cart Component module as a dependency to the Wishlist UI module and link it.</p><p>Not only do I now have a more reusable approach, but I also have separated classes that often change from classes that rarely change, thus minimizing the number of recompilations.</p><p>Because components are still independent, we can compile modules in parallel, thus improving the overall compilation time.</p><blockquote>What if I need to share code between component modules or UI modules?</blockquote><p>You will most likely encounter that problem if you work on a professional project, and the solution is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMo2FbipyXkr6BUOxjNr8Q.png" /></figure><p>If what you need to share is a feature’s specific code, you can extract what you need to reuse in a Shared Component module or a Shared UI module.</p><p>If what you need to share is generic code, let’s say code for performing a network request or a design system, you would follow the same approach you always use with third-party libraries (like Retrofit, Dagger…) with the difference that this module won’t be public but private for your project (until you decide to share it with the public).</p><blockquote>What if I need to navigate from the PDP to the Cart screen or the Wishlist screen?</blockquote><p>DIP is your friend. If you need to navigate through modules, all you need to do is to have an interface, let’s say:</p><pre>interface PDPNavigator {<br>    // you can adapt for fragments, navigation component, compose....<br>    fun navigateToCart(activity: Activity) <br>    fun navigateToWishlist(activity: Activity)<br>}</pre><p>Which will be implemented by a class in the Main (app) module:</p><pre>class AppNavigator: PDPNavigator, WishlistNavigator, CartNavigator.... {<br>    override fun navigateToCart(activity: Activity) {<br>        //...<br>    }<br><br>    override fun navigateToWishlist(activity: Activity) {<br>        //...<br>    }<br><br>}</pre><p><em>You don’t need to do this for screens inside the same module.</em></p><h4>References</h4><p>* Clean Architecture, Chapter 34 (The Missing Chapter) by Simon Brown<br>* <a href="https://dzone.com/articles/package-component-and">Simon Brown’s original post</a><br>* <a href="https://martinfowler.com/bliki/PresentationDomainDataLayering.html">Martin Fowler’s referenced article</a> in The Missing Chapter</p><h3>Encapsulation</h3><p>If there is one thing developers never do well, it is working with encapsulation.</p><p>Open one of your module&#39;s code. If every single class or interface is public, you are doing encapsulation wrong.</p><p>“Public” is a modifier that should be used only for those classes or interfaces meant to be used outside the module. Everything else should be “internal.”</p><p>If every class or interface is “public” inside a module, a developer might be misled into thinking that everything needs to be reused by other modules and will be afraid to touch the code.</p><p>More disciplined developers, to gain confidence, would use the IDE find usages tool to check that these classes are used outside of the module. <br><em>If only there were a modifier that could have avoided these extra steps and made devs more productive.</em></p><p>Module encapsulation is not just about confidence but also about future improvements.</p><p>By knowing what is public and what is not, you may find a way to decouple a module from a dependency in cases where you only use it because of a small number of classes/interfaces.</p><p>It doesn’t end with public/internal modifiers.</p><p>Another encapsulation problem you may find is related to the exposure of transitive dependencies.</p><p>This happens when one of your dependencies is leaking a transitive dependency by using api instead of implementation.</p><p>Ideally, you always use implementation, as this avoids the leaking of dependencies and extra compilation time.</p><h4>Encapsulation with package by component</h4><p>In Package by Component, it is quite simple to work with encapsulation as the number of files that can be public is just a few.</p><ul><li>In component modules: the only files that should be public are the use-case interfaces and the models that need to be used outside the module.<br>Use case implementations, repository interfaces, repository implementations, mappers interfaces, mappers implementations, DTOs, etc., should always be internal, as the presentation layer should not access them.<br>Component modules are stable (SDP adherence), containing business rules and use cases. By making only use case interfaces public, we also adhere to the SAP since now other modules will only depend on the abstraction of this module.</li><li>In UI modules: the only files that should be public are the screens (fragments, activities, compose screen Composables) and the external navigators.<br>UI modules are unstable since UI is very volatile; hence, we should try not to add them as dependencies and import them only in the Main (app) module to connect the navigation.</li></ul><p>If you are working with Dagger, the modules providing these dependencies should also be made internal.</p><pre>// Dagger module for a Wishlist Component Module<br>@Module<br>@InstallIn(SingletonComponent::class) // Or any other scope<br>internal object WishlistComponentModule {<br><br>    @Provides<br>    fun provideAddToWishlistUseCase(<br>        addToWishlistUseCaseImpl: AddToWishlistUseCaseImpl<br>    ): AddToWishlistUseCase = addToWishlistUseCaseImpl<br><br>    @Provides<br>    fun provideGetWishlistUseCase(<br>        getWishlistUseCaseImpl: GetWishlistUseCaseImpl<br>    ): GetWishlistUseCase = getWishlistUseCaseImpl<br><br>    @Provides<br>    fun provideWishlistRepository(<br>        wishlistRepositoryImpl: WishlistRepositoryImpl<br>    ): WishlistRepository = wishlistRepositoryImpl<br><br>    //...<br><br>}<br><br>// Dagger module for a Wishlist UI Module<br>@Module<br>@InstallIn(ActivityComponent::class) // Or any other scope<br>internal object WishlistUIModule {<br><br>    @Provides<br>    fun provideSomeDependency(<br>        someDependencyImpl: SomeDependencyImpl<br>    ): SomeDependency = someDependencyImpl<br><br>    //...<br><br>}</pre><p>If you are using manual injection, you can make your Dependency Containers public and make sure that only public files are returned from a public method (you will get a compilation error otherwise).</p><h4>References</h4><p>* <a href="https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_recognizing_dependencies">Gradle API vs implementation documentation</a></p><h3>The Main Component</h3><p>In every system, at least one component creates, coordinates, and oversees the others.</p><p>The Main Component (app module in Android) is the ultimate detail, it contains the lowest-level policies and is the system’s entry point.<br>It is a dirty low-level module in the outermost circle of the clean architecture. It loads everything up for the high-level system and then hands control over to it.</p><p>The following should be placed in this area:</p><ul><li>all the “glue code” required to connect the modules</li><li>all the injection code that cannot be internal in the modules</li><li>all the navigation code that cannot be internal in the modules</li><li>your flavors configurations</li><li>all the initialization required by the frameworks</li></ul><h4>References</h4><p>* Clean Architecture, Chapter 26 (The Main Component)</p><h3>Last Notes</h3><p>I know that the article was long and that principles are never fun, especially when they require you to know other principles beforehand.<br>If I had to write this article with only the solutions, these would have just been an opinion to the reader rather than the product of the component principles.</p><p>Despite this being a long read, a lot has been left out, like Domain-Driven Design concepts for decoupling the contexts or Package by Ports and Adapters (another suboptimal package design solution).</p><p>I hope the article was still enjoyable despite the theoretical parts and you have learned new tools to modularize your projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e26940fd0a23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clean-android-dev/the-real-clean-architecture-in-android-modularization-e26940fd0a23">The “Real” Clean Architecture in Android: Modularization</a> was originally published in <a href="https://medium.com/clean-android-dev">Clean Android Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Avoid Use Cases Boilerplate in Android]]></title>
            <link>https://medium.com/clean-android-dev/how-to-avoid-use-cases-boilerplate-in-android-d0c9aa27ef27?source=rss----55056bc45674---4</link>
            <guid isPermaLink="false">https://medium.com/p/d0c9aa27ef27</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 14:58:53 GMT</pubDate>
            <atom:updated>2022-08-29T09:08:18.870Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring four different approaches</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEq_Om0oEILtB31526pCxw.png" /></figure><p>Since the dawn of layered architectures, <a href="https://proandroiddev.com/why-you-need-use-cases-interactors-142e8a6fe576">Use Cases</a> have had a controversial reputation.</p><p>While on the one side, they help you adhere to <a href="https://betterprogramming.pub/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451">S.O.L.I.D.</a> principles and improve your code readability; on the other, they are sometimes “useless” (the only thing they do is call a repository method).</p><p>Because of that, the industry converged on the following four approaches (to be used only when use cases are just a call to a repository method):</p><h3>Approach 1: Skip the Use Case</h3><p>With this approach, you have a Use Case only if it is doing something, while if it is “useless,” you call the repository directly.</p><p>Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f1a4018d350260aba4b80d236901850/href">https://medium.com/media/1f1a4018d350260aba4b80d236901850/href</a></iframe><h4>Pros</h4><ol><li>Less code to write</li><li>No redundancy: a change to the repository method will not require a Use Case change.</li></ol><h4>Cons</h4><ol><li>Inconsistency</li><li>Scalability: if the repository method requires extra parameters that are not coming from the presentation layer, all the VMs using it will need to be updated, and this, when it comes to core repositories, might be a big refactor.</li><li>ISP violation: repositories usually have many methods. Hence when you have a repository as a collaborator, your class will require a recompilation every time a method you are not using gets added, removed, or changed.</li><li>Cheating: my experience with this approach is that lazy engineers will find excuses not ever to have a Use Case and therefore overload either ViewModels or Repositories with business logic.</li></ol><h3>Approach 2: Keep the Use Case</h3><p>With this approach, you don’t care whether your use case is doing something or not since you are always going to have a use case:</p><p>Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5e9c81d50c1c48beda850ffc7196475/href">https://medium.com/media/c5e9c81d50c1c48beda850ffc7196475/href</a></iframe><h4>Pros</h4><ol><li>Consistency.</li><li>Scalability: if the repository method requires extra parameters not coming from the presentation layer, all the VMs using the use case won’t need to be updated because they are protected by the use case interface.</li><li>ISP adherence.</li></ol><h4>Cons</h4><ol><li>More code to write.</li><li>Redundancy: if your repository method signature changes for getting different parameters from the presentation layer, you will have to update the use case class, tests, and interface.</li></ol><blockquote>NB: when I say “parameters coming from the presentation layer” I don’t mean presentation models passed to the use case, I mean input coming from the presentation layer that is mapped into domain models.</blockquote><p>In pure OOP, these two approaches are the only options you have but when you add functional programming to the mixture, things change for the better.</p><h3>Approach 3: Functional Use Cases With Type Aliases</h3><p>A while ago, I came out with the <a href="https://medium.com/swlh/functional-use-cases-f896f92e768f">Functional Use Case approach</a>, where you have a function or a type alias instead of having an interface for the Use Case.</p><p>Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbabfd7539fb170036c51d0d580d5454/href">https://medium.com/media/bbabfd7539fb170036c51d0d580d5454/href</a></iframe><p>Because you don’t have an interface but a higher order function, you can inject whatever you want; therefore, swapping a repository method for a use case class is just a matter of updating the DI layer.</p><p>Overall, this was a good approach since it removes boilerplate, but given that most Android projects are heavily influenced by DI frameworks like Koin and Dagger, which require types to work, this approach came with an additional complexity for the DI layer.</p><p>In Dagger, if you have multiple suspend () -&gt; Answer&lt;List&lt;SomeModel&gt;, String&gt; you won’t be able to do the following:</p><pre>@Provides<br>@Singleton<br>fun provideGetSomeModelUseCase(<br>    someModelRepository: SomeModelRepository<br>): GetSomeModelUseCase {<br>    return someModelRepository::getSomeModels<br>}</pre><p>Unless for each specific function, you don’t add the ugly @Named hack.</p><p>In Koin, you won’t be able to do the following:</p><pre>single&lt;GetSomeModelUseCase&gt; {<br>    get&lt;SomeModelRepository&gt;()::getSomeModels<br>}</pre><h4>Pros</h4><ol><li>Less code to write.</li><li>No redundancy: a change to the repository method will not require a Use Case change.</li><li>Consistency.</li><li>Scalability: if the repository method requires extra parameters not coming from the presentation layer, all the VMs using the use case won’t need to be updated because they are protected by the use case interface.</li><li>ISP adherence.</li></ol><h4>Cons</h4><ol><li>Doesn’t work well with DI frameworks</li></ol><p>This was the best approach I could come up with back then, and as Howard Stark once said:</p><blockquote>“I’m limited by the technology of my time, but one day you’ll figure this out. And when you do, you will change the world. What is and always will be my greatest creation… is you.”</blockquote><h3>[FINAL] Approach 4: Functional Use Cases With Functional Interfaces</h3><p>After years, JetBrains answered my prayers and introduced <a href="https://kotlinlang.org/docs/fun-interfaces.html">Functional Interfaces (SAM)</a>.</p><p>Thanks to this Kotlin update, functions can be injected as Functional Interfaces, unlike type aliases, are “real types.”</p><p>Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ede858c8bd4e3e200a673918b966d3f/href">https://medium.com/media/4ede858c8bd4e3e200a673918b966d3f/href</a></iframe><p>The Dagger provides a function that can be fixed this way:</p><pre>@Provides<br>@Singleton<br>fun provideGetSomeModelUseCase(<br>    someModelRepository: SomeModelRepository<br>): GetSomeModelUseCase {<br>    return GetSomeModelUseCase(someModelRepository::getSomeModels)<br>}</pre><p>And the Koin provides function as well:</p><pre>single&lt;GetSomeModelUseCase&gt; {<br>    GetSomeModelUseCase(get&lt;SomeModelRepository&gt;()::getSomeModels)<br>}</pre><h4>Pros</h4><ol><li>Less code to write.</li><li>No redundancy: a change to the repository method will not require a Use Case change.</li><li>Consistency.</li><li>Scalability: if the repository method requires extra parameters that are not coming from the presentation layer, all the VMs using the use case won’t need to be updated because they are protected by the use case interface.</li><li>ISP adherence.</li><li>Work well with all DI frameworks</li></ol><h4>Cons: N/A</h4><p>We finally have a solution with no cons.</p><h3>Summary</h3><p>Use cases are a crucial part of clean architecture, and developers always had a love/hate relationship with them.</p><p>I hope that by applying this solution, you will love them more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0c9aa27ef27" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clean-android-dev/how-to-avoid-use-cases-boilerplate-in-android-d0c9aa27ef27">How To Avoid Use Cases Boilerplate in Android</a> was originally published in <a href="https://medium.com/clean-android-dev">Clean Android Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The “Real” Clean Architecture in Android: S.O.L.I.D.]]></title>
            <link>https://medium.com/clean-android-dev/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451?source=rss----55056bc45674---4</link>
            <guid isPermaLink="false">https://medium.com/p/6a661b103451</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 14:57:13 GMT</pubDate>
            <atom:updated>2023-06-20T14:03:06.945Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>If you think good architecture is expensive, try bad architecture. ~ </em>Brian Foote and Joseph Yoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b69nu6FaKG4ofQGPpAnc4A.png" /><figcaption>Image by author</figcaption></figure><p>Clean Architecture has been probably the hottest topic in the Android community in the past few years and this trend doesn’t seem to go away (thankfully).</p><p>This series is based on the following books and documentation:</p><ol><li><a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?crid=9GR6QM8XY4T9&amp;keywords=the+clean+code&amp;qid=1657047914&amp;sprefix=the+clean+code%2Caps%2C186&amp;sr=8-1">Clean Code by Robert C. Martin</a></li><li><a href="https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164/ref=sr_1_1?keywords=clean+architecture&amp;qid=1657047966&amp;sprefix=clean+ar%2Caps%2C180&amp;sr=8-1">Clean Architecture by Robert C. Martin</a></li><li><a href="https://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420/ref=sr_1_1?keywords=pattern+of+enterprise+application+architecture&amp;qid=1657048013&amp;sprefix=pattern+of+enter%2Caps%2C193&amp;sr=8-1">Patterns of Enterprise Application Architecture by Martin Fowler</a></li><li><a href="https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215/ref=sr_1_1?keywords=domain+driven+design&amp;qid=1657048072&amp;sprefix=Domain+dri%2Caps%2C182&amp;sr=8-1">Domain-Driven Design by Eric Evans</a></li><li><a href="https://alistair.cockburn.us/hexagonal-architecture/">Hexagonal Architecture by Alistair Cockburn</a></li><li><a href="https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/">Onion Architecture by Jeffrey Palermo</a></li></ol><p>All these authors agree on most things but sometimes they tend to take a different route and <em>so do I</em>! <br>Therefore this series won’t be a summary of the source material, but an opinionated approach to Clean Architecture based on the preference of the majority of experts in the field and mine.</p><p>PS: In this article, I’m not going to say <strong>what you want to hear</strong> but <strong>what you need to hear.</strong></p><h3>What is Clean Architecture?</h3><p>To start, let’s say what CA is not:</p><ol><li>A template to follow</li><li>An unnecessary boilerplate that slows you down (unless you do it wrong)</li><li>A new trendy architecture that works only on Android (looking at you iOS, Web, and Backend guys)</li></ol><blockquote><em>So what is Clean Architecture?</em></blockquote><p>The short answer is:</p><blockquote>Clean Architecture is the outcome of the S.O.L.I.D. principles.</blockquote><p><em>Hence if you don’t follow them you are not doing CA, you are just following a template that will never make sense.</em></p><p>My rant against other articles is that they rarely mention S.O.L.I.D principles and they focus only on the separation of concerns part (SRP), and because of that, they leave the reader with more doubts than they had before reading the article: <em>why does that use case have a single method? why do I need that interface there? why do I need a different object and mappers?</em></p><p>The answer to all these questions is in the S.O.L.I.D. principles so in part 1 I will focus on the theory and I will show how each principle shapes Clean Architecture, then I will deep dive into each component in the following articles.</p><h3>S.O.L.I.D.</h3><p>What you need to realize is that S.O.L.I.D. principles are not just a myth or a bullet point you need to put on your CV.</p><p><strong><em>They are the benchmark to determine how clean your code is.</em></strong></p><p>You don’t know if you have the right design? <em>Check if your code adheres to S.O.L.I.D.</em> just like a doctor would check your blood test, if something is wrong your blood test will tell, the same is for S.O.L.I.D. and your code.</p><p>Now, just because a principle has been violated, it doesn’t mean you are going to have issues but if you have issues, bugs or you are less productive you are most likely breaking one or more S.O.L.I.D. principles.</p><p><em>Look at S.O.L.I.D. principles as common-sense disciplines that can help you stay out of trouble, you may not have to use them always but </em><strong><em>you better know them!</em></strong></p><h3>Liskov Substitution Principle</h3><blockquote>Derived classes must be substitutable for their base classes.</blockquote><p>Inheritance is the tightest coupling you can have, <em>bad usage of it leads to highly-coupled and lowly-cohesive code</em>.</p><p>Most inexperienced engineers use inheritance as the primary way to achieve reusability but this often makes maintenance almost impossible to achieve (and just so you know, repeating code is much better than coupling code, maintenance &gt; reusability).</p><p>Because this used to be very common in the early days of Object-Oriented Programming, even among senior developers, <strong>the LSP was the main principle used to regulate inheritance</strong>.</p><p>Let’s have a look at this over-simplistic example (which is not the usual square/rectangle example you’ll see around) where the LSP is violated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cdb1014cdc22dba4b89fc0d584d7dc1/href">https://medium.com/media/0cdb1014cdc22dba4b89fc0d584d7dc1/href</a></iframe><p>Before you wonder, no the LSP is not violated because Android Developers are underpaid (although it would make a good argument 😈).</p><p>In this scenario, the developer decided to make CTO a subclass of Employee for reusing the getSalary method and because of that now the app could crash if the method getLineManager is called on a CTO object.</p><p>I know for certain that 99% of you wouldn’t have made this mistake because you know that a CTO is a <em>chief</em> and not an <em>employee</em> but not always relationships are clear in the codebase.<br>In fact, I bet that you have seen many projects with massive BaseActivity, BaseFragment , BaseViewModel…. classes, that is another clear example of LSP violation.</p><blockquote>So it is fine to use inheritance as far as I don’t break the LSP?</blockquote><p>Instead of using inheritance and then switching to another approach if LSP is violated, <strong><em>you should change your way of thinking and default to composition</em></strong>.</p><p>99% of the things you want to do with inheritance can be done with composition so you should always <strong><em>favor</em> <em>composition over inheritance</em></strong>.<br>If by any chance composition cannot be used, even with the help of any of the <strong>G.o.F. design patterns, </strong>then you can use inheritance (by making sure you adhere to the LSP!).</p><blockquote>What are the most common scenarios in which inheritance is fine to use?</blockquote><p>There are a couple of scenarios where inheritance (IS-A relationship) is fine to use instead of composition (HAS-A relationship), or maybe it isn’t but you are forced to use it, for example:</p><ol><li>When the framework you are using requires you to use it (extending Activities, Fragments, ViewModels…)</li><li>When doing data modeling (Animal -&gt; Mammals…)</li></ol><p>Excluding models and frameworks, <em>usually</em>, architectural components should not rely on inheritance, hence any architecture relying on inheritance is far from being good and clean.</p><h4>Testing</h4><p>Testing inheritance is always painful and requires more effort than testing composition.</p><p>When implementing a new subclass you not only have to test the new public methods added and the ones that you are overriding from the parent class, but <em>you also have to test all the other methods of the parent class that you are not overriding!</em></p><p><em>After all, you don’t want changes to the parent class to break your subclass behavior, don’t you?</em></p><p><em>Testing composition instead is a piece of cake since your tests won’t care about how the collaborator works, they will only care about your collaborator’s contract which can easily be mocked/stubbed/faked… if required.</em></p><p><em>References:<br></em><strong><em>* </em></strong><em>Clean Architecture, Chapter 9 </em>(<strong>LSP</strong>)<em><br>* </em><a href="https://www.youtube.com/watch?v=-Z-17h3jG0A&amp;ab_channel=TuringAwardeeClips"><em>Origin of LSP</em></a></p><h3><strong>S</strong>ingle Responsibility Principle</h3><blockquote>A class should do one, and only one, thing.</blockquote><p>Hmmm… you meant <em>“A </em><strong><em>function</em></strong><em> should do one, and only one, thing?”. <br></em><strong>The wrong principle</strong>, try again.</p><blockquote>A class should have one, and only one, reason to change.</blockquote><p>Better, but maybe rephrase it in a way that explains what that <em>“reason to change”</em> is…</p><blockquote><em>A class should be responsible to one, and only one, actor (group of users or stakeholders).</em></blockquote><p>Now we are talking!<br>I’m using the term <em>“class”</em> because we work in the Java-Kotlin realm, a more generic description is a “<em>module (not a java module) or a source file that contains a cohesive set of functions and data structures</em>”.</p><p><em>“Cohesion”</em> is the keyword in the SRP: the methods of the class must be cohesive, if they are not you should move those methods to another class.</p><p>Who are the actors? There are actually many, and therefore there are going to be many classes. <em>“Logging in”</em> and <em>“Making a purchase”</em> will most likely interest different actors, the <em>onboarding team</em> and the <em>sales team</em> for example. So putting them in the same class would be a violation.</p><p>To top that, the <em>“Logging in”</em> feature will interest not only a PO but also the UI/UX Designers that defined how the user interaction is performed and the BE team that provided you the REST API (plus other actors that might be involved).</p><p>These actors, even if all involved in the same feature will want to be independent of each other as much as possible and will not want to be affected by other actors (UI changes shouldn’t break your API code, API changes shouldn’t break your UI code, both UI changes and API changes shouldn’t break your business logic code).</p><blockquote>Conway’s law: The best structure for a software system is heavily influenced by the social structure of the organization that uses it so that each software module has one, and only one, reason to change.</blockquote><p>This brings in the concept of vertical and horizontal slicing: <strong>features </strong>(login, search, purchase…)<strong> </strong>and <strong>layers </strong>(presentation, domain, data…..).</p><p><em>A feature set per cross-functional team.</em><br><em>A layer for each actor of that cross-functional team.</em></p><p>I will elaborate more on vertical and horizontal slicing in the next articles.</p><h4>From SRP to CCP</h4><p>At the <strong>component level,</strong> the<strong> SRP </strong>becomes the <strong>Common Closure Principle (CCP) </strong>which can be phrased in the following way:</p><blockquote><em>Gather into components those classes that change for the same reasons and at the same times.</em></blockquote><blockquote><em>Separate into different components those classes that change at different times and for different reasons</em>.</blockquote><p>The<strong> CCP</strong> is one of the most important principles to follow for having a rock-SOLID <strong>modularization</strong> (another topic I’ll cover in the following articles).</p><p>By only applying the SRP this is how the architecture of the system would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*ce3NgapFzBamtg1Xqt_H3w.png" /><figcaption>Outcome of SRP</figcaption></figure><p>Again, I will explain each component in the following articles.</p><p><em>References:<br></em><strong><em>* </em></strong><em>Clean Architecture, Chapter 7 (</em><strong><em>SRP</em></strong><em>)<br></em><strong><em>* </em></strong><em>Clean Architecture, Chapter 13 (</em><strong><em>CCP</em></strong><em>)<br>* Patterns of Enterprise Application Architecture, Chapter 1</em></p><h3>Dependency Inversion Principle</h3><blockquote>The most flexible systems are those in which source code dependencies refer only to abstractions, not to concretions.</blockquote><p>This is the easiest principle to follow and yet it is the one that has been more brutally violated by developers.</p><p>Somehow developers think that you should have an interface <em>“only in the case of multiple implementations”</em>.<br><strong>This couldn’t be more wrong.</strong></p><p>Any modern Software Architecture worth its name (Hexagonal, Onion, Clean) heavily relies on the DIP.<br><strong><em>We do not want our high-level business rules to depend upon low-level details.<br></em>We want the isolation of high-level abstractions from low-level details.</strong></p><p>Many developers struggle to understand the problem of isolation because they are not aware of how the compiler works, of transitive dependencies or <em>that they start writing code from the wrong class (more on this in the next article).</em></p><p>Let’s use the diagram from the previous chapter (SRP) as an example, where all the arrows point in the same direction:</p><pre>View -&gt; ViewModel -&gt; Interactor -&gt; Repository -&gt; Data Store...</pre><p>The class ViewModelwill have an import for the Interactor .<br>The class Interactor will have an import for the Repository …. and so on.</p><p>What many developers don’t know is that the ViewModel also imports the Repository and the DataStore <strong><em>transitively</em></strong>.<br>Any change to the Data Store will trigger the recompilation of the Repository which will cause the recompilation of the Interactor and the ViewModel and so on.. up to the first class of the <strong>Flow of Control</strong>.</p><p>A good Architecture is supposed to isolate changes, not propagate them everywhere.</p><p>On top of that not only does the arrows’ direction dictates the compilation but it also dictates the first class the developer is going to write, the Data Source in this case, which as we will see in the next articles is the wrong class to start implementing.</p><p>If we apply the DIP principle to the diagram of the previous chapter, this is how it will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*ySw5cRfql7kUhMYEiDADhg.png" /><figcaption>The outcome of SRP + DIP</figcaption></figure><h4>Testing</h4><p><strong><em>Testability</em></strong> is also heavily affected by this principle.<br>Once you have an interface, creating a test double becomes a mainstream job.</p><blockquote>But I use Mockito, I don’t need interfaces for testing…</blockquote><p>Yes I know, you can still “mock” the behavior of the collaborator by using a mocking framework that uses <em>reflection</em> under the hood.<br>But I also know that Mocking frameworks <em>make tests slower</em>. In fact, on my machine, every time I run a test class, Mockito adds an extra 5–10 seconds to the execution time, and this for a TDDer means waiting 5–10 extra seconds for each TDD cycle (which is still faster than not doing TDD at all btw).</p><p><em>PS: the 5–10 extra seconds become a minor problem when you run the tests on your CI since this is the time that Mockito takes to start for each module (</em><a href="https://github.com/mockk/mockk/issues/13"><em>The same thing will happen with Mockk</em></a><em> in case you are thinking that by switching framework you would solve the problem).</em></p><p>The last advantage of creating your own test double instead of using a mocking framework is that you never have to reference the collaborator’s method.</p><p>For example, when mocking using Mockito you are doing something like this:</p><pre>@Test<br>fun test1() {<br>    whenever(collaborator.method()).thenReturn(...)<br>    //...<br>}</pre><pre>@Test<br>fun test2() {<br>    whenever(collaborator.method()).thenReturn(...)<br>    //...<br>}</pre><pre>@Test<br>fun test3() {<br>    whenever(collaborator.method()).thenReturn(...)<br>    //...<br>}</pre><pre>//... you got the point</pre><p>While, when you create your own test double:</p><pre>class CollaboratorTestDouble: Collaborator {<br>    fun mockMethod(...) { ... }</pre><pre>    override fun method() {<br>        // stub, mock, spy...<br>    }<br>}</pre><p>Your tests won’t reference the method anymore:</p><pre>@Test<br>fun test1() {<br>    collaborator.mockMethod(...)<br>    //...<br>}</pre><pre>@Test<br>fun test2() {<br>    collaborator.mockMethod(...)<br>    //...<br>}</pre><pre>@Test<br>fun test3() {<br>    collaborator.mockMethod(...)<br>    //...<br>}</pre><pre>//... </pre><p>And by not referencing the collaborator’s methods your tests are more protected from method signature changes, which ends up with less code to update and less code to review.<br>Tests also look more readable.</p><p>Sometimes you may not even have to create a test double because you can just <strong>use a real implementation. <br></strong>This is usually preferable when such implementation <strong>requires minimal setup</strong> (it has no collaborators) and it was created before the current class under test.</p><p>Some other times mocks just don’t work well at all. <br>Think about the SharedPreferences.Editor interface, every method returns the object instance and the transaction is not executed until apply or commit is invoked.<br>Many here give up with the mocking and just move the test to androidTest folder so they can use the real preferences but that in my opinion is a complete failure.<br>The fastest and cleanest solution is to create a <strong>fake </strong>like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3aa463df5fd1c279d59a06891ca3fb57/href">https://medium.com/media/3aa463df5fd1c279d59a06891ca3fb57/href</a></iframe><p>This fake uses an in-memory implementation of the SharedPreferences interface.<br>By using this in your test class there is no setup required and you can pre-set your preferences by just doing <br>fakePreferences.putString(&quot;key&quot;, &quot;value&quot;).apply() <br>just like you would do with real SharedPreferences in androidTest with the difference that with this approach your tests will run on the <strong>JVM</strong> and will be much faster (and obviously faster than using mocks).</p><h4>A funny story</h4><p>A few years ago Mockito didn’t have support for final classes and when developers were migrating their codebases from Java to Kotlin (where classes are final by default) their tests were failing.</p><p>That was a clear sign of their bad architecture and at that point, there were only a clean solution (adding an abstraction) and a dirty solution (making classes open).</p><p>Which solution do you think most developers adopted? 😈</p><p>Let’s just say that I know many companies that did a big refactoring PR for removing open keyword everywhere once Mockito released their mock-maker-inline workaround (that still doesn’t work for spy and cannot be used in androidTest btw).</p><p><em>References:<br></em><strong><em>* </em></strong><em>Clean Architecture, Chapter 11 </em>(<strong>DIP</strong>)<em><br>* </em><a href="https://alistair.cockburn.us/hexagonal-architecture/"><em>Hexagonal Architecture</em></a><em><br>* </em><a href="https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/"><em>Onion Architecture, Part 1</em></a><em><br>* </em><a href="https://martinfowler.com/articles/mocksArentStubs.html"><em>Martin Fowler, Mocks Aren’t Stubs</em></a></p><h3>Interface Segregation Principle</h3><blockquote><em>Keep interfaces small so that users don’t end up depending on things they don’t need.</em></blockquote><p>This is one mainly for us, statically-typed language users, in fact in dynamically-typed languages developers may even get away with just <strong>S.O.L.D. </strong>instead of<strong> S.O.L.I.D. </strong>(there are still benefits in adhering to the ISP in dynamically typed languages but I won’t cover them since Android is based on Java/Kotlin anyway).</p><p>The ISP can be seen as an extension of the DIP, given that you can’t have small interfaces if you don’t have interfaces at all 😉.</p><p>While with the DIP the purpose is to protect your code from the flow of control and transitive dependencies, with the ISP <em>we make sure our collaborators not only are interfaces (or any other type of abstractions) but they are also small so we don’t depend on something we don’t use, that when changed, will cause an extra recompilation</em>.</p><p>Let’s take a look at this example:</p><pre>interface UserService {<br>    fun login(...)<br>    fun logout(...)<br>    fun createAccount(...)<br>    //...<br>}</pre><pre>class LoginViewModel(<br>    private val userService: UserService<br>): ViewModel() {<br>    fun doSomething() {<br>        //...<br>        userService.login(...)<br>        //...<br>    }<br>}</pre><p>LoginViewModel uses only one method of UserService yet it is depending on all of them + all the object parameters they require.<br>This means that a change in logout will recompile LoginViewModel.<br>And also adding/removing methods to UserService will cause a recompilation.</p><p>How do you solve this? Simple, instead of having a big interface you create more and smaller interfaces:</p><pre>interface LoginInteractor {<br>    fun execute(...)<br>}<br>interface LogoutInteractor {<br>    fun execute()<br>}<br>interface CreateAccountInteractor {<br>    fun execute()<br>}<br>//...</pre><h4>ISP and SRP</h4><p>If it wasn’t clear already, S.O.L.I.D. principles are not independent of each other, so by following one you are most likely following also some others, and by breaking one, you are most likely breaking also some others (this is the reason why most developers break most of them).</p><p>Classes can implement interfaces, so if interfaces are small then classes are most likely following the SRP.</p><p><em>After all, which class do you think is more likely to break the SRP? <br>A class with a single method or a class with 100 methods?</em></p><p>Sometimes instead you want small interfaces but slightly bigger classes.<br><em>Interfaces are preferably small because they are optimized for the classes that use them.</em><br>Classes instead should be responsible for 1 thing, this often makes them smaller but as the SRP says, you should not split one responsibility into multiple classes since you are meant to aggregate cohesive methods in a single class.</p><p>What to do in this case? <br>Simple, <em>you make your class implement multiple interfaces</em>!</p><h4>From ISP to CRP</h4><p>At the <strong>component level,</strong> the <strong>ISP</strong> becomes the <strong>Common Reuse Principle (CRP) </strong>which can be phrased in the following way:</p><blockquote><em>Don’t force users of a component to depend on things they don’t need.</em></blockquote><p>This is another important principle for modularization.<br><em>Classes that are reused together should be part of the same component.<br></em>Like the CCP it tells us how to group classes but it also tells us which classes are not to keep together under the same component.</p><p>Just like a class recompiles when an unused collaborator’s method changes, a <em>component</em> recompiles when an unused class of an <em>imported component </em>changes.</p><h4>Testing</h4><p>When creating a test double it is quite annoying having to deal with big interfaces since you have to stub/mock all the methods of the interface.</p><p>In order to avoid this issue, you can either <strong>use a mocking framework </strong>or <strong>adhere to the ISP.</strong></p><p>Personally, I’m not against mocking frameworks, I actually use them in all my projects but what I don’t like is that by using them developers can be tempted to break 1 or more principles:</p><ul><li>Because you can mock classes, you might be tempted to avoid interfaces (DIP 💔)</li><li>Because you don’t have to mock all the methods, you might be tempted to keep big interfaces/classes (SRP and ISP 💔)</li></ul><p>Adhering to S.O.L.I.D. principles makes testing easier and <em>removes the need to use mocking frameworks.<br></em>Somehow Android Developers think that they can’t test their code if they don’t use mocking frameworks, unlike iOS developers that tend to stay as vanilla (classicists) as possible. <br><em>This is because Java/Kotlin library developers have done very good marketing in the past years and </em><strong><em>not because unit testing was born with mocking in mind</em></strong>.</p><p>My take is that choosing between Mocking Frameworks and Test Doubles is up to your team’s preference (<em>if that is the only way your team is going to write tests then it is the right way</em>) but <strong>your code should be testable regardless of the mocking strategy you use</strong>!</p><p>References:<br>* Clean Architecture, Chapter 10 (<strong>ISP</strong>)<br>* Clean Architecture, Chapter 13 (<strong>CRP</strong>)</p><h3>Open-Closed Principle</h3><blockquote><em>A software artifact should be open for extension but closed for modification.</em></blockquote><p>The ultimate goal of software architecture is to add new features without having to rewrite or recompile any existing code.<br>This is because every time you modify existing code you may introduce regression bugs and break previously built functionalities, not to mention merge conflicts and very big pull requests!</p><p>The OCP is the least independent S.O.L.I.D. principle and the one you should monitor the most, in fact, breaking any other principle will most likely break the OCP too:</p><ol><li><strong>When LSP is violated</strong>, hence inheritance is used in the wrong way, adding a subclass may require a <strong>modification of the parent class</strong> in order to not break other subclasses.</li><li><strong>When SRP is violated</strong>, hence a class belongs to more than 1 actor, whenever an actor requires a new integration then that new integration will <strong>modify an existing method</strong> which will affect also the other actors.</li><li><strong>When DIP is violated</strong>,<strong> </strong>hence concrete classes depend on concrete classes (creating also transitive dependencies), adding a new method somewhere will require a <strong>recompilation</strong> of all the classes up to the start of the flow (and yes, if you were wondering, recompilation counts as modification too).</li><li><strong>When ISP is violated</strong>, hence collaborators&#39; abstractions have more methods than required, adding a new method to a collaborator will <strong>recompile</strong> also classes that don’t use that method.</li></ol><blockquote>So if I follow the other 4 principles, do I get this one for free?</blockquote><p>No, unfortunately.</p><p>There are other ways you can break the OCP without breaking the other principles, but luckily it is very easy to detect these extra scenarios.</p><h4>Flag Arguments AKA “Magic Booleans”</h4><p>How many times have you thought<em> “I’ll just add a boolean here, if true I do A and if false I do B”?</em></p><p>That’s a modification of existing code where you support the integration of B by adding a boolean.</p><p>Instead of adding a boolean and modifying an existing function, add a new function.</p><p>For example, instead of:</p><pre>fun pay(isDebitCard: Boolean) { ... }</pre><p>do:</p><pre>fun payWithDebitCard() { ... }</pre><pre>fun payWithCreditCard() { ... }</pre><h4>Enums</h4><p>They present the same problem of flag arguments but the chance of breaking existing features is even higher since you can have a lot of values, unlike booleans where you have at most 2 values (unless you are passing more than one boolean 😈).</p><p>So again, instead of:</p><pre>enum class PaymentType {<br>    DEBIT_CARD, CREDIT_CARD, BANK_TRANSFER, GOOGLE_PAY<br>}</pre><pre>fun pay(paymentType: PaymentType)</pre><p>do:</p><pre>fun payWithDebitCard() { ... }</pre><pre>fun payWithCreditCard() { ... }</pre><pre>fun payWithBankTransfer() { ... }</pre><pre>fun payWithGooglePay() { ... }</pre><p>This way adding a payment method cannot break the previously implemented payment methods and doesn’t require recompilation of all the classes importing the enum.</p><blockquote>Does this mean I can’t ever use flags and enums?</blockquote><p>It is nearly impossible to write software without ever using flags and enums so, obviously, not all your classes and functions will strictly adhere to the OCP.<br>The important thing is that when you have to use a flag argument or an enum your function does only that if/else or when statement and nothing else.</p><p>References:<br>* Clean Architecture, Chapter 8<br>* Clean Code, Chapter 3</p><h3>Summary</h3><p>We can summarize the principles in the following way:</p><ol><li>SRP: Classes should belong to a single actor</li><li>OCP: New integrations shouldn’t touch existing code</li><li>LSP: Use inheritance properly and favor composition</li><li>ISP: Abstractions should be as small as possible</li><li>DIP: Collaborators should be abstractions</li></ol><h3>Last Notes</h3><p>I know that S.O.L.I.D. principles are not the most interesting topic and that the article was long but hopefully now you have a better understanding of the theory behind Clean Architecture.</p><p>If you are still struggling to understand them don’t worry, we will see how they work in practice in the next articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a661b103451" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clean-android-dev/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451">The “Real” Clean Architecture in Android: S.O.L.I.D.</a> was originally published in <a href="https://medium.com/clean-android-dev">Clean Android Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>