<?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 Baruch Nurilov on Medium]]></title>
        <description><![CDATA[Stories by Baruch Nurilov on Medium]]></description>
        <link>https://medium.com/@baruhn?source=rss-5cc6824dad1c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2ZHuATgmqN8_7pUuZrhGlQ.jpeg</url>
            <title>Stories by Baruch Nurilov on Medium</title>
            <link>https://medium.com/@baruhn?source=rss-5cc6824dad1c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 15:32:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@baruhn/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[You say “Reactive Programming” but what do you mean?]]></title>
            <link>https://medium.com/meliopayments/you-say-reactive-programming-but-what-do-you-mean-059ecf1cae52?source=rss-5cc6824dad1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/059ecf1cae52</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[melioengineering]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <dc:creator><![CDATA[Baruch Nurilov]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 10:37:11 GMT</pubDate>
            <atom:updated>2024-11-19T10:37:11.344Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*t3VIncD1rtscYUPklbcLGQ.png" /></figure><h3>Introduction</h3><p>Reactive Programming has become very common in recent years. But it is actually a general paradigm that can be implemented in many ways. Understanding the terms can be critical for developers. This article will introduce the fundamentals of Reactive Programming. Then it will dive into the most common reactive pattern — the Observer Pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/0*wNBszrrP3FDCg4JG" /></figure><h3>What is reactive programming?</h3><p>Wikipedia defines reactive programming as “<em>a declarative programming paradigm concerned with data streams and the propagation of change</em>”. Let’s take a deeper look at what it actually means.</p><p>You’ve probably noticed that this definition can be split into two parts. The first one is “<em>a declarative programming paradigm</em>”. Every coding paradigm can be categorized as either <strong>declarative</strong> or <strong>imperative</strong>. To understand the former we’ll begin by describing the latter: imperative programming.</p><h3>Using Imperative Programming</h3><p>Imperative programming is the most basic form of programming. It is what most people think of when they think about programming. We can describe it as a set of commands to be executed. In imperative programming the developer directly writes the control flow of the program.</p><p>Here’s an example: Let’s create some stopwatch logic using imperative programming:</p><pre>fun timer() {<br>  while (true) {<br>    delay(ONE_SECOND)<br>    secondsCounter++<br>  }<br>}</pre><p>We start by writing a while loop. In every iteration the loop will wait for a second and then increment the value of a seconds counter.</p><h3>Understanding Declarative Programming</h3><p>In declarative programming the code can be described as many units, each with a specified action or result. These units communicate by informing each other that something has happened. Here the control flow of the program is created from passing information between the units.<br>Let’s build the same stopwatch using declarative programming.</p><pre>fun timer() {<br>  while (true) {<br>    delay(ONE_SECOND)<br>    onSecondPassed()<br>  }<br>}<br><br>fun onSecondPassed() {<br>    incrementTimerCounter()<br>}<br><br>fun incrementTimerCounter() {<br>    secondsCounter++<br>}</pre><p>We start by creating the same while loop that waits for a second on every iteration. But, every time the waiting is over, the loop will simply indicate to the rest of the code that a second has passed. Upon receiving this indication, a code that increments the counter will be invoked elsewhere in the program.</p><h3>Comparing Imperative and Declarative</h3><p>This simple example shows a noticeable difference in how the logic and control flow of the program are scoped. The imperative implementation centralizes both of them. The declarative one, on the other hand, distributes them. As a result, imperative programming often depends on <strong>mutable</strong> <strong>shared data</strong>. In contrast, declarative programming usually uses <strong>immutable</strong> <strong>data</strong> transferred between code units.</p><p>To summarize: imperative code is a set of instructions that tells the program <strong>how</strong> <strong>to do something</strong>. To increment a counter every second in this example. Declarative code is focused on notifying <strong>what</strong> <strong>happened.</strong> A second has passed. Now, as a result, a counter will be incremented by another unit.</p><h3>Data streams and the propagation of change</h3><p>Now to the second part of the definition — “<em>concerned with data streams and the propagation of change</em>”. We saw that declarative programming separates the code into multiple units. In reactive programming the logic of the program is triggered by information passed between those units. As a result, every unit may generate its own data or information and pass it on. This way a stream, or multiple streams, of changes are created and propagated through the code driving the logic. Therefore, the program works by <strong>reacting</strong> to the propagation of these streams. In the example above, the information that a second has passed is what’s triggering the counter logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*i5v6g3iSx82AFxN0" /></figure><h3>Now, what is the observer pattern?</h3><p>In practice, programmers often implement reactive programming by using the <a href="https://en.wikipedia.org/wiki/Observer_pattern#:~:text=The%20observer%20pattern%20addresses%20the,can%20notify%20multiple%20other%20objects.">observer pattern</a>.</p><p>The most basic entities in the observer pattern are very creatively named the <strong>observable</strong> and the <strong>observer</strong>. Observers subscribe to updates from observables, and this connection is called a <strong>subscription</strong>.</p><p>The observable is a certain type of entity that emits events or changes to its value over time. They come in many names and implementations such as Publisher or Subject.</p><p>One popular implementation of the observer pattern is in the <a href="https://reactivex.io/">ReactiveX</a> libraries. They are available in many languages. Some languages have their own implementations like <a href="https://kotlinlang.org/docs/flow.html">Flow</a> in Kotlin or <a href="https://developer.apple.com/documentation/combine">Combine</a> in Swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*5VPgmEbDDUb1pify" /></figure><h3>Explaining different types of observables</h3><p>There are two types of observables — hot and cold. In short, hot observables are always active and can emit data and consume resources regardless of whether they’re being observed. Cold ones are created on-demand and emit data only when they’re being observed. The main reason to prefer one over the other is performance tradeoffs. Hot ones always consume resources but are always available. The cold ones don’t consume resources in idle but will be slower to respond for the first time.</p><p>For practical reasons I also like to divide observables into two additional groups — stateful and stateless. Both of these observables can be subscribed to and emit data. A stateless observable acts like a pipe — it streams data updates to all of its subscribers. When the moment of emission passes, the data is gone. <br>A stateful one acts exactly like a stateless one but also saves the last emitted value. Therefore, it can be queried just like a regular variable at any time. Stateless observables are used to communicate events, while stateful ones are used to relay changes in a continuous state. For example, a second passing is a one time event while the number of seconds passed is a continuous state.</p><h3>Summary</h3><p>Now we can update our declarative stopwatch example to use the observer pattern:</p><pre>fun timer() {<br>    while (true) {<br>        delay(ONE_SECOND)<br>        // Stateless observable to stream time events<br>        timeEventsStream.emit(SecondPassedEvent)<br>    }<br>}<br><br>fun incrementTimerCounter() {<br>    timeEventsStream.observe { event -&gt;<br>        // Stateful observable to emit and store the seconds count<br>        secondsPassedSinceStart.updateValue(secondsPassedSinceStart.value + 1)<br>    }<br>}</pre><p>This example now shows a code unit that observes events from another unit and reacts to them. In other words, this is a <strong>reactive program</strong> implemented using the <strong>observer pattern</strong>.</p><p>Now we can compare it to the first imperative implementation. This version seems to require more code to achieve the same result. But the main difference lies in the way we think about the code. This difference becomes significant as the program grows. In the next article we’ll see how it can make a very big difference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oax8wHazYd2h1-4A.png" /><figcaption><a href="https://bit.ly/jobs-medium">visit our career website</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=059ecf1cae52" width="1" height="1" alt=""><hr><p><a href="https://medium.com/meliopayments/you-say-reactive-programming-but-what-do-you-mean-059ecf1cae52">You say “Reactive Programming” but what do you mean?</a> was originally published in <a href="https://medium.com/meliopayments">Melio’s R&amp;D blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mobile Library Development — It’s Not Another Application]]></title>
            <link>https://proandroiddev.com/mobile-library-development-its-not-another-application-82a74875ded3?source=rss-5cc6824dad1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/82a74875ded3</guid>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Baruch Nurilov]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 15:40:07 GMT</pubDate>
            <atom:updated>2023-06-05T13:16:05.154Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mobile Library vs App Development — Same Same But Different</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MeWUX2bXzXAtI3BMVY_1yQ.png" /></figure><p>At first glance, library and application development seem very similar. Both use the same programming language, work with the same tools and run on the same devices. But when you get to the actual coding, you realize that libraries are a whole different world. They serve a different purpose and pose different challenges and limitations. As a result, they need a different approach to design, coding and project planning. These challenges go beyond the initial development well into the post-launch release cycles. This article will cover the main differences between the two. It will provide you with useful information you should know before you write a library. The examples in this article will use Android libraries but most of these principles apply to other types of libraries as well.</p><h3>Design Considerations</h3><p>The first difference between libraries and applications is the target audience. The audience of applications is the general public. Libraries, on the other hand, provide services to applications. Thus, their audience is application developers. As a result, the main consideration in designing a library is the developer experience.</p><p>The main components of user experience are UI, usability and performance. The developer experience is somewhat similar. The equivalents for developers being APIs, integration and performance. Yes, performance is important in every aspect of programming 🙂. This equivalence manifests in the design considerations that every component presents.</p><p>We will now look at each of these main considerations:</p><h3>APIs</h3><blockquote>“They say UI is like a joke — if you have to explain it, it’s not that good.” — Martin Leblanc</blockquote><p>The same rule applies to APIs. They have to be clear and simple.</p><p>Variables and methods names should be expressive, with consistent terminology.</p><p>Methods should do exactly what their name suggests with no side effects.</p><p>Position the methods, variables and constants in places where a developer would expect to find them. Make sure they are available when needed. Split APIs into different objects based on their responsibilities. Expose globally available APIs on a single static object. Position specific APIs on objects with the relevant responsibility. If an API is only available in a certain context, keep it in a dedicated class.</p><blockquote>A good API should be easy to use and hard to abuse.</blockquote><p>APIs have to be as hard as possible to use in any way other than intended. If some of the APIs are not always available, don’t expose them on a static object. Instead, expose them in an asynchronous way only when they are actually useful. This will make it impossible to use them when they aren’t available.</p><p>Here’s an example of an API of a library that provides video players:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b44560b403e7b9d8d866e082b879da61/href">https://medium.com/media/b44560b403e7b9d8d866e082b879da61/href</a></iframe><p>Another limitation that APIs may have is being constrained to a certain scope or context. To prevent abusing these types of APIs provide them as extensions to the relevant object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8fe6b601b8263b316c0a8752a684798/href">https://medium.com/media/a8fe6b601b8263b316c0a8752a684798/href</a></iframe><p>One more requirement that is common to both UI and APIs design is transparency. It is important that the application UI will show when the application is busy or some functionality is unavailable. Similarly, it’s important that the library API will let the developer know exactly what’s going on inside it.</p><ul><li>Expose states and events. There is a significant difference between state and events and selecting the wrong one will result in an inconvenient API. A good rule of thumb is if the developer can ask “is X currently Y?” then Y is a state of X, otherwise it’s probably an event.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ca39b52abcce50646423cde0bfb623f/href">https://medium.com/media/5ca39b52abcce50646423cde0bfb623f/href</a></iframe><ul><li>Make sure to provide a result for asynchronous operations.</li><li>Expose Errors. Application users should be notified about errors with a polite general message. Application developers on the other hand should be notified with a message that should be as informative as possible. Explain exactly what went wrong and why. State possible actions if available. Make sure to do it in the relevant place for the application developer to be able to take action. Note that choosing your own response to an error may be unexpected. Avoid returning a default value and delegate the reaction to the application. Reflect this behavior in the API’s name.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e9914a20162a572b7e82410cf69cdd3/href">https://medium.com/media/9e9914a20162a572b7e82410cf69cdd3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba17cfbf2e14df6403f422593434dc14/href">https://medium.com/media/ba17cfbf2e14df6403f422593434dc14/href</a></iframe><p>Reduce throwing exceptions only to the most basic misuse that makes the library useless. Handle exceptions internally and avoid crashing the host application at all cost.</p><p>APIs should be easy to extend.</p><ul><li>Avoid using methods with many parameters because adding another parameter is a breaking change. Instead, try to use the builder pattern that can easily be extended in a backwards compatible way. In Kotlin, use <a href="https://kotlinlang.org/docs/type-safe-builders.html">type safe builders</a> to create a <a href="https://en.wikipedia.org/wiki/Domain-specific_language">Domain Specific Language (DSL)</a> and achieve a very convenient API that is also very easy to extend.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbb2571dbd9cdf79e2fcac9f5de04960/href">https://medium.com/media/fbb2571dbd9cdf79e2fcac9f5de04960/href</a></iframe><p>** The full implementation of these APIs can be found <a href="https://gist.github.com/baruchn/304df94852c248d90cc6ce0e6a77774c">here</a>.</p><ul><li>Use enums instead of booleans even if you only have two options because enums are extendable.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f685db81e8901d9e54e693c812af78e/href">https://medium.com/media/2f685db81e8901d9e54e693c812af78e/href</a></iframe><h3>Integration</h3><p>The second developer experience component is integration. The integration, especially of the most basic use case, must be as easy and intuitive as possible. Application developers will often try to evaluate any potential library by implementing the basic integration. If it is too complicated they may decide not to use the library. In addition, the more complicated the integration is, the more likely it is that the application developer will get it wrong. Therefore, always go over the integration process and see if you can perform any of the integration steps internally. Merge integration steps whenever possible. It is better to provide default settings and behavior while keeping them open for customization if needed.</p><p>Naming is also very important to help guide the process. See example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f042b5efc07cc4fe2f2cdf59991538e/href">https://medium.com/media/9f042b5efc07cc4fe2f2cdf59991538e/href</a></iframe><p>Different development paradigms. Some developers prefer <a href="https://en.wikipedia.org/wiki/Declarative_programming">declarative programming</a> while others prefer <a href="https://en.wikipedia.org/wiki/Imperative_programming">imperative</a>. In practice it mostly applies to states. In the declarative programming style the developer would like to observe state changes and react to them. Developers who use imperative programming will need to be able to query the state. Thus expose state as both variables and change listeners. Kotlin’s <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-state-flow/">StateFlow</a>s are a perfect way to support both paradigms. Libraries that would like to maintain Java compatibility won’t be able to avoid listeners and variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ae6560ceaf4b8e8b13398b112aad234/href">https://medium.com/media/6ae6560ceaf4b8e8b13398b112aad234/href</a></iframe><h3>Performance</h3><p>The third component of the developer experience is performance. It’s pretty obvious that performance must be as good as possible. Any operation the library does will inevitably have some impact on the performance of the application. There are ways to make this impact easier to handle.</p><p>Let’s start with initialization. There are a few things to keep in mind about it.</p><p>The library must never perform any operations before it is initialized. It should provide full control over the initialization process and timing. Avoid performing actions that the application developer may not be aware of or have control over. This rule will allow application developers to integrate the library with a feature flag or some other condition knowing that when it’s off, the library has no effect. Common use cases are gradual release, A\B testing or disabling in case of an error that’s only discovered after distribution.</p><p>Do only the bare minimum during initialization. Move any other operation to a background thread as initialization is expected to be synchronous and run as early as possible — e.g. Application.onCreate() for Android.</p><p>Reduce the amount of resources that the initialization consumes. Especially mobile data as it may consume the user’s data plan. It’s common for a library to be initialized on every launch of the application but only used in certain scenarios. So initialization should be slim and light to avoid wasting resources when the library is initialized but not used.</p><p>If the library needs to perform some data or computation heavy operation, It’s better to provide a separate API for it with a clear name like “fetchImages”. Let application developers decide when to use it — they know what’s best for their application.</p><p>Sample project. It’s very important for documentation to provide not only written information and code samples but also a runnable project. This provides a much higher level of confidence in the ability to successfully integrate the library. It’s also advised to provide as many integration scenarios as possible. Provide them in the form of several projects,modules or flavors if necessary. Developers tend to follow the saying that “code never lies, comments (and documentation) sometimes do” and prefer to rely on a working sample for integration.</p><h3>Key Differences And Limitations</h3><h3>Initialization</h3><p>There are several ways in which the actual development process of a library is different from the one of an application. The first one is that unlike applications, libraries must be initialized. I’ve provided some general considerations for its design in the section about performance. Now I would like to provide some more practical advice. Initialization is important mostly to prepare the library for action. Use it to initialize services that are absolutely necessary for the library to function like dependency injection. In addition, perform operations that the library would like to perform as soon as possible like fetching configuration. That, obviously, must be executed on a separate thread and be as small as possible.</p><p>Another role of initialization is to receive global configuration from the application that may be required throughout the entire lifecycle of the library. On Android, it is also used to obtain context. <br>On Android, a library can initialize itself using a Content Provider as the good guys from Firebase describe in <a href="https://firebase.blog/posts/2016/12/how-does-firebase-initialize-on-android">this blog post from 2016</a>. Later on Google released the <a href="https://developer.android.com/topic/libraries/app-startup">Androidx App Startup</a> library to facilitate this method and provide some additional control. As mentioned before in the “Performance” section, I believe that even though this method exists and is very convenient, libraries shouldn’t use it and I strongly recommend libraries to use manual initialization.</p><h3>Code Visibility</h3><p>One thing that library developers should be more aware of than application developers is code visibility. Making big parts of application code public is a common practice and is <a href="https://discuss.kotlinlang.org/t/a-bit-about-picking-defaults/1418">the reason (excuse) why it’s the default access modifier in Kotlin</a>. This is not the case for library development. Any public code in a library may be consumed by the host application. Therefore the access modifiers of every bit of code require careful consideration. <br>A common source of accidental exposure of internal code is utilities and extensions. Pay extra attention to the scope in which they should be valid.<br>One way to catch those before a release, besides lint, is to go over the documentation that is generated from the code and check for anything that doesn’t belong.</p><h3>Monitoring And Configuration</h3><p>The amount of control the developer has over the release cycle is different between an application and a library. When releasing an application and then realizing that changes have to be made, the developer can always release a new version. Adoption may not be very fast but clients do update eventually and applications can <a href="https://developer.android.com/guide/playcore/in-app-updates">request or even force the user to update</a>. This is not the case for a library. Once a library goes live, the developer has very little control over it and over the developers who embed it into their applications. They may never upgrade from version 1.0.0. And even if they do upgrade it takes much longer and is out of the library developer’s control. Keep as much control over the library as possible by providing remote configuration from the server. As mentioned before, this config should be synced to the library on initialization and cached for future runs. It should contain parameters that can be easily changed and have a significant effect on the functionality of the library such as feature flags, API URLs, etc.</p><p>In addition, just like application developers, library developers also need to monitor usage and detect issues. The first and most obvious solution that comes to mind is to simply use a library for that. But there is a catch. All of these solutions, that I know of, are designed to work as a single tennant. This means that if, for example, a library integrates Google Analytics and the application that embeds that library also uses Google Analytics, only one of them can receive data. In this situation the library is either blocking the host application from receiving their analytics data or it receives nothing. This limitation forces libraries to develop in-house solutions for both monitoring usage and detecting issues like crashes or ANRs. How to do that is an article in and of itself. <br>Here’s a response I got from Firebase regarding usage inside libraries:</p><blockquote>“Firebase SDKs are not intended for library projects. The features available on Firebase were integrated in an application level and not on a per module or per library basis so, the use case for having this integrated on a library project is not possible or not supported.”</blockquote><h3>Dependencies</h3><p>Unlike applications that follow the “don’t reinvent the wheel” principle, library developers should adopt the opposite approach and keep dependencies to a bare minimum. On Android the main reason is that the application that will be using the library may rely on the same dependencies. In this case, only one instance of the dependency will actually be present at runtime. Gradle will perform a <a href="https://docs.gradle.org/current/userguide/dependency_resolution.html">dependency resolution</a> process that will most likely end up in either the app or the library running a different version of that dependency than the one it was developed with. This may lead to unexpected behavior and crashes if the versions aren’t compatible, especially in the case of two different major versions. The exception to this rule are libraries that generate their product at build time and don’t actually run any of their own code at runtime. This is usually the case with libraries that provide database abstractions or libraries that perform code manipulation using annotation processing.</p><p>Adding dependencies also increases the size of the library, sometimes significantly. A large size is a common reason for application developers to decide not to use a certain library.</p><h3>Modularization (Android)</h3><p>We are constantly being told to <a href="https://medium.com/google-developer-experts/modularizing-android-applications-9e2d18f244a0">modularize our applications</a>. There are <a href="https://proandroiddev.com/build-a-modular-android-app-architecture-25342d99de82">many advantages to modularization</a>, like shorter build times, testability, code reuse, and more. Google even prepared <a href="https://developer.android.com/studio/projects/index.html#ApplicationModules">different types of modules</a> to make the lives of application developers easier. But what about library development? There seem to be no official guidelines or support for modularization of libraries.</p><p>In practice, there is a big difference between modules in applications and libraries. While in applications modules are being packaged automatically into the apk (or bundle), this is not the case with jars (or aars). There are two ways to include more than one module in a compiled library.</p><p>One is to compile every dependency module to a jar (or aar) and import it as a file during the build process. This will result in the code of the dependencies being compiled as part of the original module. This approach makes sharing dependencies between two modules a big problem. It causes namespace collisions if the same classes are present in two libraries at the same time. This problem may be resolved by renaming the dependencies using a process called shadowing but it results in more than one instance of the same code.</p><p>Another way to import a module is to publish it as a separate library and use it as a dependency. In this case, Gradle will handle the version resolution and the code may be shared. Unfortunately it creates additional challenges for version management and prolongs the publishing process.</p><p>Neither way is convenient and both require a customized project structure to be able to depend on the code of the module in development and on the compiled module for publishing (depending on a file or a remote library). Also, they both complicate the publishing process. In addition, adding a new module requires more work and the more modules the project contains the more complicated and fragile it becomes.<br>The bottom line is that modularization of a library adds much more work and complexity than modularization of an application. I would suggest using modules for libraries only in order to share code between different services that can be used separately. In this case there’s no other choice and each service should be a separate library and therefore a separate module in the project. They can share code by using a shared module that is published and consumed as a dependency by the services (the second option presented above). Such a module is usually called “basement”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*3uUqvBW5__EAii62dhCgGw.png" /><figcaption>A basement library dependency in Google Play Services SDK.</figcaption></figure><p>As mentioned, this will also require the project to have at least two flavors — one for development and one for publishing. In the development flavor the services depend on the shared code as a module in the project. In the publishing one they will depend on the shared module as a Gradle dependency.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bac96b21c876fc09ad1c8f3f68a3c65/href">https://medium.com/media/4bac96b21c876fc09ad1c8f3f68a3c65/href</a></iframe><p>Notice that versioning of a library that has many modules and shares at least one of them can be tricky. They should either use the same version and be published all together or use a <a href="https://docs.gradle.org/current/userguide/platforms.html#sub:bom_import">Bill of Materials</a> (BOM) to support different versions of the services. <br>Use <a href="https://docs.gradle.org/current/userguide/custom_plugins.html">custom Gradle plugins</a> to share configuration between the modules to avoid duplicating the Gradle configuration.</p><p>My early attempts at library modularization can be found in <a href="https://medium.com/@baruhn/android-library-modular-architecture-5a20d53c8faf">this article</a>.</p><h3>Compatibility</h3><p>When developing an application, it is obvious that staying up to date with the latest versions of the programming language, build tools, and dependencies is a best practice. It is much less obvious when developing a library. In library development it is important that the code remains compatible with as many applications as possible. Using the latest versions may create compatibility issues with older ones. For example, targeting a higher Android SDK version than the host application will result in a build exception.</p><p>Another compatibility issue that may arise is language compatibility. For example, Kotlin’s suspending functions and other features won’t be available in a Java application. Therefore, every release must be tested against the lowest supported setup and all supported languages.</p><h3>Summary</h3><p>I hope that this article sums up what in my opinion are the most important things that application developers should keep in mind when approaching library development. I tried to give a brief presentation of the main ones. Note that every one of them can be the topic of a separate article. Before writing a library for the first time, every developer should get a deeper understanding of the differences in order to avoid making mistakes and deliver a quality product. Hope you find it useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82a74875ded3" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/mobile-library-development-its-not-another-application-82a74875ded3">Mobile Library Development — It’s Not Another Application</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Library Modular Architecture]]></title>
            <link>https://medium.com/@baruhn/android-library-modular-architecture-5a20d53c8faf?source=rss-5cc6824dad1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a20d53c8faf</guid>
            <category><![CDATA[android-libraries]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[library-design]]></category>
            <dc:creator><![CDATA[Baruch Nurilov]]></dc:creator>
            <pubDate>Sun, 10 May 2020 11:23:12 GMT</pubDate>
            <atom:updated>2020-05-11T11:59:23.560Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article proposes a way to take advantage of modules when developing libraries. It explains the main challenges and provides solutions.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1kDwA0aqbh0EmXL_BR2XQ.png" /></figure><ul><li><em>This article assumes you are generally familiar with the </em><a href="https://docs.gradle.org/current/userguide/multi_project_builds.html"><em>Gradle modules</em></a><em> and </em><a href="https://developer.android.com/studio/projects/android-library"><em>Android library modules</em></a><em> in particular.</em></li></ul><p>We are constantly being told to <a href="https://medium.com/google-developer-experts/modularizing-android-applications-9e2d18f244a0">modularize our applications</a>. There are <a href="https://proandroiddev.com/build-a-modular-android-app-architecture-25342d99de82">many advantages to modularization</a>, like shorter build times, testability, code reuse, and more. Google even prepared <a href="https://developer.android.com/studio/projects/index.html#ApplicationModules">different types of modules</a> to make our lives as application developers easier. But what if we develop libraries? There seem to be no official guidelines or support for modularized libraries. Can we also get all of the advantages of modularization? Maybe at least some of them? This article will provide you with a general modularized Android library architecture and some key information you will need to build or refactor a modularized library. For a complete example of a modularized Android library, see <a href="https://github.com/oriient/backend-logger">this sample project</a>.</p><h3>Should We Modularize a Library?</h3><p>I think that one of the most important advantages of modularization is the ability to force the correct structure of dependencies and access control inside our code during the development process, especially since Kotlin omitted the ‘package’ access modifier (if you miss it as much as I do, please vote to add it <a href="https://youtrack.jetbrains.com/issue/KT-29227">here</a>). Modules allow the compiler/linter to make sure that different parts of our code don’t really depend on each other more than they should. Therefore, I strongly believe that any code we write should be modularized to follow proper code architecture guidelines, and libraries are no exception.</p><p>Nevertheless, there is a very important thing we should keep in mind before deciding to go for it:</p><blockquote>Android libraries (unlike pure Kotlin ones) cannot be provided to other libraries at compile time in the form of modules or files. They can be provided to other libraries only through a repository (as a Gradle dependency).</blockquote><p>This means that we cannot have a single Android library project composed of several Android library modules without publishing every module separately. If you have two Android library modules and put this code in the build.gradle of the first library,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e36ac562a01dd87f1a8304be027d0575/href">https://medium.com/media/e36ac562a01dd87f1a8304be027d0575/href</a></iframe><p>the resulting .aar file won’t contain the code of the second module (android-library-2).</p><p>I believe this limitation shouldn’t prevent us from modularizing our libraries when we create new ones, but this limitation creates another big task to consider when refactoring an existing one. The main reason is that many of the most common dependencies like Retrofit, Room, and others will only work in Android library modules, and will have to be replaced. Depending on the size and complexity of the existing code base, replacing these dependencies may prove to be a challenging task that typically shouldn’t be carried out all at once.</p><p>The good news is that there are good replacements for most of them that don’t depend on Android and in most cases, this process can be carried out one dependency at a time.</p><p>In addition, using modules that don’t depend on Android will make our library more easily convertible to a multiplatform one, but that’s a topic for a different article.</p><h3>OK, How?</h3><p>The basic modularization architecture I suggest relies on dividing the code into several layers. The dependencies between the layers only go one way so that code can only depend on other code in the same layer or in the layers below, but not in layers above. Due to the aforementioned limitation, only one layer will be an Android library module, which we will also use eventually to distribute our library - the rest of the modules will be pure Kotlin modules.</p><p>The layers are:</p><ol><li>Utilities — this layer includes code which doesn’t depend on any other code. It includes, for example, static utility functions and build time data (we can’t depend on BuildConfig anymore since it’s an Android feature).</li><li>System Services — this layer includes all the services which can only be provided by the system like storage, location, etc. This entire layer will be implemented in a single Android library module to comply with the single Android library module limitation. To be sure we don’t depend on any OS code and prepare for multiplatform, the interfaces of this layer will be defined in a different, pure Kotlin, module.</li><li>Services — this layer includes logic-less services required by the SDKs’ business logic. It includes, for example, REST, database, and repositories. The services may depend on each other, but to ensure that no service is using another service before it has been initialized, they must be passed to each other only through the constructor. The initialization of the services is done by the Dependency Injection (DI) mechanism in the next layer. Every service should be implemented in a separate (pure Kotlin) module.</li><li>Dependency Injection (DI) — this layer is responsible for instantiating the services in the correct order and providing them to the Business Logic layer. It uses reflection to instantiate the actual implementation of the services since the implementations shouldn’t be accessible out of the modules. We will discuss more about reflection in the next chapter.</li><li>Business logic — this layer includes the unique business logic of the specific library and the main public APIs. It is also responsible for making sure that the initialization of the DI will always happen before any of the logic is being used. After all the services have been initialized, the business logic is free to use them in any way it requires.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWCMO0sbrYUu_ueC9_k6pg.png" /></figure><p>Some key points required to understand this separation:</p><ul><li>The business logic depends on the services and the utils only through the DI and should not instantiate any of them directly.</li><li>The implementation of the services and utils shouldn’t be known to any part of the code other than the DI. They should only be exposed through interfaces. The business logic may request a specific type of implementation though.</li></ul><h3>What Should Be Taken Into Consideration?</h3><ul><li>The main difference between application modularization and library modularization is, as I mentioned earlier, that dependencies between different library modules in the same library project don’t come ‘out of the box’. To get the code of the modules as part of our .aar, we need to copy the .jar files of the modules into the libs folder of the Android module before it is being assembled. To do this, just add this code to the `build.gradle` of every non-android module:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1246589632f1ff911ebd70cb2fde8dc/href">https://medium.com/media/c1246589632f1ff911ebd70cb2fde8dc/href</a></iframe><ul><li>To make adding modules easier, I would suggest putting all the configurations which are common to all the Kotlin modules in the main `build.gradle` like this:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4398893a0bebaadc4b44fecf22e2d848/href">https://medium.com/media/4398893a0bebaadc4b44fecf22e2d848/href</a></iframe><ul><li>Note that many modules may cause your project to appear messy. To keep the modules in order, make sure to name them according to the layer to which they belong, e.g. ‘services-database’.</li><li>Defining the API in a pure Kotlin module means that we can’t obtain an Android context from the host application. To overcome this limitation we’ll be using a content provider to obtain the context ourselves. See <a href="https://firebase.googleblog.com/2016/12/how-does-firebase-initialize-on-android.html">this</a> blog post and my sample project (at the end of the article) for more details.</li><li>Reflection has been chosen as a last resort because Kotlin doesn’t provide any access granularity other than public, internal, and private. This fact makes reflection the only way to get access to code which should be accessible for other modules but not for everyone. Another solution would be to make the implementations of the services public, but I believe it is a very bad practice and I won’t implement any architecture which forces me to do so. Reflection is not easy to master, it can be a nightmare to debug and requires extra effort when obfuscation is used. The good news is that you mostly deal with it during the initial setup.</li><li>Another issue with reflection is that it introduces a performance impact. Unfortunately, there’s no way around it. Luckily this impact isn’t very big and only affects the first initialization, which makes it much less noticeable.</li><li>There are a couple of Proguard rules which can help to deal with the obfuscation of classes that are instantiated by reflection. These rules make Proguard (R8) obfuscate strings which match class names so the reflection will keep working:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f71d966f33a6d5a918ddac0e8e4006a/href">https://medium.com/media/5f71d966f33a6d5a918ddac0e8e4006a/href</a></iframe><ul><li>The publication of such a library is also a little different. Since the modules are added through .jar files, their dependencies won’t be added automatically to the .pom. The simplest way to overcome this issue is to collect all the dependencies in the extensions of the root project while building the modules. Then, when publishing, filter out duplicates and add them to the .pom.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c4366f0a52d9b7c569b50d20e66dc61/href">https://medium.com/media/9c4366f0a52d9b7c569b50d20e66dc61/href</a></iframe><ul><li>As mentioned earlier, a <a href="https://github.com/oriient/backend-logger">sample project</a> is available with an example of this implementation.</li></ul><h3>So What’s Next?</h3><p>Multiplatform!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a20d53c8faf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>