<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Raul M on Medium]]></title>
        <description><![CDATA[Stories by Raul M on Medium]]></description>
        <link>https://medium.com/@zealotdev?source=rss-92791f451727------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4I-CX7KVCMt9LYUMTHDJvw.jpeg</url>
            <title>Stories by Raul M on Medium</title>
            <link>https://medium.com/@zealotdev?source=rss-92791f451727------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 18:48:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zealotdev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[5 Don’ts of working with Jetpack Compose]]></title>
            <link>https://medium.com/@zealotdev/5-donts-of-working-with-jetpack-compose-de01555fa21e?source=rss-92791f451727------2</link>
            <guid isPermaLink="false">https://medium.com/p/de01555fa21e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Raul M]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 05:38:47 GMT</pubDate>
            <atom:updated>2026-02-22T05:38:47.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxsJfl77y1YndNq9K0JKaQ.png" /></figure><p>Have you ever had issues managing state, updating the UI in Compose, or having functions called multiple times without knowing why?</p><p>Jetpack Compose is a framework that gives you a lot of freedom, but if we’re not careful, it’s easy to fall into bad practices causing these problems. Here’s a list of guidelines to help avoid them.</p><p><strong>1 —Don’t Inject ViewModels in every composable</strong></p><p>The main guideline here is that the ViewModel should be injected at <strong>the root composables of the screen</strong>. For child composables, pass down only the properties or functions they need instead of injecting the ViewModel again.</p><pre>class ProductViewModel : ViewModel() { /* ... */ }<br><br>@Composable<br>fun ProductList() {<br>    LazyColumn {<br>        items(products) { product -&gt;<br>            ProductItem(product)<br>        }<br>    }<br>}<br><br>@Composable<br>fun ProductItem(product: Product) {<br>    // Bad: Getting ViewModel here, deep inside the UI hierarchy<br>    val viewModel: ProductViewModel = viewModel() <br>    Button(onClick = { viewModel.addToCart(product) }) {<br>        Text(&quot;Add to Cart&quot;)<br>    }<br>}</pre><p>This approach is difficult to maintain, test, and because it may be recomposed frequently, can lead to performance issues. or not even just viewModels but any other complex function. On the other hand,</p><pre>class ProductViewModel : ViewModel() { /* ... */ }<br><br>@Composable<br>fun ProductScreen() {<br>    // Good: Access ViewModel at screen-level<br>    val viewModel: ProductViewModel = viewModel()<br><br>    LazyColumn {<br>        items(viewModel.products) { product -&gt;<br>            ProductItem(product = product, onAddToCart = { viewModel.addToCart(it) })<br>        }<br>    }<br>}<br><br>@Composable<br>fun ProductItem(product: Product, onAddToCart: (Product) -&gt; Unit) {<br>    // Now ProductItem is stateless; doesn&#39;t access ViewModel directly<br>    Button(onClick = { onAddToCart(product) }) {<br>        Text(&quot;Add to Cart&quot;)<br>    }<br>}<br><br></pre><p>Single source of truth: Only one ViewModel owns the state.</p><p>Composable reusability: Lower-level composables don’t care about business logic. They just receive state/events.</p><p>Easier testing: You can pass fake state/events to stateless composables.</p><p>No hidden lifecycle bugs: ViewModels stay tied to the correct owner.</p><p><strong>2 — Don’t work with mutable objects</strong></p><p>Jetpack Compose only works with immutable objects for example this class would be considered as unstable, that’s why <strong>any change done to this state will pass unaware for Jetpack Compose</strong> and you won’t see any changes reflected on the UI.</p><pre>//BAD for the state<br>data class User(<br>    var id: String,<br>    var name: String<br>)</pre><p>including mutableListOf like this</p><pre>@Composable<br>fun ContactListScreen() {<br>    //BAD: mutableListOf is not observable<br>    val contacts = mutableListOf(<br>        Contact(&quot;Alice&quot;, &quot;123&quot;),<br>        Contact(&quot;Bob&quot;, &quot;456&quot;)<br>    )<br><br>    Column {<br>        Button(onClick = {<br>            // Trying to add a contact<br>            contacts.add(Contact(&quot;Charlie&quot;, &quot;789&quot;))<br>        }) {<br>            Text(&quot;Add Contact&quot;)<br>        }<br><br>        // This will NOT update automatically<br>        contacts.forEach { contact -&gt;<br>            Text(&quot;${contact.name}: ${contact.number}&quot;)<br>        }<br>    }<br>}</pre><p>instead use use val for immutability</p><pre>//Stable class<br>data class User(<br>    val id: String,<br>    val name: String<br>)</pre><p>and use mutableStateListOf — which is a <strong>special observable list</strong>. Compose tracks <strong>internal mutations</strong>, so adding/removing items automatically triggers recomposition.</p><pre>import androidx.compose.foundation.layout.*<br>import androidx.compose.material3.*<br>import androidx.compose.runtime.*<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.unit.dp<br><br>data class Contact(val name: String, val number: String)<br><br>@Composable<br>fun ContactListScreen() {<br>    val contacts = remember {<br>        mutableStateListOf(<br>            Contact(&quot;Alice&quot;, &quot;123&quot;),<br>            Contact(&quot;Bob&quot;, &quot;456&quot;)<br>        )<br>    }<br><br>    Column(modifier = Modifier.padding(16.dp)) {<br>        Button(<br>            onClick = { contacts.add(Contact(&quot;Charlie&quot;, &quot;789&quot;)) },<br>            modifier = Modifier.padding(bottom = 16.dp)<br>        ) {<br>            Text(&quot;Add Contact&quot;)<br>        }<br><br>        LazyColumn(<br>            verticalArrangement = Arrangement.spacedBy(8.dp),<br>            modifier = Modifier.fillMaxWidth()<br>        ) {<br>            items(contacts) { contact -&gt;<br>                Text(&quot;${contact.name}: ${contact.number}&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>see more in <a href="http://medium.com/r?url=https%3A%2F%2Fdeveloper.android.com%2Fdevelop%2Fui%2Fcompose%2Fperformance%2Fstability">official documentation</a>, <a href="https://developer.android.com/develop/ui/compose/state#state-in-composables">extra documentation</a></p><p><strong>3 — Don’t consider configuration changes while holding the state</strong></p><p>Let’s say we’re saving the state of a checkbox selection. If something like screen rotation, dark mode, or a font scale change occurs (which are considered configuration changes), the state would be reset.</p><pre>@Composable<br>fun Greeting() {<br>    // State will be lost after configuration changes<br>    var isChecked by remember { mutableStateOf(false) }<br><br>    // State will be kept<br>    var isChecked by rememberSaveable { mutableStateOf(false) } <br><br>    Checkbox(<br>        checked = isChecked,<br>        onCheckedChange = { isChecked = it }<br>    )<br>}<br><br></pre><p><strong>4 — Don’t consider lifecycle awareness for flows</strong></p><p>Collecting flows from a ViewModel should be done safely and lifecycle-aware.</p><pre>// Android Only <br>val user by viewModel.userFlow.collectAsStateWithLifecycle()<br><br>// Platform Agnostic<br>val user by viewModel.userFlow.collectAsState()</pre><p><strong>5 —Don’t forget to set an index when using lists</strong></p><p>By default, lists in Compose are index-based. If the list you’re using allows items to be inserted, removed, or reordered, the state of each item can be affected.</p><pre>@Composable<br>fun UserList(users: List&lt;User&gt;) {<br>    LazyColumn {<br>        //index based<br>        items(users) { user -&gt;<br>            UserRow(user)<br>        }<br>    }<br>}</pre><p>For example, in this screen, when we check the box for a user, it shows that user’s details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*BsX5LkQh0Ah8YTuUryc3oA.png" /></figure><p>Now, let’s say we add George at the beginning of the list (position 0). <strong>The state from Bob will be passed to Alice instead of being kept for Bob.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*H5kPs6LerWldG-VX9_-qQQ.png" /></figure><p>But if we keep an id for each item in the list and use it as the key, this issue won&#39;t occur anymore.</p><pre>@Composable<br>fun UserList(users: List&lt;User&gt;) {<br>    LazyColumn {<br>        //good practice<br>        items(items = users, key = { user -&gt; user.id }) { user -&gt;<br>            UserRow(user)<br>        }<br>    }<br>}</pre><p>What other don’ts should you add to the list? feel free to comment! or clap if you found it useful! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de01555fa21e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Ways to make your code more Unit-Test friendly (Android Native)]]></title>
            <link>https://medium.com/@zealotdev/5-ways-to-make-your-code-more-unit-test-friendly-android-native-263659dc0a99?source=rss-92791f451727------2</link>
            <guid isPermaLink="false">https://medium.com/p/263659dc0a99</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Raul M]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 02:25:38 GMT</pubDate>
            <atom:updated>2026-02-15T05:03:21.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BdnwsysVhfz8O1_r-TAaBg.png" /></figure><p>You might wonder why we have to write unit tests for our apps. Is it just a whim from our boss? Is it meant to make developers’ work harder?</p><p>The answer is neither. Writing tests helps us maintain <strong>code integrity</strong> and ensures that future updates don’t unintentionally break existing functionality.</p><p>So how can we design and develop our applications in a way that makes unit testing easier and more effective?</p><p><strong>1 — Dispatcher Injection </strong><br>Since we’re working with coroutines and our applications perform asynchronous operations, we should inject dispatchers instead of hardcoding them whenever we launch a coroutine. Otherwise, our tests may become flaky and unpredictable.</p><p>Avoid Hardcoded dispatchers ❌</p><pre>class UserRepository(<br> private val api: UserApi<br>) {<br>  suspend fun fetchUser(): User = withContext(Dispatchers.IO) {<br>   api.getUser()<br>   }<br>}</pre><p>Use injection ✅</p><pre>class UserRepository(<br>    private val api: UserApi,<br>    private val dispatchers: DispatcherProvider<br>) {<br>    suspend fun fetchUser(): User = withContext(dispatchers.io) {<br>        api.getUser()<br>    }<br>}</pre><p>In this way, the test implementation would look like this:</p><pre>import kotlinx.coroutines.test.StandardTestDispatcher<br>import kotlinx.coroutines.test.runTest<br>import org.junit.Test<br>import kotlin.test.assertEquals<br><br>class UserRepositoryTest {<br><br>    private val testDispatcher = StandardTestDispatcher()<br><br>    @Test<br>    fun `loadUser returns expected user`() = runTest(testDispatcher) {<br>        val fakeApi = FakeApi()<br>        val repository = UserRepository(<br>            ioDispatcher = testDispatcher<br>        )<br><br>        val user = repository.loadUser()<br><br>        assertEquals(&quot;John&quot;, user.name)<br>    }<br>}</pre><p><strong>2 — Only use nullables when necessary</strong></p><p>Kotlin’s null-safety is powerful, but that doesn’t mean we should use it all the time. There are a few reasons to consider:</p><p>a) Increased test coverage:<br>For example, a Boolean has only two states. Making it nullable introduces an additional case that must be tested. When this is multiplied across all nullable properties, it can significantly impact overall test coverage.</p><p>b) Potential invalid or ambiguous UI states:<strong><br></strong> A null value can mean many things — “not loaded yet,” “loading,” “failed,” “empty,” “not available,” or “not initialized.” This ambiguity can lead to conflicting UI states. By defining explicit states, we avoid these conflicts and make the app’s behavior clearer.</p><p>But if we define a state like this we wouldn’t have conflict states ✅</p><pre>sealed interface UserUiState {<br>    object Loading : UserUiState<br>    data class Success(val user: User) : UserUiState<br>    data class Error(val message: String) : UserUiState<br>}</pre><p>and we would have a better and exhaustive evaluation ✅</p><pre>when (state) {<br>    is Success -&gt; Text(state.user.name)<br>    is Loading -&gt; LoadingIndicator()<br>    is Error -&gt; ErrorView(state.message)<br>}</pre><p>Helping us making an exhaustive tests with legitimate scenarios</p><p><strong>3 — Android API only in component classes</strong></p><p>Like the documentation in the <a href="https://developer.android.com/topic/architecture">General best practices</a> says app components should be the only clases that rely on Android Framework SDK to reduce coupling.</p><p>If you’re trying to cover a class, but this class turns out to have a lot of references to Android’s API all of their properties will return null, unless are mocked</p><p>Injecting Context ❌</p><pre>class LoginUseCase {<br>    fun validateEmail(email: String, context: Context): Boolean {<br>        if (!email.contains(&quot;@&quot;)) {<br>            Toast.makeText(context, &quot;Invalid email&quot;, Toast.LENGTH_SHORT).show()<br>            return false<br>        }<br>        return true<br>    }<br>}</pre><p>No references to Android’s API ✅</p><pre>class LoginUseCase {<br>    fun validateEmail(email: String): Boolean {<br>        return email.contains(&quot;@&quot;)<br>    }<br>}</pre><p><strong>4 — Test should be short and clear</strong></p><p>If every test checks something specific, it will be easier to identify what’s broken.</p><p>General test case ❌</p><pre>@Test<br>fun loginWorks() {<br>    val result = login(&quot;admin@test.com&quot;, &quot;123456&quot;)<br>    assertTrue(result.isValidEmail)<br>    assertTrue(result.isPasswordCorrect)<br>    assertTrue(result.isLoggedIn)<br>}</pre><p>Specific tests like these, your peers will appreciate it ✅</p><pre>@Test<br>fun emailShouldBeValid() { ... }<br><br>@Test<br>fun passwordShouldBeCorrect() { ... }<br><br>@Test<br>fun userShouldLoginSuccessfully() { ... }</pre><p><strong>5 — Ignore data classes</strong></p><p>In cases such as API responses, data classes do not contain any business logic. For this reason, we can use a suffix, a dedicated package, or a marker annotation to exclude them from coverage.</p><pre>sonar.coverage.exclusions=**/dto/**, **/data/**, **/*Response.kt</pre><p>Those are my 5 tips for writing unit-test friendly Android code. How about you? I’d love to hear how you and your team keep your code easy to test.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=263659dc0a99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 5 Runtime Exceptions that we overlook when we’re developing Android Apps and how to prevent…]]></title>
            <link>https://medium.com/@zealotdev/top-5-runtime-exceptions-that-we-overlook-when-were-developing-android-apps-and-how-to-prevent-74088cb87dc2?source=rss-92791f451727------2</link>
            <guid isPermaLink="false">https://medium.com/p/74088cb87dc2</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Raul M]]></dc:creator>
            <pubDate>Sat, 03 May 2025 04:06:41 GMT</pubDate>
            <atom:updated>2025-05-03T04:06:41.004Z</atom:updated>
            <content:encoded><![CDATA[<h3>Top 5 Runtime Exceptions that we overlook when we’re developing Android Apps and how to prevent them</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vb3-yJbeaDlOmWoxLU1_SA.png" /></figure><p>Since “checked exceptions” are detected for the compiler try to wrap any chance of these 5 exceptions which are the most common using Kotlin.</p><p><strong>1 — IndexOutOfBoundsException</strong></p><p>Basically happens when we try to open a slot of the list/array that doesn’t exist</p><pre>IndexOutOfBoundsException<br>val list = listOf(1, 2, 3)<br>println(list[3]) // Throws IndexOutOfBoundsException</pre><p>what we could use instead are getters with optionals for nulls</p><pre>val list = listOf(1, 2, 3)<br>val item = list.getOrNull(5) // Returns null instead of throwing<br><br>//or<br><br>val first = list.firstOrNull()<br>val last = list.lastOrNull()</pre><p>or just don’t hardcode indexes and use iterators for example</p><pre>for (i in list.indices) {<br>    println(list[i])<br>}</pre><p><strong>2 — IllegalStateException</strong></p><p>This happens when a value is read but it hasn’t being initialized</p><pre>lateinit var name: String<br>println(name) // Throws IllegalStateException: lateinit property not initialized</pre><p>so we can check first before its usage</p><pre>if (::name.isInitialized) {<br>    println(name)<br>} else {<br>    println(&quot;Name not initialized yet&quot;)<br>}</pre><p><strong>3 - ClassCastException</strong></p><p>Sometimes we have a list of different type of objects and when we try to cast without doing it safely using as? will throw this exception</p><pre>val obj: Any = &quot;hello&quot;<br>val number = obj as Int // Throws ClassCastException<br>val number = obj as? Int // Returns null</pre><p>or check the type before its usage</p><pre>val obj: Any = 123<br><br>if (obj is String) {<br>    println(obj.length)  // Smart cast to String<br>} else {<br>    println(&quot;Not a String&quot;)<br>} </pre><p><strong>4- NumberFormatException</strong></p><p>If we’re not sure of the value that we’re going to receive is better to enclose it within a try catch and give a default value or to use the optional null method</p><pre>val num = &quot;abc&quot;.toInt() // Throws NumberFormatException<br>val num = &quot;abc&quot;.toIntOrNull() //will return null</pre><p><strong>5 — ConcurrentModificationException</strong></p><p>This happens when we try to modify a list while we’re iterating it</p><pre>val list = mutableListOf(1, 2, 3)<br>for (item in list) {<br>    if (item == 2) list.remove(item) // Throws ConcurrentModificationException<br>}</pre><pre>list.removeIf { it == 2 } // Safe</pre><p>and finally <strong>NullPointerException</strong> is a really common exception but since Kotlin is null safe we’re not going to cover it. Just avoid the operator “<strong>!!</strong>” unless it is really necessary.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74088cb87dc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Coding practices to follow for a maintainable app]]></title>
            <link>https://medium.com/@zealotdev/send-this-5-points-checklist-to-a-junior-dev-to-read-before-raising-a-pull-request-7108bcb5d336?source=rss-92791f451727------2</link>
            <guid isPermaLink="false">https://medium.com/p/7108bcb5d336</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Raul M]]></dc:creator>
            <pubDate>Thu, 01 May 2025 04:14:21 GMT</pubDate>
            <atom:updated>2025-05-03T03:53:11.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r7vD-KyETzFvndSNhhRo5Q.png" /></figure><p>As we’re developing software, new features are being placed on top of existing ones, that’s why every feature has to be carefully placed and flexible to move if needed. That’s why I wrote some practices to keep our blocks of software stable and flexible, just like jenga pieces.</p><p><strong>1- Avoid putting Business Logic on the View Layer</strong></p><pre>//Composables are views<br>@Composable<br>fun PriceTag(price: Double, discount: Double) {<br>    //Business logic<br>    val finalPrice = if (discount &gt; 0) price * (1 - discount) else price<br>    Text(text = &quot;Final price: $${String.format(&quot;%.2f&quot;, finalPrice)}&quot;)<br>}</pre><p>Instead we can have it in a View Model or a use case</p><pre>fun calculateFinalPrice(price: Double, discount: Double): Double {<br>    return if (discount &gt; 0) price * (1 - discount) else price<br>}</pre><p>And then call that function inside the view</p><pre>@Composable<br>fun PriceTag(price: Double, discount: Double) {<br>    val finalPrice = remember(price, discount) {<br>        //Calling Business Logic from another layer<br>        calculateFinalPrice(price, discount)<br>    }<br><br>    Text(text = &quot;Final price: $${String.format(&quot;%.2f&quot;, finalPrice)}&quot;)<br>}</pre><p>So what logic is allowed in a view? just <strong>pure UI-related logic</strong> (e.g., formatting, colors, visibility). This would help us for better testing as well.</p><p>This was just a small example but you can look further googling the principle of Separation of concerns.</p><p><strong>2 — Don’t break Encapsulation for Testing visibility</strong></p><p>Sometimes I’ve seen functions or variables made public, or using an annotation or even reflection to be able to increase test coverage. But the thing is that private methods or variables should be tested through the public functions that are calling those private members of the class, like the following example:</p><p>Note that here the token is properly encapsulated</p><pre>class AuthManager {<br>    private var authToken: String? = null //making it private as it should<br><br>    fun login(user: String, pass: String): Boolean {<br>        if (user == &quot;admin&quot; &amp;&amp; pass == &quot;1234&quot;) {<br>            authToken = &quot;token_abc123&quot;<br>            return true<br>        }<br>        return false<br>    }<br>}</pre><p>but if we break it making it public</p><pre>class AuthManager {<br>    var authToken: String? = null // changed from private to public <br><br>    fun login(user: String, pass: String): Boolean {<br>        if (user == &quot;admin&quot; &amp;&amp; pass == &quot;1234&quot;) {<br>            authToken = &quot;token_abc123&quot;<br>            return true<br>        }<br>        return false<br>    }<br>}</pre><p>to be able to test the function incorrectly</p><pre>val authManager = AuthManager()<br>authManager.login(&quot;admin&quot;, &quot;1234&quot;)<br>assertEquals(&quot;token_abc123&quot;, authManager.authToken) // testing internal state (bad)</pre><p>internal state gets exposed… but if we keep it private we can test over the result</p><pre>val result = authManager.login(&quot;admin&quot;, &quot;1234&quot;)<br>assertTrue(result) // behavior, not internal state</pre><p>Note aside : sometimes technologies like sonar might be looking just for the cursor to pass over certain flows, so if sonar is failing you might not need to assert the private values but just let the sonar’s cursor run over all the flows.</p><p><strong>3 - Avoid Over-Engineering</strong></p><p>Perhaps we have a simple feature to develop or function to do and we end up creating classes and instances that are not necessary like the following example:</p><pre>object MathHelper { //internally creates a singleton<br>    fun square(x: Int): Int {<br>        return x * x<br>    }<br>}</pre><p>or worse</p><pre>class MathHelper {<br>    fun square(x: Int): Int = x * x<br>}<br>val helper = MathHelper()<br>val result = helper.square(5)</pre><p>These are both bad solutions, since there’s no state to manage, dependencies or logic since it is a simple calculation that returns a value.</p><p>So we could make a top-level function</p><pre>fun square(x: Int): Int = x * x</pre><p>And there’s no need to inject a helper or instantiate it, we just import the function</p><p><strong>4— Keep loose Coupling</strong></p><p>Sometimes we create a function to do a simple task but the parameter that we defined is incorrect since we send the whole object with multiple fields but use only one of it. Here’s an example:</p><pre>data class User(<br>    val id: String,<br>    val name: String,<br>    val email: String,<br>    val profilePictureUrl: String,<br>    val settings: UserSettings,<br>    val lastLogin: Long<br>)<br><br>fun sendWelcomeEmail(user: User) {<br>    // Only email is used<br>    println(&quot;Sending welcome email to ${user.email}&quot;)<br>}</pre><p>Why is this bad?</p><p>Maybe later on we would need to send a welcome email but the email is coming from a different class, that’s what makes it hard to reuse and now we can say is tightly coupled.</p><p>Also it increases the memory usage and test complexity.</p><p>As well, makes it easier to break encapsulation or misuse unrelated fields.</p><p>So instead we should define the parameter with the only field needed, the email</p><pre>fun sendWelcomeEmail(email: String) { // This is the only param we need<br>    println(&quot;Sending welcome email to $email&quot;)<br>}<br><br>sendWelcomeEmail(user.email)</pre><p>Now it’s clear, decoupled, and focused.</p><p><strong>5 — Try to keep it as local as possible</strong></p><p>Every time we work on a function or a variable, it should be accessible for the places that is needed, nowhere else, a bad example could be:</p><pre>class Calculator {<br><br>    var result: Int = 0  // This should be local, not global<br><br>    fun add(a: Int, b: Int): Int {<br>        result = a + b<br>        return result<br>    }<br><br>    fun multiply(a: Int, b: Int): Int {<br>        result = a * b<br>        return result<br>    }<br>}</pre><p>Why is this bad?</p><p>Sharing result var is not necessary<br>Other code might read or write result at the wrong time<br>It’s not thread safe if class is used concurrently</p><p>A good example would be</p><pre>class Calculator {<br><br>    fun add(a: Int, b: Int): Int {<br>        val result = a + b // result it&#39;s local<br>        return result<br>    }<br><br>    fun multiply(a: Int, b: Int): Int {<br>        val result = a * b<br>        return result<br>    }<br>}</pre><p>Now is pure, thread safe, and easier to test</p><p>Give it a like and share if you think your peers should check this before raising a PR :)</p><p>But also let me know, what practices has helped you to keep your application maintainable for new features a new developers joining the team?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7108bcb5d336" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID principle in a minute]]></title>
            <link>https://medium.com/@zealotdev/solid-principle-in-a-minute-a3415e7000f7?source=rss-92791f451727------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3415e7000f7</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[computer-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Raul M]]></dc:creator>
            <pubDate>Wed, 22 May 2024 00:50:47 GMT</pubDate>
            <atom:updated>2026-02-15T05:46:49.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWHxJ4qkhf-c0qcLQUB9jA.png" /></figure><p>This is a topic very well know and explored, so if you read about it a long time ago but can’t remember exactly here’s a brief explanation, in my own words, and a quick example — hope you like it!</p><h4>Single Responsibility Principle (SRP)</h4><p>A Class shouldn’t have more than one Responsibility<br><em>breach</em> — when the POJO class saves into the database and generates reports</p><p>User has 3 responsibilities ❌</p><pre>// Bad: This POJO is doing too many things<br>data class User(val id: Int, val name: String) {<br><br>    fun saveToDatabase() {<br>        // code to save user to database<br>    }<br><br>    fun generateReport(): String {<br>        // code to generate a report for this user<br>        return &quot;Report for $name&quot;<br>    }<br>}</pre><p>Each class has <strong>one clear responsibility ✅</strong></p><pre>// POJO: Only represents data<br>data class User(val id: Int, val name: String)<br><br>// Responsibility 1: Database operations<br>class UserRepository {<br>    fun save(user: User) {<br>        // code to save user to database<br>    }<br>}<br><br>// Responsibility 2: Reporting<br>class UserReportGenerator {<br>    fun generate(user: User): String {<br>        // code to generate a report for the user<br>        return &quot;Report for ${user.name}&quot;<br>    }<br>}</pre><h4>Open Closed Principle (OCP)</h4><p>Open for extension, Closed for modification.</p><p>Every time we add sibling classes, we shouldn’t modify the existing methods that are working with them.<br><em>breach</em> — switch statements in the methods to call different behaviors for each sibling class, instead of using polymorphism</p><p>Every time you add a <strong>new notification type</strong> (e.g., PushNotification), you must <strong>modify </strong><strong>send() ❌</strong></p><pre>// Sibling classes<br>open class Notification<br>class EmailNotification(val email: String) : Notification()<br>class SMSNotification(val phone: String) : Notification()<br><br>// Bad: method using when/switch on sibling classes<br>class NotificationSender {<br>    fun send(notification: Notification) {<br>        when (notification) {<br>            is EmailNotification -&gt; println(&quot;Sending email to ${notification.email}&quot;)<br>            is SMSNotification -&gt; println(&quot;Sending SMS to ${notification.phone}&quot;)<br>        }<br>    }<br>}</pre><p>Using polymorphism ✅</p><pre>// Each class knows how to send itself<br>abstract class Notification {<br>    abstract fun send()<br>}<br><br>class EmailNotification(val email: String) : Notification() {<br>    override fun send() {<br>        println(&quot;Sending email to $email&quot;)<br>    }<br>}<br><br>class SMSNotification(val phone: String) : Notification() {<br>    override fun send() {<br>        println(&quot;Sending SMS to $phone&quot;)<br>    }<br>}<br><br>// Now NotificationSender doesn’t need changes<br>class NotificationSender {<br>    fun send(notification: Notification) {<br>        notification.send()  // polymorphism handles the right behavior<br>    }<br>}</pre><h4>Liskov Substitution Principle (LSP)</h4><p>Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. <em>breach</em> — when you pass a subclass to a method and obtain a different result when you pass the class</p><p>Ostrich is a Bird, but it <strong>cannot replace </strong><strong>Bird safely ❌</strong></p><pre>// Base class<br>open class Bird {<br>    open fun fly() {<br>        println(&quot;Flying high!&quot;)<br>    }<br>}<br><br>// Subclass that violates LSP<br>class Ostrich : Bird() {<br>    override fun fly() {<br>        throw UnsupportedOperationException(&quot;Ostriches can&#39;t fly!&quot;)<br>    }<br>}<br><br>// Function expecting a Bird<br>fun letBirdFly(bird: Bird) {<br>    bird.fly()  // will crash if an Ostrich is passed<br>}<br><br>fun main() {<br>    val ostrich = Ostrich()<br>    letBirdFly(ostrich) // ❌ Throws exception, breaks program<br>}</pre><p>Ostrich isn’t forced to inherit Bird behavior it cannot do ✅</p><pre>// Base interface for flying<br>interface Flyable {<br>    fun fly()<br>}<br><br>// Birds that can fly implement Flyable<br>class Sparrow : Flyable {<br>    override fun fly() {<br>        println(&quot;Sparrow flying!&quot;)<br>    }<br>}<br><br>// Birds that can&#39;t fly don&#39;t implement Flyable<br>class Ostrich {<br>    fun run() {<br>        println(&quot;Ostrich running!&quot;)<br>    }<br>}<br><br>// Function expecting a Flyable<br>fun makeItFly(flyable: Flyable) {<br>    flyable.fly()  // safe: only works with objects that can actually fly<br>}<br><br>fun main() {<br>    val sparrow = Sparrow()<br>    makeItFly(sparrow)  // ✅ Works fine<br><br>    val ostrich = Ostrich()<br>    // makeItFly(ostrich)  // ❌ Compile-time error, safe<br>}</pre><h4>Interface Segregation Principle (ISP)</h4><p>Many client-specific interfaces are better than one general-purpose interface<br><em>breach</em> — when you implement an interface and leave implementation empty for some methods)</p><p>Robot is forced to implement eat(), which it doesn’t need ❌</p><pre>// Fat interface<br>interface Worker {<br>    fun work()<br>    fun eat()<br>}<br><br>// Class that only needs to work<br>class Robot : Worker {<br>    override fun work() {<br>        println(&quot;Robot working&quot;)<br>    }<br><br>    override fun eat() {<br>        // ❌ Robots don’t eat! This method is useless, but we have to implement it<br>    }<br>}</pre><p>Each interface is <strong>focused on one responsibility ✅</strong></p><pre>// Segregated interfaces<br>interface Workable {<br>    fun work()<br>}<br><br>interface Eatable {<br>    fun eat()<br>}<br><br>// Robot only implements what it needs<br>class Robot : Workable {<br>    override fun work() {<br>        println(&quot;Robot working&quot;)<br>    }<br>}<br><br>// Human implements both<br>class Human : Workable, Eatable {<br>    override fun work() {<br>        println(&quot;Human working&quot;)<br>    }<br><br>    override fun eat() {<br>        println(&quot;Human eating&quot;)<br>    }<br>}</pre><h4>Dependency Inversion Principle (DIP)</h4><p>High-level modules should not depend on low-level modules; both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.<br><em>breach</em> — when the classes relies directly on other classes instead of interfaces like the ones on repositories</p><ul><li>UserService (high-level) <strong>depends directly on </strong><strong>UserRepository (low-level)</strong></li><li>Hard to replace UserRepository with a different implementation (e.g., API instead of DB) ❌</li></ul><pre>// Low-level module<br>class UserRepository {<br>    fun getUser(id: Int): String {<br>        return &quot;User $id&quot;<br>    }<br>}<br><br>// High-level module directly depends on low-level module<br>class UserService(private val userRepository: UserRepository) {<br>    fun printUser(id: Int) {<br>        val user = userRepository.getUser(id)<br>        println(&quot;User info: $user&quot;)<br>    }<br>}<br><br>fun main() {<br>    val repo = UserRepository()<br>    val service = UserService(repo)<br>    service.printUser(1)  // Works, but tightly coupled<br>}</pre><p>UserService depends on <strong>IUserRepository (abstraction)</strong>, not the concrete UserRepository ✅</p><pre>// Abstraction<br>interface IUserRepository {<br>    fun getUser(id: Int): String<br>}<br><br>// Low-level module implements abstraction<br>class UserRepository : IUserRepository {<br>    override fun getUser(id: Int): String {<br>        return &quot;User $id from DB&quot;<br>    }<br>}<br><br>// High-level module depends on abstraction<br>class UserService(private val userRepository: IUserRepository) {<br>    fun printUser(id: Int) {<br>        val user = userRepository.getUser(id)<br>        println(&quot;User info: $user&quot;)<br>    }<br>}<br><br>fun main() {<br>    val repo: IUserRepository = UserRepository()<br>    val service = UserService(repo)<br>    service.printUser(1)  // Works, loosely coupled<br>}</pre><p>Any feedback is welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3415e7000f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Concepts to understand background processes in Android]]></title>
            <link>https://medium.com/@zealotdev/basic-concepts-to-understand-background-processes-in-android-d4ae229916c7?source=rss-92791f451727------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4ae229916c7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Raul M]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 06:11:01 GMT</pubDate>
            <atom:updated>2022-12-22T06:11:01.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p543FKDbXFkqp5ZWbhBuWA.jpeg" /></figure><p>When you run an app it starts a linux process single threaded, it means that all the components you use and all the instructions that you program on it, will go one after the other on that single thread.</p><p>This thread is called <strong><em>Main</em></strong> since everything runs here by default, things like system events, user input events, services, alarms, etc but it’s also called <strong><em>UI</em></strong> because it draws all the views for the user to display every 16 ms to keep 60 frames per second.</p><p>So what happens if we know that we have to run something that could take a little bit of time, we can’t use the UI thread because it will give the user the feeling that the app is glitching or frozen and 5 seconds later we’ll get an <strong>ANR</strong> (Application Not Responding) giving the user a chance to close the application.</p><p>Therefore these kinds of heavy tasks or packages should line up for another “assembly line” or thread to process rather than going to the Main thread.</p><p>Another case to go off the Main Thread is when the <em>app is in the background</em> which means there’s no visible activities nor foreground services.</p><p><strong>What should we use to work with background processes?</strong></p><p>Well, if the task is <strong>impersistent</strong> (which means it won’t start again if the app is killed or if the device is rebooted) and <strong>immediate</strong> (that needs to be done right away) we’ll use Coroutines, for all other cases we’ll use WorkManager.</p><h4>What’s a coroutine?</h4><p>A Coroutine also called <em>light weight threads;</em> is a line of execution, with its own stack, its own local variables, and its own instruction pointer; but it shares global variables and mostly anything else with other coroutines.</p><p>If we compare Coroutines vs Threads, we’ll see that Coroutines have :</p><ul><li>Performance is way higher since consume not too much memory</li><li>Cancellation support</li><li>Fewer memory leaks</li><li>Since they’re executed within a thread and they can switch between them</li></ul><p>Before building a coroutine we’re gonna need a place to run them, for that we use the Scope :</p><ul><li>GlobalScope (not recommended since it’ll live as long as the app lives)</li><li>lifecycleScope</li><li>viewModelScope</li></ul><p>and then we start it with launch or async.</p><p><strong>Scope &amp; Dispatcher</strong></p><p>The <strong>Scope</strong> will define how long is going to live.</p><p>The <strong>Dispatcher</strong> will decide where it will run, and will put it on a queue.</p><p>But what kind of scopes do we have?</p><ul><li>Default — complex calculations</li><li>IO — network calls, working with databases, reading / writing files</li><li>Main — Updating anything on the view layer</li><li>Unconfined — Others</li></ul><p><strong>Differences between coroutine builders:</strong></p><p><strong>Launch</strong> starts a coroutine that is gonna be fired and forgotten and it will re-throws the exception if there’s any. <strong>It won’t block the thread</strong> and it <strong>will return a Job</strong> object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf4ec0e6f693d1410c51f39ae942ef7c/href">https://medium.com/media/cf4ec0e6f693d1410c51f39ae942ef7c/href</a></iframe><p><strong>Async</strong> It will return a value and it will hold on exceptions until await is called, calling await<strong> will block the thread </strong>and it <strong>will return a Deferred </strong>so<strong> you must call await </strong>and the exception or result is going to be retrieved in it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e2b4cc1b28e9aa7146c1e1fa15b3d1e/href">https://medium.com/media/9e2b4cc1b28e9aa7146c1e1fa15b3d1e/href</a></iframe><p><strong>RunBlocking<em> </em></strong>means that the thread that runs it (in this case — the main thread) gets <em>blocked</em> for the duration of the call, until all the coroutines inside runBlocking { … } complete their execution.</p><p><strong>Job vs Deferred</strong></p><p>Conceptually, a <strong><em>Job</em> is a cancellable thing with a life-cycle that culminates in its completion</strong>. Jobs can be arranged into parent-child hierarchies where cancellation of a parent leads to immediate cancellation of all its children.</p><p><strong>Deferred</strong>, it is a Job with a result. Deferred value is a non-blocking cancellable future.</p><h4>WorkManager</h4><p>As we mentioned above Work Manager is for <strong>persistent</strong> <strong>work</strong>, it means it will survive even if the app is killed or the device is rebooted, could be immediate, schedulable or long processes. Here is a quick example</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b567aaf7b9cbc9cc7d862f6f47f9dda8/href">https://medium.com/media/b567aaf7b9cbc9cc7d862f6f47f9dda8/href</a></iframe><h4>Services</h4><p>It’s one of the four application components and is meant to perform long operations in the background (even when by default they run on the main thread), and doesn’t provide a UI. We have to be careful though, if they’re not handled correctly they could consume a lot of memory and would end up draining the battery.</p><p>There are 3 types of services :</p><p><strong>Foreground Services </strong>:</p><p>Have to mention WorkManager already has an API for this.</p><p>We can use Foreground Services (shows a persistent notification like the one you have when you’re playing music, or using navigation) when the work isn’t urgent, nor user doesn’t need to know about it, but we must notify the user that the process is ongoing.</p><p>Note : Most of the foreground services don’t last more than 10 seconds so we should notify the user only if it lasts more than that otherwise it could be distracting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de8dc476181629d43cc74c753f366329/href">https://medium.com/media/de8dc476181629d43cc74c753f366329/href</a></iframe><p><strong>Background Services</strong> :</p><p>After API 26 the system imposed some restrictions for these services, in order to handle these restrictions, instead of using Service we can use WorkManager.</p><p><strong>Bound Service</strong>:</p><p>They can start when another component binds to them (could be another app as well though IPC) or calling startService or startForegroundService and then binding to them.</p><p>When you start a bound service you basically create a client-server relationship where the Service is going to be the server, and the client will be a fragment / activity or other application.</p><p>Whenever we need consistent or frequent communication between a client and the “server” we’ll need a bound service.</p><p><strong>Other Terms</strong> :</p><p><strong>IntentService / JobIntentService </strong>are <a href="https://developer.android.com/reference/android/app/IntentService">deprecated</a> instead use WorkManager</p><p><strong>Alarm Manager</strong> should be only used for precise events because it’s going to have a negative impact on the battery.</p><p><strong>Threads</strong> are low-level abstractions so it’s better use RxJava or Coroutines</p><p><strong>Job Scheduler</strong> is under the hood of WorkManager since API 23 +</p><p><strong>AsyncTask </strong>is <a href="https://developer.android.com/reference/android/os/AsyncTask">deprecated</a> instead use coroutines</p><p>Links used :</p><p><a href="https://medium.com/google-developer-experts/services-the-life-with-without-and-worker-6933111d62a6">Services the life with/without and work manager</a></p><p><a href="https://www.youtube.com/watch?v=t-3TOke8tq8&amp;t=275s">Async and Await — Kotlin Coroutines</a></p><p><a href="https://stackoverflow.com/questions/50343578/android-work-manager-vs-services">Work Manager vs Services</a></p><p><a href="https://youtu.be/_xNkVNaC9AI">Bound Services on Android</a></p><p><a href="https://developer.android.com/guide/background">Background Work Overview</a></p><p><a href="https://www.freepik.com/">Image Designed by <em>slidesgo</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4ae229916c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>