<?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 David Cruz on Medium]]></title>
        <description><![CDATA[Stories by David Cruz on Medium]]></description>
        <link>https://medium.com/@davthecoder?source=rss-4c1be6bf35fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lJSpd-u4sbNmYx00ExCSRQ.jpeg</url>
            <title>Stories by David Cruz on Medium</title>
            <link>https://medium.com/@davthecoder?source=rss-4c1be6bf35fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:45:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davthecoder/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[I Built a Tarot App, Shipped It on Google Play, and Here Is Its Architecture]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">This article provides a practical demonstration of clean architecture, Riverpod, offline-first design, and multi-language support within a&#x2026;</p><p class="medium-feed-link"><a href="https://davthecoder.medium.com/i-built-a-tarot-app-shipped-it-on-google-play-and-here-is-its-architecture-1246b09ff117?source=rss-4c1be6bf35fc------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://davthecoder.medium.com/i-built-a-tarot-app-shipped-it-on-google-play-and-here-is-its-architecture-1246b09ff117?source=rss-4c1be6bf35fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1246b09ff117</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[tarot-app]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[source-code]]></category>
            <dc:creator><![CDATA[David Cruz]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 12:00:48 GMT</pubDate>
            <atom:updated>2026-04-06T13:25:31.133Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Building High-Performance iOS Financial Charts with Rust and SwiftUI]]></title>
            <link>https://davthecoder.medium.com/building-high-performance-ios-financial-charts-with-rust-and-swiftui-c09a4d4881b1?source=rss-4c1be6bf35fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c09a4d4881b1</guid>
            <category><![CDATA[high-performance]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[David Cruz]]></dc:creator>
            <pubDate>Tue, 14 Oct 2025 22:59:32 GMT</pubDate>
            <atom:updated>2025-10-14T22:59:32.801Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How combining Rust’s computational power with SwiftUI’s elegance creates a blazing-fast financial charting app</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GqZg9Ix_p8WHVnLc5dTCXw.png" /></figure><h3>The Challenge: Performance Meets User Experience</h3><p>When building financial applications, developers face a fundamental tension. On one hand, users expect buttery-smooth 60 FPS animations and real-time updates. On the other hand, calculating technical indicators like RSI, MACD, and moving averages across thousands of data points is computationally expensive. This dilemma is especially true when you need to recalculate these indicators on every price update from a WebSocket stream.</p><p>Traditional approaches force you to choose between performance and developer experience. You can write everything in a low-level language like C++ for maximum speed, sacrificing the elegant declarative UI patterns of modern frameworks. For an excellent developer experience, you can also use pure Swift/SwiftUI, albeit with the performance cost of a garbage-collected language.</p><p>What if you didn’t have to choose?</p><h3>The Solution: Hybrid Architecture</h3><p>The Financial-RustAndSwift project demonstrates a third path by combining the strengths of both worlds. Rust handles all computationally intensive calculations, while SwiftUI provides the beautiful, reactive user interface. The result is an application that delivers native performance where it matters most while maintaining the developer-friendly patterns that make iOS development enjoyable.</p><p>The architecture creates a clear separation of concerns. At the bottom layer, Rust implementations of technical indicators run with zero garbage collection overhead and benefit from SIMD autovectorization. Above that, a thin C FFI bridge connects the Rust code to Swift. Finally, SwiftUI manages the presentation layer with its reactive data flow and declarative syntax.</p><h3>Real Performance Gains: The Numbers Don’t Lie</h3><p>The performance improvements from this hybrid approach are substantial and measurable. When processing one thousand candlesticks, the Rust implementations consistently outperform pure Swift alternatives by factors of two to four and a half.</p><p>The Simple Moving Average calculation runs in just 0.8 milliseconds with Rust compared to 2.1 milliseconds in pure Swift, achieving a 2.6x speedup. The Exponential Moving Average completes in 0.6 milliseconds versus 1.8 milliseconds, a 3.0x improvement. The more complex calculations show even more dramatic gains. The Relative Strength Index drops from 5.4 milliseconds to just 1.2 milliseconds, achieving a 4.5x speedup. The MACD indicator, which combines multiple moving averages, sees a similar 4.5x improvement, running in 1.5 milliseconds compared to 6.8 milliseconds in pure Swift.</p><p>These improvements stem from several factors working together. Rust’s lack of garbage collection eliminates unpredictable pauses during calculations. The compiler&#39;s aggressive optimisation, including SIMD vectorisation, allows calculations to process multiple data points simultaneously. Efficient memory layout and cache usage reduce the time spent waiting for data from RAM. Finally, Rust’s zero-cost abstractions mean that writing clean, maintainable code doesn’t sacrifice runtime performance.</p><h3>Deep Dive: The Rust Implementation</h3><p>At the heart of the performance story is the Rust implementation of technical indicators. The code lives in the indicators.rs file and demonstrates how systems-level programming can be both safe and fast.</p><p>Consider the implementation of the Simple Moving Average, one of the most fundamental technical indicators. The Rust version is remarkably straightforward yet highly optimised.</p><pre>pub fn calculate_sma(data: &amp;[f32], period: usize) -&gt; Vec&lt;f32&gt; {<br>    let mut result = Vec::with_capacity(data.len());<br>    <br>    if data.len() &lt; period {<br>        return result;<br>    }<br>    <br>    // Fill initial values with NaN<br>    for _ in 0..period - 1 {<br>        result.push(f32::NAN);<br>    }<br>    <br>    // Calculate SMA for each window<br>    for i in period - 1..data.len() {<br>        let sum: f32 = data[i - period + 1..=i].iter().sum();<br>        result.push(sum / period as f32);<br>    }<br>    <br>    result<br>}</pre><p>This implementation makes several key choices that contribute to its performance. Pre-allocating the result vector with the exact capacity needed eliminates reallocation overhead. Using slicing operations leverages Rust&#39;s optimised iterator implementations. The compiler can automatically vectorise the sum calculation and process multiple values per CPU instruction. Most importantly, everything happens without any heap allocations in the hot loop.</p><p>The Exponential Moving Average builds on this foundation with a more sophisticated algorithm that gives more weight to recent prices:</p><pre>pub fn calculate_ema(data: &amp;[f32], period: usize) -&gt; Vec&lt;f32&gt; {<br>    let mut result = Vec::with_capacity(data.len());<br>    <br>    if data.len() &lt; period {<br>        return result;<br>    }<br>    <br>    let multiplier = 2.0 / (period + 1) as f32;<br>    <br>    // Initialize with SMA<br>    let initial_sma: f32 = data[..period].iter().sum::&lt;f32&gt;() / period as f32;<br>    <br>    for _ in 0..period - 1 {<br>        result.push(f32::NAN);<br>    }<br>    result.push(initial_sma);<br>    <br>    // Calculate EMA recursively<br>    for i in period..data.len() {<br>        let ema = (data[i] - result[i - 1]) * multiplier + result[i - 1];<br>        result.push(ema);<br>    }<br>    <br>    result<br>}</pre><p>The EMA calculation demonstrates one of Rust’s key advantages: the recursive nature of the algorithm means each calculation depends on the previous result, which could be problematic in some languages. However, Rust’s ownership system ensures memory safety without runtime checks, and the tight loop with simple arithmetic operations allows the compiler to generate highly efficient machine code.</p><h3>Bridging Two Worlds: The FFI Layer</h3><p>The magic that connects Rust’s performance to Swift’s elegance happens through the Foreign Function Interface. The FFI implementation in lib.rs carefully manages the boundary between Rust’s memory model and Swift’s requirements.</p><p>The bridge uses a custom structure to safely pass arrays across the FFI boundary:</p><pre>#[repr(C)]<br>pub struct FloatArray {<br>    pub data: *mut f32,<br>    pub len: usize,<br>    pub capacity: usize,<br>}</pre><p>The repr(C) annotation ensures that Rust uses the same memory layout as C, making the structure compatible with Swift. The structure contains a pointer to the data, along with length and capacity information that Swift needs to properly interpret the array.</p><p>Each indicator function gets wrapped with FFI-safe code that handles the marshalling between Swift and Rust:</p><pre>#[no_mangle]<br>pub unsafe extern &quot;C&quot; fn calculate_sma_ffi(<br>    data: *const f32,<br>    len: usize,<br>    period: usize,<br>) -&gt; FloatArray {<br>    if data.is_null() || len == 0 {<br>        return FloatArray {<br>            data: std::ptr::null_mut(),<br>            len: 0,<br>            capacity: 0,<br>        };<br>    }<br>    <br>    let slice = std::slice::from_raw_parts(data, len);<br>    let result = calculate_sma(slice, period);<br>    <br>    let mut result_boxed = result.into_boxed_slice();<br>    let ptr = result_boxed.as_mut_ptr();<br>    let len = result_boxed.len();<br>    let capacity = len;<br>    <br>    std::mem::forget(result_boxed);<br>    <br>    FloatArray {<br>        data: ptr,<br>        len,<br>        capacity,<br>    }<br>}</pre><p>This FFI function demonstrates the careful dance required at language boundaries. The no_mangle attribute prevents Rust from changing the function name, ensuring Swift can find it. The unsafe extern “C” declaration marks this functionality as a C-compatible function that can be called across the FFI boundary. Inside, the code carefully converts between raw pointers and Rust’s safe slice types, performs the calculation, then hands ownership of the result back to Swift by forgetting the boxed slice after extracting its pointer.</p><p>The Swift side provides a clean, idiomatic interface that hides this complexity:</p><pre>@_silgen_name(&quot;calculate_sma_ffi&quot;)<br>private static func calculate_sma_ffi(<br>    _ data: UnsafePointer&lt;Float&gt;,<br>    _ len: Int,<br>    _ period: Int<br>) -&gt; FloatArray</pre><pre>static func calculateSMA (data: [Float], period: Int) -&gt; [Float] {<br>    guard !data.isEmpty &amp;&amp; period &gt; 0 &amp;&amp; period &lt;= data.count else {<br>        return []<br>    }<br>    <br>    let result = data.withUnsafeBufferPointer { bufferPtr in<br>        calculate_sma_ffi(bufferPtr.baseAddress!, data.count, period)<br>    }<br>    <br>    guard result.data != nil else {<br>        return []<br>    }<br>    <br>    let array = Array(UnsafeBufferPointer(<br>        start: result.data,<br>        count: result.len<br>    ))<br>    <br>    free_float_array(result)<br>    <br>    return array<br>}</pre><p>This Swift wrapper handles all the unsafe pointer operations internally while exposing a completely safe interface to the rest of the application. The withUnsafeBufferPointer method temporarily provides direct access to the array’s memory, avoiding any copying. After retrieving the result, the code creates a new Swift array from the Rust-allocated memory, then explicitly frees the Rust memory to prevent leaks.</p><h3>Real-Time Data: The WebSocket Integration</h3><p>Performance calculations mean nothing without data to process. The application connects to Binance’s WebSocket API to receive real-time trade data for Bitcoin against USDT. The BinanceWebSocketService demonstrates how to integrate live financial data into a SwiftUI application.</p><p>The service maintains its state using published properties that automatically trigger UI updates:</p><pre>class BinanceWebSocketService: ObservableObject {<br>    @Published var connectionState: ConnectionState = .disconnected<br>    @Published var latestTrade: TradeData?<br>    <br>    private var webSocketTask: URLSessionWebSocketTask?<br>    private let symbol: String<br>    <br>    init(symbol: String = &quot;btcusdt&quot;) {<br>        self.symbol = symbol.lowercased()<br>    }<br>    <br>    func connect() {<br>        let url = URL(string: &quot;wss://stream.binance.com:9443/ws/\(symbol)@trade&quot;)!<br>        webSocketTask = URLSession.shared.webSocketTask(with: url)<br>        <br>        connectionState = .connecting<br>        webSocketTask?.resume()<br>        <br>        receiveMessage()<br>    }<br>}</pre><p>The connection process uses URLSession’s native WebSocket support, avoiding external dependencies. The service connects to Binance’s trade stream endpoint, which provides individual trade data as it happens on the exchange. Each trade includes the price, quantity, timestamp, and whether it was a buy or sell order.</p><p>The message-receiving loop demonstrates Swift’s modern async patterns:</p><pre>private func receiveMessage() {<br>    webSocketTask?.receive { [weak self] result in<br>        guard let self = self else { return }<br>        <br>        switch result {<br>        case .success(let message):<br>            switch message {<br>            case .string(let text):<br>                self.handleMessage(text)<br>            case .data(let data):<br>                if let text = String(data: data, encoding: .utf8) {<br>                    self.handleMessage(text)<br>                }<br>            @unknown default:<br>                break<br>            }<br>            <br>            // Keep receiving messages<br>            self.receiveMessage()<br>            <br>        case .failure(let error):<br>            print(&quot;WebSocket error: \(error)&quot;)<br>            self.connectionState = .disconnected<br>        }<br>    }<br>}</pre><p>The recursive nature of receiveMessage creates a continuous loop that processes messages as they arrive. This pattern ensures the connection stays active and responsive without blocking the main thread. When a message arrives, the code decodes the JSON into a structured TradeData model that the rest of the application can use.</p><h3>Orchestrating Everything: The Data Manager</h3><p>The FinancialDataManager acts as the central coordinator, bringing together WebSocket data, Rust calculations, and UI state management. This class demonstrates how to structure a complex SwiftUI application with multiple data sources and heavy computations.</p><p>The manager maintains all the state needed for the UI:</p><pre>class FinancialDataManager: ObservableObject {<br>    @Published var chartData: ChartData?<br>    @Published var currentPrice: String = &quot;0.00&quot;<br>    @Published var priceChange: String = &quot;0.00&quot;<br>    @Published var priceChangePercent: String = &quot;0.00&quot;<br>    <br>    private let webSocketService: BinanceWebSocketService<br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br>    <br>    init() {<br>        self.webSocketService = BinanceWebSocketService(symbol: &quot;btcusdt&quot;)<br>        setupSubscriptions()<br>        loadInitialData()<br>        webSocketService.connect()<br>    }<br>}</pre><p>The published properties automatically trigger UI updates whenever they change, following SwiftUI’s reactive programming model. The Combine framework handles subscriptions to the WebSocket service, creating a clean data flow from network events to UI updates.</p><p>When new trade data arrives, the manager processes it and recalculates all indicators:</p><pre>func calculateIndicators() {<br>    guard let candles = chartData?.candles, !candles.isEmpty else { return }<br>    <br>    let closePrices = candles.map { $0.close }<br>    <br>    // All calculations use Rust for maximum performance<br>    let sma20 = TechnicalIndicators.calculateSMA(data: closePrices, period: 20)<br>    let sma50 = TechnicalIndicators.calculateSMA(data: closePrices, period: 50)<br>    let ema12 = TechnicalIndicators.calculateEMA(data: closePrices, period: 12)<br>    let ema26 = TechnicalIndicators.calculateEMA(data: closePrices, period: 26)<br>    let rsi = TechnicalIndicators.calculateRSI(data: closePrices, period: 14)<br>    let macd = TechnicalIndicators.calculateMACD(data: closePrices)<br>    <br>    // Update chart data with calculated indicators<br>    DispatchQueue.main.async {<br>        self.chartData?.sma20 = sma20<br>        self.chartData?.sma50 = sma50<br>        self.chartData?.ema12 = ema12<br>        self.chartData?.ema26 = ema26<br>        self.chartData?.rsi = rsi<br>        self.chartData?.macd = macd<br>    }<br>}</pre><p>The code extracts close prices from the candlestick data, then calls each Rust-powered indicator function. The calculations happen on a background thread to avoid blocking the UI, with results dispatched back to the main thread for display. Because Rust handles the heavy lifting, these recalculations complete in just a few milliseconds even with thousands of data points.</p><h3>Rendering at 60 FPS: The Chart Implementation</h3><p>The chart rendering demonstrates how to build high-performance visualisations in SwiftUI. Rather than using standard SwiftUI views, which can be slow for complex graphics, the implementation uses the Canvas API for direct, efficient drawing.</p><p>The candlestick chart shows the core rendering approach:</p><pre>struct CandlestickChartView: View {<br>    let chartData: ChartData<br>    let width: CGFloat<br>    let height: CGFloat<br>    <br>    var body: some View {<br>        Canvas { context, size in<br>            drawCandles(context: context, size: size)<br>            if chartData.showSMA20 {<br>                drawIndicator(context: context, size: size, <br>                             data: chartData.sma20, <br>                             color: .blue)<br>            }<br>            // Draw other indicators...<br>        }<br>        .frame(width: width, height: height)<br>    }<br>    <br>    private func drawCandles(context: GraphicsContext, size: CGSize) {<br>        let candleWidth = size.width / CGFloat(chartData.candles.count)<br>        <br>        for (index, candle) in chartData.candles.enumerated() {<br>            let x = CGFloat(index) * candleWidth<br>            let color = candle.close &gt;= candle.open ? <br>                       ChartColors.bullish : ChartColors.bearish<br>            <br>            // Draw high-low line<br>            let highY = mapPriceToY(price: candle.high, size: size)<br>            let lowY = mapPriceToY(price: candle.low, size: size)<br>            context.stroke(<br>                Path { path in<br>                    path.move(to: CGPoint(x: x + candleWidth/2, y: highY))<br>                    path.addLine(to: CGPoint(x: x + candleWidth/2, y: lowY))<br>                },<br>                with: .color(color),<br>                lineWidth: 1<br>            )<br>            <br>            // Draw open-close body<br>            let openY = mapPriceToY(price: candle.open, size: size)<br>            let closeY = mapPriceToY(price: candle.close, size: size)<br>            let rect = CGRect(<br>                x: x + candleWidth * 0.2,<br>                y: min(openY, closeY),<br>                width: candleWidth * 0.6,<br>                height: abs(openY - closeY)<br>            )<br>            context.fill(Path(rect), with: .color(color))<br>        }<br>    }<br>}</pre><p>The Canvas API provides direct access to the graphics context, allowing fine-grained control over rendering. Each candlestick consists of a vertical line showing the high and low prices, with a thicker body showing the open and close. The colour code makes bullish candles (where close is greater than open) visually distinct from bearish ones.</p><p>The coordinate mapping function transforms price values into screen coordinates:</p><pre>private func mapPriceToY(price: Float, size: CGSize) -&gt; CGFloat {<br>    let priceRange = chartData.maxPrice - chartData.minPrice<br>    let priceOffset = price - chartData.minPrice<br>    let normalizedPosition = CGFloat(priceOffset / priceRange)<br>    return size.height * (1 - normalizedPosition)<br>}</pre><p>This function inverts the Y axis because screen coordinates increase downward while prices increase upward. Normalisation ensures that the chart automatically scales to show all the data, regardless of the price range.</p><h3>Key Learnings and Insights</h3><p>Building this hybrid application revealed several important insights about combining Rust and Swift. The FFI boundary requires careful attention to memory management, but once properly implemented, it becomes invisible to the rest of the codebase. The key is to encapsulate all unsafe operations in a thin layer that exposes safe, idiomatic Swift interfaces.</p><p>The performance benefits of Rust are not theoretical. In real-world usage with live data streaming and constant recalculations, the difference between smooth 60 FPS rendering and janky, stuttering animations comes down to these milliseconds. When you need to recalculate indicators on every price update, having calculations complete in under 2 milliseconds instead of 6–8 milliseconds is the difference between responsive and sluggish.</p><p>SwiftUI’s reactive programming model pairs beautifully with high-performance computations. The published properties and Combine framework create a clean separation between data processing and presentation. Heavy calculations can happen on background threads without complicating the view code.</p><p>This method of using a static library is different from Android&#39;s dynamic library model, but it works well for iOS. The static libraries get linked directly into the application binary, eliminating the need to bundle separate library files. This simplifies deployment and reduces the risk of version mismatches, though it does increase the overall binary size.</p><h3>Beyond Performance: Architecture Benefits</h3><p>The hybrid architecture delivers benefits beyond raw speed. The clear separation between calculation logic (Rust) and presentation logic (Swift) makes the codebase more maintainable. Changes to indicator algorithms don’t require touching any UI code. Similarly, UI redesigns don’t risk breaking calculation logic.</p><p>Testing becomes more straightforward with this separation. The Rust code can be tested independently with comprehensive unit tests that run quickly and reliably. The Swift side can use preview providers and UI tests without needing to mock complex calculations.</p><p>The architecture also provides flexibility for future enhancements. Adding new indicators means implementing them in Rust, where performance matters most, then exposing them through the FFI layer. The pattern established by existing indicators makes this process straightforward.</p><h3>The Best of Both Worlds</h3><p>This project demonstrates that native performance and modern UI frameworks are not mutually exclusive. By leveraging Rust for computational work and Swift for user interfaces, you can build applications that are both blazingly fast and delightful to use.</p><p>The approach scales well beyond financial applications. Any iOS app with significant computational requirements, from image processing to machine learning to scientific calculations, could benefit from this hybrid architecture. The key is identifying the performance-critical paths and implementing them in Rust while keeping the user-facing code in Swift.</p><p>The tooling and ecosystem support for Rust-Swift interop continue to improve. Building for multiple architectures and platforms becomes more streamlined with each release. For developers willing to work across languages, the reward is applications that deliver exceptional performance without sacrificing developer experience.</p><p>The complete source code and build instructions are available in the GitHub repository <a href="https://github.com/davthecodercom/Financial-RustAndswift">https://github.com/davthecodercom/Financial-RustAndswift</a>, making it easy to explore this architecture pattern in depth or use it as a foundation for your projects. Whether you’re building financial applications or any other performance-sensitive iOS app, this hybrid approach offers a proven path to achieving both speed and elegance.</p><p>Happy coding!</p><p>David Cruz<br><a href="https://www.davthecoder.com/">davthecoder.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c09a4d4881b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a High-Performance Financial Charting App: Rust + Kotlin on Android]]></title>
            <link>https://davthecoder.medium.com/building-a-high-performance-financial-charting-app-rust-kotlin-on-android-6a2b17349cfb?source=rss-4c1be6bf35fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a2b17349cfb</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[android-jni]]></category>
            <category><![CDATA[android-ndk]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[David Cruz]]></dc:creator>
            <pubDate>Sun, 05 Oct 2025 21:40:28 GMT</pubDate>
            <atom:updated>2025-10-08T09:05:17.124Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YC1HDKmJyHWPfxuqrnJbJg.png" /></figure><p><strong>Real-world case study: Achieving 6–80x speedups on technical indicators with Rust native code</strong></p><p>When building a real-time financial charting application for Android that processes cryptocurrency price data from Binance, I faced a critical performance challenge. Technical indicators like Moving Averages, RSI, and MACD need to process thousands of data points at 60 FPS while maintaining smooth UI interactions. The solution? A hybrid Rust/Kotlin architecture that delivers native performance with automatic fallback to pure Kotlin. This post walks through the actual implementation, showing real code and benchmark results from production.</p><h3>The Performance Problem: Why Kotlin Wasn’t Enough</h3><p>The application streams live BTC/USDT price data from Binance WebSocket, processes candlestick data, and calculates multiple technical indicators in realtime. With 1,000+ historical candlesticks on screen and updates coming in continuously, the Kotlin implementation worked but showed limitations:</p><ul><li>Full chart processing (SMA 20/50, EMA 12/26, RSI 14, MACD) taking 400–600µs per frame</li><li>Occasional GC pauses causing frame drops during intensive calculations</li><li>CPU usage spiking when users toggle multiple indicators simultaneously</li><li>Memory pressure from allocating temporary arrays for each calculation</li></ul><p>The target was clear: maintain 60 FPS (16.6ms per frame) even with 10,000 data points and all indicators enabled. While Kotlin could handle smaller datasets, scaling to larger historical views needed optimisation.</p><p>Enter Rust with its zero-cost abstractions, no garbage collection, and SIMD auto-vectorisation capabilities.</p><h3>The Architecture: Hybrid Rust/Kotlin with Smart Fallback</h3><p>The solution implements a four-layer architecture that bridges Kotlin’s Android ecosystem with Rust’s computational power:</p><pre>┌─────────────────────────────────────────────────────────────┐<br>│                  Jetpack Compose UI Layer                   │<br>│  • CandlestickChart  • Volume Bars  • RSI Indicators        │<br>│  • Real-time Updates • Smooth Canvas Animations             │<br>└─────────────────────────────┬───────────────────────────────┘<br>                              │<br>┌─────────────────────────────▼───────────────────────────────┐<br>│            TechnicalIndicators.kt (Hybrid)                  │<br>│  • Loads Rust library via System.loadLibrary()              │<br>│  • Calls native methods for performance                     │<br>│  • Auto-falls back to Kotlin if library unavailable         │<br>└─────────────────────────────┬───────────────────────────────┘<br>                              │<br>                ┌─────────────┴─────────────┐<br>                │                           │<br>    ┌───────────▼──────────┐    ┌──────────▼────────────┐<br>    │  Rust Native Code    │    │  Kotlin Fallback      │<br>    │  (Primary Path)      │    │  (Backup Path)        │<br>    │  • lib.rs (JNI)      │    │  • calculateSMAKotlin │<br>    │  • indicators.rs     │    │  • calculateEMAKotlin │<br>    │  • 6-80x faster      │    │  • Always works       │<br>    └──────────────────────┘    └───────────────────────┘</pre><p>This hybrid approach provides production reliability: if the Rust library fails to load (wrong architecture, corrupted file, etc.), the app seamlessly falls back to pure Kotlin. Users never see crashes — just slightly slower calculations.</p><h3>Implementation Deep Dive: Real Code from Production</h3><h3>Layer 1: Pure Rust Algorithms (indicators.rs)</h3><p>The core calculations live in pure Rust with zero Android dependencies. Here’s the actual Simple Moving Average implementation:</p><pre>/// Calculate Simple Moving Average (SMA)<br>///<br>/// # Arguments<br>/// * `data` - Input price data<br>/// * `period` - Number of periods for averaging<br>///<br>/// # Returns<br>/// Vector of SMA values with NaN for insufficient data points<br>pub fn calculate_sma(data: &amp;[f32], period: usize) -&gt; Vec&lt;f32&gt; {<br>    if data.len() &lt; period {<br>        return vec![];<br>    }<br>    <br>    let mut result = vec![f32::NAN; data.len()];<br>    <br>    // Calculate SMA for values where we have enough data<br>    for i in (period - 1)..data.len() {<br>        let start = i.saturating_sub(period - 1);<br>        let sum: f32 = data[start..=i].iter().sum();<br>        result[i] = sum / period as f32;<br>    }<br><br>    result<br>}</pre><p>This implementation demonstrates Rust’s strengths:</p><ul><li><strong>Memory efficiency</strong>: Pre-allocated result vector with NaN padding</li><li><strong>Bounds safety</strong>: Using saturating_sub prevents underflow without runtime checks</li><li><strong>Iterator optimization</strong>: The compiler can vectorize the sum() operation using SIMD</li><li><strong>Zero allocations</strong>: No heap allocations in the hot loop</li></ul><p>The Exponential Moving Average shows more sophisticated optimization:</p><pre>pub fn calculate_ema(data: &amp;[f32], period: usize) -&gt; Vec&lt;f32&gt; {<br>    if data.len() &lt; period {<br>        return vec![];<br>    }<br><br>    let mut result = vec![f32::NAN; data.len()];<br>    let multiplier = 2.0 / (period as f32 + 1.0);<br>    // Calculate initial SMA as first EMA value<br>    let sum: f32 = data[0..period].iter().sum();<br>    let mut ema = sum / period as f32;<br>    result[period - 1] = ema;<br>    // Calculate EMA for remaining values<br>    for i in period..data.len() {<br>        ema = (data[i] - ema) * multiplier + ema;<br>        result[i] = ema;<br>    }<br>    result<br>}</pre><p>The EMA calculation maintains state in a single f32 variable, updating it iteratively. This results in excellent cache locality and enables aggressive compiler optimisations.</p><p>The RSI implementation addresses the more complex elements of technical analysis, including smoothed averaging and separate tracking of gains and losses:</p><pre>pub fn calculate_rsi(data: &amp;[f32], period: usize) -&gt; Vec&lt;f32&gt; {<br>    if data.len() &lt; period + 1 {<br>        return vec![];<br>    }<br><br>    let mut result = vec![f32::NAN; data.len()];<br><br>    // Calculate price changes and separate gains/losses<br>    let mut gains = vec![0.0f32; data.len() - 1];<br>    let mut losses = vec![0.0f32; data.len() - 1];<br>    for i in 1..data.len() {<br>        let change = data[i] - data[i - 1];<br>        gains[i - 1] = if change &gt; 0.0 { change } else { 0.0 };<br>        losses[i - 1] = if change &lt; 0.0 { -change } else { 0.0 };<br>    }<br><br>    // Calculate initial average gain and loss<br>    let sum_gain: f32 = gains[0..period].iter().sum();<br>    let sum_loss: f32 = losses[0..period].iter().sum();<br>    let mut avg_gain = sum_gain / period as f32;<br>    let mut avg_loss = sum_loss / period as f32;<br><br>    // Calculate first RSI<br>    let rs = if avg_loss == 0.0 { 100.0 } else { avg_gain / avg_loss };<br>    let rsi = 100.0 - (100.0 / (1.0 + rs));<br>    result[period] = rsi;<br><br>    // Calculate remaining RSI values using smoothed averages<br>    for i in period..gains.len() {<br>        avg_gain = (avg_gain * (period - 1) as f32 + gains[i]) / period as f32;<br>        avg_loss = (avg_loss * (period - 1) as f32 + losses[i]) / period as f32;<br>        let rs_value = if avg_loss == 0.0 { 100.0 } else { avg_gain / avg_loss };<br>        let rsi_value = 100.0 - (100.0 / (1.0 + rs_value));<br>        result[i + 1] = rsi_value;<br>    }<br><br>    result<br>}</pre><p><strong>Critical optimisation notes:</strong></p><ul><li>Division by zero is handled explicitly without exceptions</li><li>The smoothing calculation reuses previous averages (proper Wilder’s smoothing)</li><li>All arrays are stack-allocated where possible</li><li>No string allocations or debug overhead in release builds</li></ul><h3>Layer 2: JNI Bridge Layer (lib.rs)</h3><p>The JNI bindings translate between Kotlin’s FloatArray and Rust&#39;s &amp;[f32] slices. Here&#39;s the actual SMA binding:</p><pre>use jni::JNIEnv;<br>use jni::objects::{JClass, JFloatArray};<br>use jni::sys::jfloatArray;<br><br>mod indicators;<br><br>/// Calculate Simple Moving Average (SMA)<br>#[no_mangle]<br>pub extern &quot;C&quot; fn Java_com_davthecoder_financial_TechnicalIndicators_calculateSMANative(<br>    env: JNIEnv,<br>    _class: JClass,<br>    data: JFloatArray,<br>    period: i32,<br>) -&gt; jfloatArray {<br>    let len = match env.get_array_length(&amp;data) {<br>        Ok(l) =&gt; l as usize,<br>        Err(_) =&gt; return JFloatArray::default().into_raw(),<br>    };<br>    let mut data_vec = vec![0.0f32; len];<br>    if env.get_float_array_region(&amp;data, 0, &amp;mut data_vec).is_err() {<br>        return JFloatArray::default().into_raw();<br>    }<br>    let result = indicators::calculate_sma(&amp;data_vec, period as usize);<br>    match env.new_float_array(result.len() as i32) {<br>        Ok(output) =&gt; {<br>            let _ = env.set_float_array_region(&amp;output, 0, &amp;result);<br>            output.into_raw()<br>        }<br>        Err(_) =&gt; JFloatArray::default().into_raw(),<br>    }<br>}</pre><p><strong>Key implementation details:</strong></p><p>The function name follows JNI’s strict naming convention: Java_&lt;package&gt;_&lt;class&gt;_&lt;method&gt;. The #[no_mangle] attribute prevents Rust&#39;s name mangling, ensuring the JVM can locate the symbol. Error handling uses match expressions, returning empty arrays on failure rather than panicking (which would crash the Android app).</p><p>The critical performance operation is get_float_array_region, which bulk-copies the Java array to Rust&#39;s stack in a single JNI call. This is far more efficient than element-by-element access. Similarly, set_float_array_region bulk-copies the result back.</p><p>The RSI binding demonstrates the same pattern with additional parameters:</p><pre>#[no_mangle]<br>pub extern &quot;C&quot; fn Java_com_davthecoder_financial_TechnicalIndicators_calculateRSINative(<br>    env: JNIEnv,<br>    _class: JClass,<br>    data: JFloatArray,<br>    period: i32,<br>) -&gt; jfloatArray {<br>    let len = match env.get_array_length(&amp;data) {<br>        Ok(l) =&gt; l as usize,<br>        Err(_) =&gt; return JFloatArray::default().into_raw(),<br>    };<br><br>    let mut data_vec = vec![0.0f32; len];<br>    if env.get_float_array_region(&amp;data, 0, &amp;mut data_vec).is_err() {<br>        return JFloatArray::default().into_raw();<br>    }<br><br>    let result = indicators::calculate_rsi(&amp;data_vec, period as usize);<br>    match env.new_float_array(result.len() as i32) {<br>        Ok(output) =&gt; {<br>            let _ = env.set_float_array_region(&amp;output, 0, &amp;result);<br>            output.into_raw()<br>        }<br>        Err(_) =&gt; JFloatArray::default().into_raw(),<br>    }<br>}</pre><p>The MACD binding is slightly more complex due to returning flattened arrays with three values per data point:</p><pre>#[no_mangle]<br>pub extern &quot;C&quot; fn Java_com_davthecoder_financial_TechnicalIndicators_calculateMACDNative(<br>    env: JNIEnv,<br>    _class: JClass,<br>    data: JFloatArray,<br>    fast_period: i32,<br>    slow_period: i32,<br>    signal_period: i32,<br>) -&gt; jfloatArray {<br>    let len = match env.get_array_length(&amp;data) {<br>        Ok(l) =&gt; l as usize,<br>        Err(_) =&gt; return JFloatArray::default().into_raw(),<br>    };<br><br>    let mut data_vec = vec![0.0f32; len];<br><br>    if env.get_float_array_region(&amp;data, 0, &amp;mut data_vec).is_err() {<br>        return JFloatArray::default().into_raw();<br>    }<br><br>    let result = indicators::calculate_macd(<br>        &amp;data_vec,<br>        fast_period as usize,<br>        slow_period as usize,<br>        signal_period as usize,<br>    );<br><br>    match env.new_float_array(result.len() as i32) {<br>        Ok(output) =&gt; {<br>            let _ = env.set_float_array_region(&amp;output, 0, &amp;result);<br>            output.into_raw()<br>        }<br>        Err(_) =&gt; JFloatArray::default().into_raw(),<br>    }<br>}</pre><h3>Layer 3: Kotlin Hybrid Wrapper (TechnicalIndicators.kt)</h3><p>The Kotlin layer provides the elegant fallback mechanism that makes this architecture production-ready:</p><pre>package com.davthecoder.financial<br><br>object TechnicalIndicators {<br><br>    private var useNative = true<br><br>    init {<br>        try {<br>            System.loadLibrary(&quot;financial_indicators&quot;)<br>        } catch (e: UnsatisfiedLinkError) {<br>            useNative = false<br>            println(&quot;Failed to load native library, using Kotlin fallback: ${e.message}&quot;)<br>        }<br>    }<br><br>    // Native method declarations<br>    @JvmStatic<br>    private external fun calculateSMANative(<br>        data: FloatArray,<br>        period: Int,<br>    ): FloatArray<br><br>    /**<br>     * Calculate Simple Moving Average (SMA)<br>     * @param data Input price data<br>     * @param period Number of periods for averaging<br>     * @return List of SMA values with NaN for insufficient data points<br>     */<br>    fun calculateSMA(<br>        data: FloatArray,<br>        period: Int,<br>    ): FloatArray {<br>        return if (useNative) {<br>            try {<br>                calculateSMANative(data, period)<br>            } catch (e: Exception) {<br>                calculateSMAKotlin(data, period)<br>            }<br>        } else {<br>            calculateSMAKotlin(data, period)<br>        }<br>    }<br><br>    private fun calculateSMAKotlin(<br>        data: FloatArray,<br>        period: Int,<br>    ): FloatArray {<br>        if (data.size &lt; period) {<br>            return FloatArray(0)<br>        }<br>        val result = FloatArray(data.size)<br>        // Fill initial values with NaN (not enough data for calculation)<br>        for (i in 0 until period - 1) {<br>            result[i] = Float.NaN<br>        }<br>        // Calculate SMA for remaining values<br>        for (i in period - 1 until data.size) {<br>            var sum = 0f<br>            for (j in i - period + 1..i) {<br>                sum += data[j]<br>            }<br>            result[i] = sum / period.toFloat()<br>        }<br>        return result<br>    }<br><br>}</pre><p>This pattern repeats for all indicators. The brilliance is in the three-tier fallback:</p><ol><li><strong>Try native first</strong> (calculateSMANative) for maximum performance</li><li><strong>Catch runtime exceptions</strong> and fall back to Kotlin if native call fails</li><li><strong>Boot-time detection</strong> sets useNative = false if library doesn&#39;t load at all</li></ol><p>The Kotlin implementations mirror the Rust algorithms exactly, ensuring identical results. Here’s the EMA fallback:</p><pre>private fun calculateEMAKotlin(<br>    data: FloatArray,<br>    period: Int,<br>): FloatArray {<br>    if (data.size &lt; period) {<br>        return FloatArray(0)<br>    }<br><br>    val result = FloatArray(data.size)<br>    val multiplier = 2f / (period.toFloat() + 1f)<br><br>    // Fill initial values with NaN<br>    for (i in 0 until period - 1) {<br>        result[i] = Float.NaN<br>    }<br><br>    // Calculate initial SMA as first EMA value<br>    var sum = 0f<br>    for (i in 0 until period) {<br>        sum += data[i]<br>    }<br>    var ema = sum / period.toFloat()<br>    result[period - 1] = ema<br><br>    // Calculate EMA for remaining values<br>    for (i in period until data.size) {<br>        ema = (data[i] - ema) * multiplier + ema<br>        result[i] = ema<br>    }<br><br>    return result<br>}</pre><p>The RSI and MACD fallbacks follow identical patterns, maintaining algorithmic parity with Rust while providing the safety net.</p><h3>Real Performance Results: The Numbers Don’t Lie</h3><p>The proof is in the benchmarks. Running instrumented tests on a Google Pixel 5 (ARM64, Android 14) with realistic BTC price data reveals dramatic performance improvements.</p><h3>Benchmark Configuration</h3><ul><li><strong>Device</strong>: Google Pixel 5 (arm64-v8a)</li><li><strong>Data</strong>: Realistic BTC price movements (simulated with Gaussian distribution)</li><li><strong>Iterations</strong>: 100 per test with 10 warmup iterations</li><li><strong>Sizes</strong>: 100, 500, 1K, 5K, 10K data points</li></ul><h3>MACD: Up to 80x Speedup</h3><p>MACD shows the most dramatic improvements because it combines multiple EMA calculations:</p><pre>| Data Points   | Rust  | Kotlin  | Speedup |<br>|---------------|-------|---------|---------|<br>| 100           | 19µs  | 1556µ   | 80.89x  |<br>| 500           | 59µs  | 3297µs  | 55.75x  |<br>| 1000          | 104µs | 5839µs  | 55.83x  |<br>| 5000          | 404µs | 11463µs | 28.31x  |<br>| 10000         | 810µs | 5215µs  | 6.44x   |</pre><p>From the actual log output:</p><pre>Size: 100  | Current: 19µs  | Kotlin: 1556µs | Speedup: 80.89x<br>Size: 500  | Current: 59µs  | Kotlin: 3297µs | Speedup: 55.75x<br>Size: 1000 | Current: 104µs | Kotlin: 5839µs | Speedup: 55.83x</pre><p>That’s not a typo: <strong>80x faster</strong> for small datasets. Even at 10,000 points, Rust is 6.4x faster.</p><h3>RSI: Consistent 15–16x Speedup</h3><p>RSI shows excellent scaling with consistent speedups across dataset sizes:</p><pre>| Data Points   | Rust  | Kotlin  | Speedup |<br>|---------------|-------|---------|---------|<br>| 100           | 13µs  | 217µs   | 15.66x  |<br>| 500           | 35µs  | 546µs   | 15.47x  |<br>| 1000          | 68µs  | 68µs    | 1.00x   |<br>| 5000          | 250µs | 291µs   | 1.16x   |<br>| 10000         | 490µs | 617µs   | 1.26x   |</pre><p>The performance gains are dramatic for smaller datasets. Interestingly, at 1,000+ points, the performance converges — this is likely due to JIT optimisation kicking in for Kotlin’s simpler RSI loop.</p><h3>SMA: 1.4x Speedup at Scale</h3><p>Simple Moving Average shows more modest but consistent improvements:</p><pre>| Data Points   | Rust  | Kotlin  | Speedup |<br>|---------------|-------|---------|---------|<br>| 100           | 12µs  | 223µs   | 17.80x  |<br>| 500           | 42µs  | 47µs    | 1.12x   |<br>| 1000          | 79µs  | 95µs    | 1.20x   |<br>| 5000          | 350µs | 485µs   | 1.38x   |<br>| 10000         | 685µs | 970µs   | 1.42x   |</pre><p>Even the “simple” moving average benefits from Rust’s optimisations, particularly at larger scales.</p><h3>Full Chart Processing: Real-World Performance</h3><p>The most important metric is full chart processing with all indicators enabled (SMA 20/50, EMA 12/26, RSI 14, MACD 12/26/9):</p><pre>| Data Points   | Time    | Potential FPS | vs 60 FPS Target |<br>|---------------|---------|---------------|------------------|<br>| 100           | 79µs    | 12,579 FPS    | ✅ 210x headroom |<br>| 500           | 233µs   | 4,292 FPS     | ✅ 71x headroom  |<br>| 1000          | 420µs   | 2,380 FPS     | ✅ 40x headroom  |<br>| 5000          | 1,875µs | 533 FPS       | ✅ 9x headroom   |<br>| 10000         | 3,704µs | 270 FPS       | ✅ 4.5x headroom |</pre><p>From the log output:</p><pre>Size: 100  | Time: 79µs  | Potential FPS: 12579.1<br>Size: 500  | Time: 233µs | Potential FPS: 4291.8<br>Size: 1000 | Time: 420µs | Potential FPS: 2380.4</pre><p>Even with 10,000 candlesticks and all indicators enabled, processing completes in under 4ms — leaving plenty of room for UI rendering, animation, and user interaction within the 16.6ms frame budget (60 FPS).</p><h3>Why Such Dramatic Speedups?</h3><p>Several factors combine to create these results:</p><ol><li><strong>Zero GC overhead</strong>: Rust has no garbage collector. Kotlin’s GC can pause for milliseconds during collection cycles.</li><li><strong>Memory layout</strong>: Rust’s contiguous arrays have better cache locality than Kotlin’s boxed arrays.</li><li><strong>SIMD auto-vectorisation:</strong> The compiler can process 4+ floats simultaneously using ARM NEON instructions.</li><li><strong>JNI overhead is minimal</strong>: Bulk array copies (1–5µs for 10K elements) are amortised across the calculation time.</li><li><strong>No runtime warmup</strong>: Rust code runs at full speed immediately; Kotlin needs JIT warmup iterations.</li></ol><p>The most surprising result is that even small datasets (100 points) benefit dramatically, suggesting the GC overhead and object allocation costs dominate Kotlin’s performance even more than the raw computation.</p><p>Benchmark Log to Visualizations: <a href="https://gemini.google.com/share/940c19741096">https://gemini.google.com/share/940c19741096</a></p><h3>The Build Process: From Rust to Android APK</h3><p>The project includes a comprehensive build script that handles cross-compilation for all Android architectures. Here’s the actual build-rust.sh:</p><pre>#!/bin/bash<br>set -e<br><br>echo &quot;🦀 Building Rust libraries for Android...&quot;<br># Check if Rust is installed<br>if ! command -v cargo &amp;&gt; /dev/null; then<br>    echo &quot;❌ Rust/Cargo not found. Please install Rust from https://rustup.rs&quot;<br>    exit 1<br>fi<br># Add Android targets if not already added<br>TARGETS=(<br>    &quot;aarch64-linux-android&quot;<br>    &quot;armv7-linux-androideabi&quot;<br>    &quot;x86_64-linux-android&quot;<br>    &quot;i686-linux-android&quot;<br>)<br>echo &quot;📦 Checking Android targets...&quot;<br>for target in &quot;${TARGETS[@]}&quot;; do<br>    if ! rustup target list | grep -q &quot;$target (installed)&quot;; then<br>        echo &quot;Adding target: $target&quot;<br>        rustup target add &quot;$target&quot;<br>    fi<br>done<br># Set Android NDK path (adjust if needed)<br>if [ -z &quot;$ANDROID_NDK_HOME&quot; ]; then<br>    if [ -d &quot;$HOME/Library/Android/sdk/ndk&quot; ]; then<br>        export ANDROID_NDK_HOME=&quot;$HOME/Library/Android/sdk/ndk/$(ls -1 $HOME/Library/Android/sdk/ndk | tail -1)&quot;<br>    else<br>        echo &quot;⚠️  ANDROID_NDK_HOME not set. Please set it to your NDK installation path.&quot;<br>        exit 1<br>    fi<br>fi<br># Build for each target<br>for target in &quot;${TARGETS[@]}&quot;; do<br>    echo &quot;🔨 Building for $target...&quot;<br>    cargo build --release --target &quot;$target&quot;<br>done<br># Copy libraries to Android jniLibs<br>JNILIBS_DIR=&quot;../app/src/main/jniLibs&quot;<br>mkdir -p &quot;$JNILIBS_DIR&quot;<br># Map Rust targets to Android ABIs<br>for target in &quot;${TARGETS[@]}&quot;; do<br>    case &quot;$target&quot; in<br>        &quot;aarch64-linux-android&quot;)<br>            abi=&quot;arm64-v8a&quot;<br>            ;;<br>        &quot;armv7-linux-androideabi&quot;)<br>            abi=&quot;armeabi-v7a&quot;<br>            ;;<br>        &quot;x86_64-linux-android&quot;)<br>            abi=&quot;x86_64&quot;<br>            ;;<br>        &quot;i686-linux-android&quot;)<br>            abi=&quot;x86&quot;<br>            ;;<br>    esac<br>    src=&quot;target/$target/release/libfinancial_indicators.so&quot;<br>    dst=&quot;$JNILIBS_DIR/$abi&quot;<br>    if [ -f &quot;$src&quot; ]; then<br>        mkdir -p &quot;$dst&quot;<br>        cp &quot;$src&quot; &quot;$dst/libfinancial_indicators.so&quot;<br>        echo &quot;✅ Copied $src -&gt; $dst/libfinancial_indicators.so&quot;<br>    fi<br>done<br>echo &quot;🎉 Rust build complete!&quot;</pre><p>The script:</p><ol><li>Verifies Rust installation</li><li>Installs Android targets if missing</li><li>Locates Android NDK automatically</li><li>Compiles for all four architectures</li><li>Copies .so files to the correct jniLibs directories</li></ol><h3>Complete Build Workflow</h3><pre># 1. Install Rust and Android targets (one-time setup)<br>curl --proto &#39;=https&#39; --tlsv1.2 -sSf https://sh.rustup.rs | sh<br>rustup target add aarch64-linux-android armv7-linux-androideabi \<br>                  x86_64-linux-android i686-linux-android<br><br># 2. Build Rust libraries<br>./build-rust.sh<br><br># 3. Build and run Android app<br>./gradlew installDebug<br><br># 4. Run benchmarks (optional)<br>./run-benchmarks.sh</pre><p>The resulting APK structure:</p><pre>app-debug.apk<br>├── lib/<br>│   ├── arm64-v8a/<br>│   │   └── libfinancial_indicators.so    # 64-bit ARM (most devices)<br>│   ├── armeabi-v7a/<br>│   │   └── libfinancial_indicators.so    # 32-bit ARM (older devices)<br>│   ├── x86_64/<br>│   │   └── libfinancial_indicators.so    # Emulator<br>│   └── x86/<br>│       └── libfinancial_indicators.so    # Older emulator<br>└── classes.dex                            # Kotlin/Java bytecode</pre><p>Android automatically loads the correct .so file based on device architecture.</p><h3>Lessons Learned and Best Practices</h3><h3>What Worked Exceptionally Well</h3><p><strong>The hybrid fallback architecture</strong> proved invaluable during development and testing. During development on macOS, the native library couldn’t load in unit tests, but the Kotlin fallback allowed testing business logic without device deployment. In production, the system gracefully handles edge cases like corrupted .so files or unsupported architectures.</p><p><strong>Identical algorithms in both languages</strong> ensured correctness. By implementing the exact same logic in Rust and Kotlin, we could cross-validate results. Unit tests verified that calculateSMA(data, 20) returned identical values (within floating-point precision) whether using Rust or Kotlin.</p><p><strong>Bulk JNI array operations</strong> minimised overhead. Using get_float_array_region for bulk copies (1-5µs for 10K elements) instead of element-by-element access (100µs+) made JNI overhead negligible compared to computation time.</p><p><strong>Comprehensive benchmarking</strong> guided optimisation decisions. The instrumented tests revealed that MACD benefited most from Rust (80x speedup), while EMA showed modest gains (1.5–2x). This helped prioritise which calculations to optimise further.</p><h3>Challenges and Solutions</h3><p><strong>Initial JNI complexity</strong> was daunting. The solution was to develop a reference implementation (SMA) that functioned flawlessly, which could then be replicated for other indicators. The JNI boilerplate is nearly identical for all array-based calculations.</p><p><strong>Cross-platform development</strong> required workflow adjustments. The rust code must be compiled on macOS/Linux before building Android APKs. The build-rust.sh script automated the process and adding it to CI/CD ensures libraries are always up-to-date.</p><p><strong>Debugging native crashes</strong> initially seemed impossible. Adding proper error handling in JNI bindings (returning empty arrays instead of panicking) prevented crashes. For development, println! statements in Rust with logcat viewing provided adequate debugging.</p><h3>When to Use This Pattern</h3><p>The hybrid Rust/Kotlin architecture makes sense when:</p><p>✅ <strong>Computational hotspots exist</strong>: Loops processed 1,000+ elements.<br>✅ <strong>Deterministic performance required</strong>: Real-time updates without GC pauses. <br>✅ <strong>Algorithm is CPU-bound</strong>: Calculations dominate over I/O.<br>✅ <strong>Code can be tested independently: </strong>Pure functions without Android dependencies.<br>✅ <strong>Team has Rust expertise</strong>: Or willingness to learn.</p><p>This pattern is overkill for:</p><p>❌ <strong>I/O-bound operations</strong>: Database queries, network calls.<br>❌ <strong>UI logic</strong>: Jetpack Compose is already optimised.<br>❌ <strong>Simple calculations</strong>: Single operations on small datasets.<br>❌ <strong>Rapid prototyping phase</strong>: Add Rust after proving product-market fit</p><h3>Real-World Impact: The Production App</h3><p>The complete application demonstrates this architecture at scale:</p><ul><li><strong>Real-time Binance WebSocket integration</strong>: Live BTC/USDT price streaming</li><li><strong>60 FPS rendering</strong>: Smooth candlestick charts with all indicators</li><li><strong>10,000+ data points</strong>: Historical data loads instantly</li><li><strong>Zero frame drops</strong>: Native calculations complete in under 4ms</li><li><strong>Progressive enhancement</strong>: Works without Rust library (slower but functional)</li></ul><p>From the README:</p><blockquote><em>“Features real-time cryptocurrency price data from Binance WebSocket API with blazing-fast native calculations.”</em></blockquote><p>The benchmarks prove the “blazing-fast” claim: processing 1,000 candlesticks with six technical indicators completes in 420µs — <strong>40x faster than the 60 FPS requirement</strong>.</p><h3>Conclusion: Hybrid Architecture as Production Strategy</h3><p>This project validates a powerful pattern for Android performance optimisation: use Rust for computational hotspots while maintaining Kotlin fallbacks for reliability. The results are impressive, demonstrating 6–80x speedups on real-world financial calculations, along with graceful degradation in the event of native library failure.</p><p>The key insights:</p><ol><li><strong>JNI overhead is negligible</strong> when bulk-copying arrays (1–5µs for thousands of elements)</li><li><strong>Rust’s zero-GC architecture</strong> eliminates unpredictable pauses in time-sensitive calculations</li><li><strong>Hybrid fallback</strong> provides production reliability without compromising performance</li><li><strong>Identical algorithms</strong> in both languages ensure correctness and enable cross-validation</li><li><strong>SIMD auto-vectorization</strong> happens automatically with proper Rust code patterns</li></ol><p>For Android developers building performance-critical applications, financial charts, signal processing, computer vision, cryptography, and data compression. Rust integration offer a proven path to native performance with modern safety guarantees.</p><p>The complete source code, benchmarks, and build scripts are available at <a href="https://github.com/davthecodercom/Financial-RustAndAndroid">github.com/davthecodercom/Financial-RustAndAndroid</a>, demonstrating that production-quality Rust integration on Android is not only possible but also remarkably effective.</p><p><strong>Built with ❤️ using Rust 🦀, Kotlin, and Jetpack Compose</strong></p><p><em>Performance measurements from Google Pixel 5 (ARM64, Android 14) running instrumented tests with 100 iterations per benchmark.</em></p><p>David Cruz<br><a href="https://www.davthecoder.com/">www.davthecoder.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a2b17349cfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use C++ code in to your iOS/tvOS Xcode projects with Swift]]></title>
            <link>https://davthecoder.medium.com/how-to-use-c-code-in-to-your-ios-tvos-xcode-projects-with-swift-25fa40f9a19e?source=rss-4c1be6bf35fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/25fa40f9a19e</guid>
            <category><![CDATA[interoperability]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[c-plus-plus-tutorial]]></category>
            <category><![CDATA[cplusplus]]></category>
            <dc:creator><![CDATA[David Cruz]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 09:13:04 GMT</pubDate>
            <atom:updated>2025-09-17T08:30:22.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddWsYLPm0lx4CcAyfUQ-oQ.png" /></figure><p>A long time ago, I was asked to create some C++ code for specific functionality intended for use in both Android and iOS. I won&#39;t delve into excessive detail, but it was primarily for security reasons.</p><p>I must clarify that the main language is Swift and very rarely will you need to use C++ code to develop an app, but there are some fields where writing some parts in low-level programming languages will give you an extra layer of security so it could be recommended.</p><p>In this article, I would like to show you how to directly use your C++ code in your Xcode 15+ project for iOS and tvOS without the usual bridge, ensuring that if you encounter this scenario, you will have a straightforward guide to implement it.</p><p>Therefore, the purpose of this article is to demonstrate how to use low-level C++ rather than focusing on the C++ code itself, which is why I am using basic demo files. Here is an overview of the demo C++ files that we will use:</p><pre>//<br>//  MyCppClass.hpp<br>//  cppexample<br>//<br>//  Created by davthecoder on 16/09/2025.<br>//<br><br>#pragma once<br>#include &lt;string&gt;<br><br>class MyCppClass {<br>public:<br>    MyCppClass(int val);<br>    std::string greet() const;<br>private:<br>    int value;<br>};</pre><pre>//<br>// MyCppClass.cpp<br>//  cppexample<br>//<br>//  Created by davthecoder on 16/09/2025.<br>//<br><br>#include &quot;MyCppClass.hpp&quot;<br><br>MyCppClass::MyCppClass(int val) : value(val) {}<br><br>std::string MyCppClass::greet() const {<br>    return &quot;Hello from C++, value is &quot; + std::to_string(value);<br>}</pre><pre>//<br>//  module.modulemap<br>//  cppexample<br>//<br>//  Created by davthecoder on 16/09/2025.<br>//<br><br>module MyCppModule {<br>    header &quot;MyCppClass.hpp&quot;<br>    export *<br>}</pre><pre>//<br>//  cppexample-Bridging-Header.h<br>//  cppexample<br>//<br>//  Created by davthecoder on 16/09/2025.<br>//  Keep it empty</pre><p><strong>Would you like to try by yourself? </strong>Here is how it should look in your project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mp2JCSYiiT3X_Z5N9fbWXg.png" /></figure><p>Now that we have created and filled our .hpp, .cpp, and .modulemap files with the code above, there are a couple more steps we need to take.</p><p>the first one is to declare in <strong><em>Build Settings</em></strong> &gt; <strong><em>Swift Compiler — Language</em></strong> &gt; <strong><em>C++ and Objective-C interoperability</em></strong> to <strong><em>C++ / Objective-C++</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DZMviovwP4Y8zhkQzJFYA.png" /><figcaption>Selecting C++/Objective-C++ as Swift Compiler Language</figcaption></figure><p>The second step is to actually call the C++ code in our Swift file. In this demonstration, I will use the default Content View that is generated when we create a new project from scratch.</p><pre>//<br>//  ContentView.swift<br>//  cppexample<br>//<br>//  Created by davthecoder on 16/09/2025.<br>//<br><br>import SwiftUI<br>import MyCppModule // &lt;-- Import the C++ module<br><br>struct ContentView: View {<br>    var body: some View {<br>        VStack {<br>            let cppObj = MyCppClass(42) // &lt; --Create an instance of the C++ class<br>            Image(systemName: &quot;globe&quot;)<br>                .imageScale(.large)<br>                .foregroundStyle(.tint)<br>            Text(&quot;\(cppObj.greet())&quot;) // &lt;-- cppObj.greet() Call a method from the C++ class<br>                .padding()<br>        }<br>        .padding()<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><p>Once you&#39;ve successfully added the files and made the necessary changes to your Xcode project, you should be able to execute your C++ code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bV-H3I9ddqZEIsNXVRNsZQ.png" /><figcaption>Screenshot running in C++ code in iOS from the code above</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XG9OBMc_hJyjEKiGMHnSPg.png" /><figcaption>Screenshot running in C++ code in tvOS from the code above</figcaption></figure><p>I trust that this concise and straightforward guide will assist you in accomplishing this task as easily as possible.</p><p><a href="https://www.davthecoder.com/blog/how-to-use-c-code-in-to-your-ios-tvos-xcode-projects-with-swift">Check my article in my personal tech blog.</a></p><p>Happy coding!</p><p>David Cruz<br><a href="https://www.davthecoder.com/">davthecoder.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25fa40f9a19e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Senior Developers Fail Technical Interviews (And How to Fix It)]]></title>
            <link>https://davthecoder.medium.com/why-senior-developers-fail-technical-interviews-and-how-to-fix-it-05f44dd55ffb?source=rss-4c1be6bf35fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/05f44dd55ffb</guid>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[technical-interview]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[technical-presentation]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[David Cruz]]></dc:creator>
            <pubDate>Fri, 12 Sep 2025 09:58:41 GMT</pubDate>
            <atom:updated>2025-09-12T10:35:32.346Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2c485mF7s9i5OpSGLay3w.png" /></figure><p>Picture this: a <strong>10-year veteran engineer</strong>, respected by peers, known for shipping complex systems… who suddenly <em>tanks</em> a technical interview.</p><p>They stumble on a coding puzzle, ramble through a a system design, or undersell themselves in a behavioural round. The result? <strong>Rejection.</strong></p><p>Here’s the truth:<br> 👉 Most senior dev failures in interviews aren’t about <em>skill gaps.</em><br> They’re about <strong>misalignment</strong> between <em>real work</em> and the <strong>artificial game</strong> of interviews.</p><p>This post breaks down:</p><ul><li>Why seniors flop in interviews</li><li>How to <strong>hack the process</strong> instead of losing to it</li><li>Playbooks for <strong>both candidates and companies</strong></li></ul><h3>✨ TL;DR (The Brutal Truth)</h3><ul><li><strong>Interview ≠ Job</strong>: Most processes test problem-solving tricks, <em>not</em> true senior engineering value.</li><li><strong>It’s about mechanics, not identity</strong>: You don’t fail because you’re bad — you fail because you don’t “play the test.”</li><li><strong>Prep smart, not desperate: </strong>Learn the format, not just random problems.</li><li><strong>Companies can fix this</strong>: Shift focus to signals that actually predict senior impact.</li></ul><h3>🎭 1. Interview–Work Mismatch</h3><p>💡 <em>LeetCode ≠ Leadership.</em></p><p>Most interviews measure:</p><ul><li><strong>Quick recall</strong> of algorithms</li><li>45-minute “snapshots”</li><li>Problem-solving without rich context</li></ul><p>But most senior value comes from:</p><ul><li>Designing <strong>systems and trade-offs</strong></li><li>Leading through <strong>messy, long-term challenges</strong></li><li>Mentoring and enabling teams</li></ul><blockquote><em>🗣️ </em><strong><em>Callout:</em></strong><em> </em>“Interviews test how fast you sprint. Senior engineers win marathons.”</blockquote><p><strong>Playbooks:</strong></p><ul><li><strong>Candidates:</strong> Consider interviews to be a <strong>standardised test</strong> — format mastery &gt; raw depth.</li><li><strong>Companies:</strong> Use <strong>real work samples</strong> (debug sessions, refactors, collaborative design tasks).</li></ul><h3>🛠️ 2. Skill Rust &amp; Role Drift</h3><p>As seniors climb the ladder:</p><ul><li>They code less.</li><li>They architect more.</li><li>They rely on <strong>modern IDEs/tests/tooling</strong>.</li></ul><p>Following that, the candidates are brought to an interview and placed in front of a <strong>whiteboard</strong>. This is when disaster strikes.</p><p>👉 Fix it:</p><ul><li><strong>Candidates: </strong>Warm-up — <strong>2–3 weeks</strong> of daily short reps restores coding fluency.</li><li><strong>Companies:</strong> Let candidates use <strong>familiar tools</strong>.</li></ul><h3>🗣️ 3. Communication Gaps</h3><p>Often, seniors <em>know</em> the answer. Problem? They <strong>don’t show their thinking</strong>.</p><ul><li>Silent problem solving = interviewer thinks you’re stuck</li><li>Filling gaps = solving the <em>wrong</em> problem</li><li>Behavioral round = vague “war stories” instead of structured, metric-backed wins</li></ul><p><strong>Mini Frameworks 🧩</strong></p><ul><li><strong>CODE (for coding):</strong> Clarify → Outline → Drive → Evaluate</li><li><strong>STAR+M (for behavioural):</strong> Situation → Task → Action → Result → <strong>Metrics</strong></li></ul><h3>⚡ 4. Test-Taking Mechanics (The Hidden Curriculum)</h3><p>The <em>avoidable</em> pitfalls:<br> ❌ No clarifying questions<br> ❌ Dive into code with no plan<br> ❌ Forgetting edge cases &amp; complexity<br> ❌ Don’t timebox dead ends</p><p><strong>Habit Stack → Always Run This Checklist:</strong></p><ul><li>Restate problem + examples</li><li>List edge cases</li><li>Propose 2 approaches and talk about complexity</li><li>Choose → implement incrementally → test</li><li>Wrap with analysis and trade-offs.</li></ul><h3>🏗️ 5. System Design Pitfalls</h3><p>It is ironic that seniors are the ones who have the most difficulty with system design. What is the reason?</p><ul><li>They boil oceans 🫠 instead of scoping first</li><li>Hand-wave numbers instead of anchoring in reality</li><li>Forget non-functionals like <strong>availability goals</strong> or <strong>back-pressure plans</strong></li></ul><p>🔥 Framework: <strong>DANCE-SCALER</strong><br> Demand → APIs → Numbers → Constraints → Edges → Storage → Caching → Availability → Latency → Evolution → Reliability.</p><blockquote><strong><em>Pro tip:</em></strong><em> Keep quick math templates in your back pocket (QPS, storage, bandwidth). Numbers win credibility.</em></blockquote><h3>🎤 6. Behavioural Signals Seniors Miss</h3><p>Seniors accidentally self-sabotage by:</p><ul><li>Saying <strong>“we”</strong> without clarifying <strong>“I”</strong></li><li>Hiding failures (when real leaders show <strong>learning loops</strong>)</li><li>Delivering outcomes too vague (“improved performance”)</li></ul><p>👉 Replace with:<br> <strong>“Reduced p95 latency from 480ms to 190ms (↓60%), saving $3.2k/mo.”</strong></p><p><strong>Hack:</strong> Create a “<strong>story bank</strong>” of 8–12 STAR+M examples <em>with metrics</em>.</p><p>Here are some common questions that you may be asked:</p><ul><li>Can you provide an example of a time when you took on a leadership role for a team?</li><li>Tell me about a time you faced a significant technical challenge. How did you overcome it?</li><li>Describe a time you had to work collaboratively with others to achieve a goal.</li><li>Give me an example of a time you assumed leadership for a team.</li></ul><h3>🎲 7. Bias &amp; Miscalibration</h3><ul><li>Interviewer inconsistency</li><li>Domain mismatch (“fintech lead tested on ads puzzle”)</li><li>Ageism + résumé filtering</li></ul><p><strong>Control what you can: Candidates should focus on mechanics and clarity.</strong> For companies, enforce <strong>rubrics, training, and double scoring</strong>.</p><h3>🗓️ 8. Senior Prep Plan (2–4 Weeks)</h3><ul><li><strong>Days 1–3:</strong> Baseline → code+design dry run, build story bank</li><li><strong>Days 4–10:</strong> Daily drills → coding + system design + behavioral stories</li><li><strong>Days 11–14:</strong> Do mocks, record yourself, fix pacing</li><li><strong>Days 15–28:</strong> Tune to company’s formats/tech stacks</li></ul><h3>✅ 9. Quick Checklist</h3><p><strong>Coding</strong>: Constraints → 2 approaches → incremental testing → trade-offs<br> <strong>System Design</strong>: Demand, SLOs, quick math, failure modes<br> <strong>Behavioral</strong>: STAR+M, highlight <em>you</em>, include failure story</p><p>Print this. Tape it to your desk.</p><h3>🏢 10. For Hiring Teams</h3><p>Want better signals?</p><ul><li>Define senior rubrics (judgment, scope, teaching impact)</li><li>Prefer <strong>work samples &gt; puzzles</strong></li><li>Train interviewers and enforce structure</li><li>Let seniors use <strong>realistic tools</strong></li></ul><h3>🎯 Final Words</h3><p><strong>Senior developers don’t fail because they can’t build, </strong>They fail because interviews are a <strong>different game with different rules</strong>.</p><p>👉 As a candidate: <strong>Learn the rules, master the mechanics, and tell your story with clarity &amp; metrics.</strong><br> 👉 As a company: <strong>Measure what matters — judgement, trade-offs, and how seniors elevate teams.</strong></p><p>💡 Remember<em> this mantra:</em></p><blockquote><strong><em>“Interviews reward format mastery, not your résumé.”</em></strong></blockquote><p>Prepare accordingly — and watch how many doors open. 🚪✨</p><p><a href="https://www.davthecoder.com/blog/why-senior-developers-fail-technical-interviews">Check this blog post in my personal blog site</a></p><p>Happy coding!</p><p>David Cruz<br><a href="https://www.davthecoder.com/">davthecoder.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05f44dd55ffb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving LeetCode’s “Add Two Numbers” Problem in Kotlin: A Complete Guide]]></title>
            <link>https://davthecoder.medium.com/solving-leetcodes-add-two-numbers-problem-in-kotlin-a-complete-guide-a78c17600c54?source=rss-4c1be6bf35fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a78c17600c54</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[technical-interview]]></category>
            <category><![CDATA[faang-interview]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[David Cruz]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 10:03:21 GMT</pubDate>
            <atom:updated>2025-09-11T10:19:19.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xemR2Vt0Ed8I3UMMPj1Dwg.png" /><figcaption>image generated with AI to illustrate this problem</figcaption></figure><p>The &quot;Add Two Numbers&quot; problem on LeetCode is a classic linked list manipulation problem that comes up a lot in job interviews. This problem will test how well you understand linked lists, how to handle carries, and how to deal with edge cases. In this article, we&#39;ll look at several Kotlin solutions and explain them in detail, as well as look at their level of difficulty.</p><h3>What the Problem Is</h3><p>You have two linked lists that are not empty and represent two non-negative integers. The numbers are stored in reverse order, and each node has only one digit. Add the two numbers together and give back the sum as a linked list.</p><p>You can assume that the two numbers don&#39;t have any leading zeros, except for the number 0 itself.</p><h3>ListNode representation</h3><pre>class ListNode(var `val`: Int) {<br>    var next: ListNode? = null<br>}</pre><h3>Examples</h3><p><strong>Example 1:</strong></p><ul><li>Input: l1 = [2,4,3], l2 = [5,6,4]</li><li>Output: [7, 0, 8]</li><li>Explanation: 342 + 465 = 807</li></ul><p><strong>Example 2:</strong></p><ul><li>Input: l1 = [0], l2 = [0]</li><li>Output: [0]</li></ul><p><strong>Example 3:</strong></p><ul><li>Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]</li><li>Output: [8,9,9,9,0,0,0,1]</li></ul><h3>Constraints</h3><ul><li>The number of nodes in each linked list is in the range [1, 100]</li><li>0 ≤ Node.val ≤ 9</li><li>It is guaranteed that the list represents a number that does not have leading zeros</li></ul><h3>Why is “Add Two Numbers” Popular in Interviews?</h3><p>The <em>Add Two Numbers</em> problem (LeetCode #2) may look deceptively simple, but it tests a candidate’s ability to implement <strong>linked list manipulation, carry propagation, and iterative vs. recursive reasoning</strong> — all staple skills in coding interviews.</p><p>Many top-tier companies have used this exact problem or its variants in their interviews, including:</p><ul><li><strong>Amazon</strong></li><li><strong>Microsoft</strong></li><li><strong>Google</strong></li><li><strong>Bloomberg</strong></li><li><strong>Meta (Facebook)</strong></li><li><strong>Apple</strong></li></ul><p>This highlights its relevance for candidates preparing for competitive roles at FAANG and finance firms alike.</p><p>Unlike array-based problems that emphasise index manipulation, <em>Add Two Numbers</em> forces interviewees to think in terms of <strong>node-based data structures</strong>, edge cases (like adding 9999 + 1), and potential trade-offs between <strong>iterative and recursive approaches</strong>. This is the reason companies continue to ask this question years after its introduction.</p><p><strong>Keep in mind: </strong>Mastering this problem not only prepares you for algorithmic coding tests but also signals comfort with <strong>low-level pointer handling</strong>, <strong>data structure fundamentals</strong>, and <strong>writing clean, bug-free logic under time pressure</strong> — traits that interviewers value highly.</p><h3>Solution 1: Iterative Approach with Carry Handling</h3><p>This is the most straightforward and commonly used approach. We iterate through both linked lists simultaneously, adding corresponding digits along with any carryover from the previous addition.</p><pre>class Solution {<br>    fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {<br>        val dummy = ListNode(0)<br>        var current = dummy<br>        var carry = 0<br>        var p1 = l1<br>        var p2 = l2<br>        <br>        while (p1 != null || p2 != null || carry != 0) {<br>            val x = p1?.`val` ?: 0<br>            val y = p2?.`val` ?: 0<br>            val sum = carry + x + y<br>            <br>            carry = sum / 10<br>            current.next = ListNode(sum % 10)<br>            current = current.next!!<br>            <br>            p1 = p1?.next<br>            p2 = p2?.next<br>        }<br>        <br>        return dummy.next<br>    }<br>}</pre><h3>How It Works</h3><ol><li><strong>Initialize</strong>: Create a dummy node to simplify list construction and track carry</li><li><strong>Iterate</strong>: Process both lists simultaneously until both are exhausted and no carry remains</li><li><strong>Calculate</strong>: For each position, add the digits from both lists plus any carry</li><li><strong>Update</strong>: Set the new carry and create a node with the digit (sum % 10)</li><li><strong>Advance</strong>: Move to the next nodes in both lists</li></ol><h3>Time and Space Complexity</h3><ul><li><strong>Time Complexity</strong>: O(max(m, n)) where m and n are the lengths of the input lists</li><li><strong>Space Complexity</strong>: O(max(m, n)) for the result list</li></ul><h3>Solution 2: Recursive Approach</h3><p>This elegant solution uses recursion to handle the addition, making the code more concise and easier to understand for those familiar with recursive thinking.</p><pre>class Solution {<br>    fun addTwoNumbers(l1: ListNode?, l2: ListNode?, carry: Int = 0): ListNode? {<br>        // Base case: both lists are null and no carry<br>        if (l1 == null &amp;&amp; l2 == null &amp;&amp; carry == 0) {<br>            return null<br>        }<br>        <br>        val sum = carry + (l1?.`val` ?: 0) + (l2?.`val` ?: 0)<br>        val result = ListNode(sum % 10)<br>        <br>        result.next = addTwoNumbers(l1?.next, l2?.next, sum / 10)<br>        return result<br>    }<br>}</pre><h3>How It Works</h3><ol><li><strong>Base Case</strong>: Return null when both lists are exhausted and no carry remains</li><li><strong>Calculate</strong>: Add current digits and carry</li><li><strong>Create Node</strong>: Make a new node with the digit value</li><li><strong>Recurse</strong>: Call the function recursively for the next nodes with the new carry</li></ol><h3>Time and Space Complexity</h3><ul><li><strong>Time Complexity</strong>: O(max(m, n))</li><li><strong>Space Complexity</strong>: O(max(m, n)) due to recursion stack and result list</li></ul><h3>Solution 3: Functional Kotlin Approach</h3><p>Leveraging Kotlin’s functional programming features, we can create a more idiomatic solution:</p><pre>class Solution {<br>    fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {<br>        fun addWithCarry(node1: ListNode?, node2: ListNode?, carry: Int): ListNode? {<br>            if (node1 == null &amp;&amp; node2 == null &amp;&amp; carry == 0) return null<br>            <br>            val sum = (node1?.`val` ?: 0) + (node2?.`val` ?: 0) + carry<br>            return ListNode(sum % 10).apply {<br>                next = addWithCarry(node1?.next, node2?.next, sum / 10)<br>            }<br>        }<br>        <br>        return addWithCarry(l1, l2, 0)<br>    }<br>}</pre><p>This approach utilises Kotlin’s scope function to create more concise code while preserving readability.</p><h3>Solution 4: Tail-Recursive Optimization</h3><p>For better performance with large inputs, we can use tail recursion:</p><pre>class Solution {<br>    fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {<br>        val dummy = ListNode(0)<br>        <br>        tailrec fun addNodes(<br>            node1: ListNode?, <br>            node2: ListNode?, <br>            carry: Int, <br>            current: ListNode<br>        ) {<br>            if (node1 == null &amp;&amp; node2 == null &amp;&amp; carry == 0) return<br>            <br>            val sum = (node1?.`val` ?: 0) + (node2?.`val` ?: 0) + carry<br>            current.next = ListNode(sum % 10)<br>            <br>            addNodes(node1?.next, node2?.next, sum / 10, current.next!!)<br>        }<br>        <br>        addNodes(l1, l2, 0, dummy)<br>        return dummy.next<br>    }<br>}</pre><h3>Edge Cases to Consider</h3><p>When implementing this solution, ensure that it handles these edge cases:</p><ol><li><strong>Different length lists</strong>: [99] + [9] = [8, 0, 1]</li><li><strong>Carry at the end</strong>: [5] + [5] = [0,1]</li><li><strong>Single digit</strong>: [0] + [0] = [0]</li><li><strong>Multiple carries</strong>: [9,9,9] + [9,9,9] = [8,9,9,1]</li></ol><h3>Testing Your Solution</h3><p>Here’s a comprehensive test suite in Kotlin:</p><pre>fun main() {<br>    val solution = Solution()<br>    <br>    // Test case 1: [2,4,3] + [5,6,4] = [7,0,8]<br>    val l1 = ListNode(2).apply {<br>        next = ListNode(4).apply {<br>            next = ListNode(3)<br>        }<br>    }<br>    val l2 = ListNode(5).apply {<br>        next = ListNode(6).apply {<br>            next = ListNode(4)<br>        }<br>    }<br>    <br>    val result = solution.addTwoNumbers(l1, l2)<br>    printList(result) // Should print: 7 -&gt; 0 -&gt; 8<br>    <br>    // Add more test cases...<br>}<br><br>fun printList(head: ListNode?) {<br>    var current = head<br>    val values = mutableListOf&lt;Int&gt;()<br>    while (current != null) {<br>        values.add(current.`val`)<br>        current = current.next<br>    }<br>    println(values.joinToString(&quot; -&gt; &quot;))<br>}</pre><h3>Key Takeaways</h3><ol><li><strong>Understand the Problem</strong>: The digits are stored in reverse order, which simplifies addition</li><li><strong>Handle Carry Properly</strong>: Don’t forget to check for carry after processing both lists</li><li><strong>Use Dummy Nodes</strong>: They simplify linked list construction</li><li><strong>Consider Edge Cases</strong>: Test with different list lengths and carry scenarios</li><li><strong>Choose the Right Approach: </strong>Iterative is generally preferred for its simplicity and efficiency</li></ol><h3>Table comparison of solutions</h3><pre>| Approach        | Time Complexity | Space Complexity | Pros              | Cons                |<br>|-----------------|----------------|------------------|--------------------|---------------------|<br>| Iterative       | O(max(m,n))    | O(max(m,n))      | Simple, efficient  | More verbose        |<br>| Recursive       | O(max(m,n))    | O(max(m,n))      | Elegant, concise   | Stack overflow risk |<br>| Functional      | O(max(m,n))    | O(max(m,n))      | Idiomatic Kotlin   | May be less familiar|<br>| Tail-Recursive  | O(max(m,n))    | O(max(m,n))      | Stack-safe         | More complex        |</pre><h3>Beyond the code</h3><p>The “Add Two Numbers” problem is an excellent introduction to linked list manipulation and carry handling. The iterative approach is generally recommended for its simplicity and efficiency, but understanding the recursive solution helps develop problem-solving skills.</p><p>When solving similar problems, remember to:</p><ul><li>Draw out examples to understand the pattern</li><li>Handle edge cases. systematically</li><li>Test with various input sizes</li><li>Consider both time and space complexity</li></ul><p><em>The LeetCode Community&#39;s answers and discussions, along with other programming resources, served as inspiration for this article. Work on your algorithmic thinking by doing this problem and other linked list problems that are similar.</em></p><p><a href="https://www.davthecoder.com/blog/how-to-solve-add-two-numbers-in-kotlin-step-by-step">Link to this same article in my personal blog</a></p><p>Happy coding!</p><p>David Cruz<br><a href="https://www.davthecoder.com/">davthecoder.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a78c17600c54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode #146 — How to solve the “LRU Cache” problem in Kotlin?]]></title>
            <link>https://davthecoder.medium.com/leetcode-146-how-to-solve-the-lru-cache-problem-in-kotlin-313b0175ef96?source=rss-4c1be6bf35fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/313b0175ef96</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[technical-interview]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[code-interview]]></category>
            <dc:creator><![CDATA[David Cruz]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 08:48:16 GMT</pubDate>
            <atom:updated>2025-08-26T08:48:16.479Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode #146 — How to solve the “LRU Cache” problem in Kotlin?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1_LDGtTwDphCMliOSCkxA.png" /><figcaption>source: <a href="https://www.davthecoder.com/blog/how-to-solve-146-leetcode-lru-cache-in-kotlin">https://www.davthecoder.com/blog/how-to-solve-146-leetcode-lru-cache-in-kotlin</a></figcaption></figure><p>This problem is considered a Medium difficulty level.</p><h3>Why we need Smart Caching</h3><p>Speed is the most important thing in the world of high-performance computing. Modern apps, like dynamic websites and complex databases, need quick access to data to give users a good experience. However, getting data from primary storage, like a hard drive or a remote database, can be slow and costly. This is where caching comes in. A cache is a smaller, faster layer of memory that keeps temporary copies of data that is often accessed. It acts as a high-speed buffer between the application and the slower main data source. When systems serve requests from the cache, they can greatly lower latency and make things run more smoothly.</p><p>Caches are made to have a limited amount of space. This basic limitation creates a big problem: when the cache is full and a new piece of data needs to be stored, which item should be removed? A “cache eviction policy” controls this choice. First-In-First-Out (FIFO) is a simple policy that says to throw away the oldest item. The Least Recently Used (LRU) policy, on the other hand, is a smarter way to do things. LRU works on the idea of temporal locality, which means that data that was accessed recently is very likely to be accessed again soon. So, when space is needed, an LRU cache gets rid of the item that hasn’t been used in the longest time.</p><p>The LeetCode problem #146, LRU Cache, is a classic computer science problem that asks programmers to make and use this data structure. This challenge goes beyond just schoolwork; it&#39;s a small-scale version of real-world system design that requires careful balancing of conflicting needs like instant access, quick updates, efficient eviction, and fixed memory usage. The main issue is meeting these needs while keeping performance in mind, which is a great way to test a developer&#39;s knowledge of data structures and their trade-offs.</p><h3>Deconstructing the Challenge: The LRU Cache Problem</h3><p>The problem statement for LeetCode 146 is precise and demanding. It requires the implementation of a data structure that adheres to the constraints of a Least Recently Used cache. The implementation must expose a specific public interface:</p><ul><li>LRUCache(int capacity): This constructor initialises the cache with a fixed, positive size. The capacity defines the maximum number of key-value pairs the cache can hold at any given time.</li><li>int get(int key): This function should return the value associated with the given key. If the key exists in the cache, its value is returned. Crucially, this access must mark the key as having been &quot;recently used.&quot; If the key does not exist, the function must return -1.</li><li>void put(int key, int value): This function is responsible for either inserting a new key-value pair or updating an existing one. If it key already exists, it value is updated. If it key is new, the key-value pair is added to the cache. In either case, this operation also marks the key as &quot;recently used&quot;. If adding a new key causes the number of items to exceed the cache&#39;s capacity, the least recently used key must be evicted before the new item is inserted.</li></ul><p>The most critical requirement, which dictates the entire design of the solution, is the performance constraint: “The functions get putmust each run in O(1) average time complexity.&quot; This means that no matter how large the cache&#39;s capacity is, the time taken to retrieve or insert an item should remain constant on average.</p><p>To make these rules tangible, consider the following step-by-step walkthrough of the example provided in the problem description, using a cache with a capacity of 2.</p><pre>| Operation   | Action                                                 | Cache State (MRU -&gt; LRU) | Output |<br>| :---------- | :----------------------------------------------------- | :----------------------- | :----- |<br>| `put(1, 1)` | Add {1:1}. Cache size is 1.                            | `{1:1}`                  | `null` |<br>| `put(2, 2)` | Add {2:2}. Cache size is 2.                            | `{2:2}, {1:1}`           | `null` |<br>| `get(1)`    | Access {1:1}. It becomes the most recently used (MRU). | `{1:1}, {2:2}`           | `1`    |<br>| `put(3, 3)` | Cache is full. Evict LRU item {2:2}. Add {3:3} as MRU. | `{3:3}, {1:1}`           | `null` |<br>| `get(2)`    | Key 2 was evicted and is no longer in the cache.       | `{3:3}, {1:1}`           | `-1`   |<br>| `put(4, 4)` | Cache is full. Evict LRU item {1:1}. Add {4:4} as MRU. | `{4:4}, {3:3}`           | `null` |</pre><h3>The Quest for O(1): Why Simple Data Structures Fall Short</h3><p>The stringent O(1) time complexity requirement for both get and put operations immediately disqualifies several intuitive but ultimately inefficient approaches. A careful analysis of common data structures reveals that none, in isolation, can satisfy all the problem&#39;s constraints.</p><h3>Approach 1: Using an Array or List</h3><p>A simple array or list could maintain the order of items, with the most recently used item at one end and the least recently used at the other. However, this approach fails on multiple fronts. To perform an operation,get(key) one would need to scan the list to find the item with the matching key, an operation that takes linear time, or O(n), where n is the number of items in the cache. Similarly, after a successful move,get moving the accessed item from its current position to the front of the list would require shifting all preceding elements, which is also an O(n) operation.</p><h3>Approach 2: Using a Hash Map Alone</h3><p>A hash map (or dictionary) is the go-to data structure for O(1) average-time lookups, insertions, and deletions. It seems like a promising candidate because it can satisfy the fast access requirement of the get and put methods. However, a standard hash map provides no guarantees about the order of its elements. When the cache is full and an eviction is necessary, there is no efficient way to identify the &quot;least recently used&quot; item. Determining the LRU item would require iterating over all key-value pairs in the map, perhaps comparing timestamps stored alongside the values, which degrades performance to O(n).</p><h3>Approach 3: Using a Singly Linked List</h3><p>A singly linked list improves upon an array for reordering, as adding a new node to the head of the list is an O(1) operation. However, it still suffers from major drawbacks. First, finding a node by its key requires traversing the list from the head, an O(n) process. Second, and more critically, evicting the LRU item — which would be at the tail of the list — is inefficient. To remove the tail node in a singly linked list, one must first traverse to the second-to-last node to update its next pointer, which again takes O(n) time.</p><p>The analysis of these simple structures leads to a crucial realisation: the problem’s requirements are fundamentally in conflict when viewed through the lens of a single data structure. We need the rapid, key-based lookup capability of a hash map and the dynamic, ordered nature of a linked list. No structure alone possesses both properties. The solution, therefore, cannot be to choose one over the other but to compose them into a hybrid data structure that leverages the strengths of both.</p><h3>The Optimal Blueprint: The Hash Map and Doubly Linked List Synergy</h3><p>The canonical and most efficient solution to the LRU Cache problem is a powerful combination of two data structures: a hash map and a doubly linked list. This composite structure elegantly resolves the conflicting requirements by assigning each component a specific role, allowing them to work in synergy to achieve the desired O(1) performance for all operations.</p><h3>The Hash Map’s Role: O(1) Lookups</h3><p>The hash map serves as the primary index for the cache. Its purpose is to provide immediate, O(1) average-time access to any item in the cache given its key. However, instead of storing the item’s value directly, the hash map will store a reference (or pointer) to the corresponding node within the doubly linked list. This mapping, from key to Node, is the critical link that bridges the gap between fast, unordered lookups and the ordered list. When an operation like get(key) is called, the hash map is used to instantly locate the relevant node in the list without any traversal.</p><h3>The Doubly Linked List’s Role: O(1) Reordering and Eviction</h3><p>The doubly linked list is responsible for maintaining the recency order of all items in the cache. The list is organised such that the most recently used (MRU) item is always at the head and the least recently used (LRU) item is always at the tail.</p><p>The choice of a <em>doubly</em> linked list is deliberate and essential. Each node in a doubly linked list contains pointers to both the next and the prev nodes in the sequence. This bidirectional linking is what enables O(1) reordering. Once the hash map provides a direct reference to a node, that node can be removed from its current position and moved to the head of the list in constant time. This is because we can directly access its neighbors (node.prev and node.next) and &quot;patch&quot; the list by connecting them to each other, all without any traversal. Similarly, when an eviction is required, the LRU node at the tail of the list can be removed in O(1) time because its predecessor is immediately known via the tail.prev pointer.</p><p>To further simplify the implementation and eliminate edge cases (such as an empty list or a list with a single element), a common technique is to use two dummy nodes: a head a tail sentinel. These sentinels do not store any actual cache data but serve as fixed boundaries.</p><p>All real cache nodes are inserted between head and tail. This ensures that any node being added or removed always has non-null neighbours, streamlining the pointer manipulation logic.</p><p>This design creates two distinct but perfectly synchronised views of the same data. The hash map provides an unordered, key-based view for fast access, while the linked list provides an ordered, recency-based view for fast eviction and reordering. The integrity of the cache depends on every operation atomically updating both views to maintain consistency.</p><h3>Algorithm in Action: A Step-by-Step Walkthrough</h3><p>With the dual-structure blueprint established, the logic for the get and putmethods becomes a clear sequence of operations that manipulate both the hash map and the doubly linked list in concert.</p><h3>The get(key) Algorithm</h3><p>The get operation is a read request from the user&#39;s perspective, but it triggers an internal state change by updating the accessed item&#39;s recency.</p><ol><li>Lookup in Hash Map:</li></ol><ul><li>Check if it key exists as a key in the hashMap</li></ul><p>2. Handle Cache Miss:</p><ul><li>If the key is not found, the item is not in the cache. Return -1.</li></ul><p>3. Handle Cache Hit: If the key is found:</p><ul><li>Retrieve the reference to the corresponding node from the hashMap.</li><li>Move this node to the head of the doublyLinkedList. This action marks it as the most recently used item. This job is typically done by a helper function that first unlinks the node from its current position and then re-inserts it at the head.</li><li>Return the value stored within the node.</li></ul><h3>The put(key, value) Algorithm</h3><p>The put operation handles both the creation of new items and the update of existing ones. Its logic must branch to manage these two scenarios correctly and handle potential eviction.</p><ol><li>Lookup in Hash Map: Check if it key already exists in the hashMap.</li><li>Handle Existing Key (Update): If the key is found:</li></ol><p>3. Retrieve the reference to the existing node from the hashMap.</p><p>4. Update the value of this node with the new value provided.</p><p>5. Move this node to the head of the doublyLinkedList to mark it as the most recently used.</p><p>6. Handle New Key (Insert): If the key is not found:</p><p>7. Create a new one node containing the specified key and value.</p><p>8. Add this new one node to the head of the doublyLinkedList.</p><p>9. Add a new entry to the hashMap, mapping the key to the newly created node.</p><p>10. Check for Capacity Overflow: After adding the new node, check if the size of the cache now exceeds its capacity.</p><p>11. Perform Eviction: If the cache is over capacity:</p><ul><li>Identify the LRU node, which is the node at the tail doublyLinkedList (specifically, the node just before the dummy tail sentinel).</li><li>Remove this LRU node’s key from the hashMap.</li><li>Remove the LRU node itself from the doublyLinkedList.</li></ul><p>This algorithmic design ensures that every operation maintains the invariant: the hash map always contains keys present in the cache, and the linked list always reflects their use order from most to least recent.</p><h3>Implementation in Kotlin (Part 1): Building from First Principles</h3><p>For technical interviews and a foundational understanding, it is crucial to be able to implement the LRU Cache from scratch. The following Kotlin code demonstrates how to build the structure using a custom Node class, a for loop forMutableMap the hash map, and dummy head/tail nodes for the doubly linked list.</p><p>The use of non-nullable dummy head and tailnodes is a key implementation detail. It dramatically simplifies the pointer logic by transforming all insertion and removal operations into the &quot;general case&quot; of manipulating a node between two existing neighbours, thereby eliminating the need for special checks for edge cases, like an empty list.</p><p>Kotlin</p><pre>class LRUCache(private val capacity: Int) {<br>    // Inner class to represent a node in the doubly linked list<br>    private class Node(<br>        var key: Int,<br>        var value: Int,<br>        var prev: Node? = null,<br>        var next: Node? = null<br>    )<br>    // The cache map for O(1) key-to-node lookup<br>    private val cache: MutableMap&lt;Int, Node&gt; = HashMap()<br>    <br>    // Dummy head and tail nodes to simplify list manipulation<br>    private val head: Node = Node(-1, -1)<br>    private val tail: Node = Node(-1, -1)<br>    init {<br>        // Initialize the doubly linked list with dummy nodes<br>        head.next = tail<br>        tail.prev = head<br>    }<br>    // Helper function to remove a node from the list<br>    private fun removeNode(node: Node) {<br>        val prevNode = node.prev<br>        val nextNode = node.next<br>        prevNode?.next = nextNode<br>        nextNode?.prev = prevNode<br>    }<br>    // Helper function to add a node to the head of the list (MRU position)<br>    private fun addToHead(node: Node) {<br>        node.prev = head<br>        node.next = head.next<br>        head.next?.prev = node<br>        head.next = node<br>    }<br>    fun get(key: Int): Int {<br>        val node = cache[key]<br>        if (node == null) {<br>            // Key not found in cache<br>            return -1<br>        } else {<br>            // Key found, move the node to the head to mark it as most recently used<br>            removeNode(node)<br>            addToHead(node)<br>            return node.value<br>        }<br>    }<br>    fun put(key: Int, value: Int) {<br>        val node = cache[key]<br>        if (node!= null) {<br>            // Key already exists, update its value and move it to the head<br>            node.value = value<br>            removeNode(node)<br>            addToHead(node)<br>        } else {<br>            // Key does not exist, create a new node<br>            val newNode = Node(key, value)<br>            cache[key] = newNode<br>            addToHead(newNode)<br>            // If adding the new node exceeds capacity, evict the LRU item<br>            if (cache.size &gt; capacity) {<br>                val lruNode = tail.prev<br>                if (lruNode!= null) {<br>                    removeNode(lruNode)<br>                    cache.remove(lruNode.key)<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>Implementation in Kotlin (Part 2): The LinkedHashMap Shortcut</h3><p>While building data structures from scratch is an excellent exercise, effective software engineering often involves leveraging well-tested components from a language’s standard library. For implementing an LRU Cache, Kotlin (via the Java standard library) provides a powerful and concise tool LinkedHashMap</p><p>A LinkedHashMap is a special map implementation that maintains a doubly linked list running through all of its entries. By default, this list maintains insertion order. However, it has a special constructor that allows it to maintain an <em>access order</em>.</p><p>When constructed with the accessOrder parameter set to anytrue time an entry is accessed via getthe end of the internal linked list. This behaviour perfectly mirrors the recency update required by an LRU cache.</p><p>To enforce the capacity constraint, one can subclass LinkedHashMap and override a single protected method.removeEldestEntry() This method is called by the map after a new element is inserted, and if it returns true, the &quot;eldest&quot; entry (the least recently accessed item in access-order mode) is automatically removed. This provides a clean, declarative way to manage eviction.</p><p>The resulting code is remarkably elegant and robust, abstracting away all the manual pointer manipulation.</p><p>Kotlin</p><pre>import java.util.LinkedHashMap<br><br>class LRUCacheWithLinkedHashMap(private val capacity: Int) : <br>    LinkedHashMap&lt;Int, Int&gt;(capacity, 0.75f, true) {<br><br>    /**<br>     * This method is invoked by put and putAll after inserting a new entry into the map.<br>     * It provides the implementor with the opportunity to remove the eldest entry each time<br>     * a new one is added. This is ideal for implementing a cache with a fixed capacity.<br>     *<br>     * @param eldest The least recently accessed entry in the map.<br>     * @return true if the eldest entry should be removed, false otherwise.<br>     */<br>    override fun removeEldestEntry(eldest: MutableMap.MutableEntry&lt;Int, Int&gt;?): Boolean {<br>        return size &gt; capacity<br>    }<br>}<br><br>// The get and put methods are inherited from LinkedHashMap and work as required.<br>// No additional implementation is needed for the core LRU logic.</pre><p>This LinkedHashMap solution demonstrates the power of abstraction. While understanding the underlying mechanics (as shown in the manual implementation) is vital, knowing when to use a pre-built, optimized tool is the hallmark of a productive engineer.</p><h3>Final Analysis: Time and Space Complexity</h3><p>The performance of the optimal solution, whether implemented manually or with LinkedHashMap, is identical and meets the problem&#39;s strict requirements.</p><h3>Time Complexity: O(1)</h3><ul><li>get(key): This operation consists of a hash map lookup and a constant number of pointer manipulations in the linked list. A hash map lookup takes O(1) on average. The list operations (unlinking and re-linking a node) involve updating a fixed number of pointers, which is also an O(1) operation. Therefore, the total average time complexity for get is O(1).</li><li>put(key, value): This operation involves a hash map lookup/insertion (average O(1)), potentially creating a new node (O(1)), and performing a constant number of pointer manipulations to add a node to the head and, if necessary, remove a node from the tail. All of these are constant-time operations. Thus, the total average time complexity for put is also O(1).</li></ul><p>It is important to note the nuances of “average time complexity.” This phrasing acknowledges that in the worst-case scenario of catastrophic hash collisions, hash map operations can degrade to O(n). However, with a well-designed hashing function, this is exceedingly rare in practice, and the performance is considered amortised constant time.</p><h3>Space Complexity: O(capacity)</h3><p>The space required by the data structure is directly proportional to the maximum number of items it can store.</p><ul><li>The hash map stores capacity key-to-node references.</li><li>The doubly linked list stores up to capacity nodes. Since both structures scale linearly with the capacity, the overall space complexity is O(capacity).</li></ul><h3>Beyond the Interview</h3><p>The LRU Cache problem is a cornerstone of technical interviews for a valid reason. It tests not just knowledge of individual data structures but also the ability to analyse a complex set of requirements and synthesise a novel solution by composing simpler components. The process of rejecting naive approaches and arriving at the elegant hash map and doubly linked list pattern is an exemplary lesson in algorithmic design and trade-off analysis.</p><p>The pattern itself — using a hash map for fast lookups and a linked list to maintain a dynamic order — is a powerful and widely applicable technique. It appears in various real-world systems, including operating system page replacement algorithms, database buffer pools, and web browser caches.</p><p>Furthermore, understanding the LRU Cache provides a solid foundation for tackling more advanced caching strategies, such as the Least Frequently Used (LFU) cache, which introduces the additional complexity of tracking access frequencies. Ultimately, mastering problems like LeetCode 146 is about more than memorising a solution; it is about cultivating a deep intuition for how data structures can be combined to build efficient, high-performance systems. This skill is indispensable for any software engineer aiming to create robust and scalable applications.</p><h4>Sources:</h4><ul><li><a href="https://www.davthecoder.com/blog/how-to-solve-146-leetcode-lru-cache-in-kotlin">https://www.davthecoder.com/blog/how-to-solve-146-leetcode-lru-cache-in-kotlin</a></li><li><a href="https://leetcode.com/problems/lru-cache">https://leetcode.com/problems/lru-cache</a></li><li><a href="https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU">https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU</a></li><li><a href="https://www.bigocheatsheet.com/">https://www.bigocheatsheet.com/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=313b0175ef96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KMP for AppleTV]]></title>
            <link>https://davthecoder.medium.com/kmp-for-appletv-87c74a267ac7?source=rss-4c1be6bf35fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/87c74a267ac7</guid>
            <category><![CDATA[tvos]]></category>
            <category><![CDATA[apple-tv]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[David Cruz]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 16:52:54 GMT</pubDate>
            <atom:updated>2024-07-14T13:13:48.862Z</atom:updated>
            <content:encoded><![CDATA[<p>In the ever-changing world of software development, Kotlin Multiplatform (KMP) has emerged as a powerful tool for creating cross-platform applications. With the rise of Kotlin&#39;s popularity, many developers are looking for ways to use KMP to streamline their development process. In this post, I introduce you to my latest project: <a href="https://github.com/davthecodercom/KMP-for-AppleTV">KMP-for-AppleTV</a>, a repository designed to help developers create Apple TV apps using Kotlin Multiplatform.</p><h3>What is KMP-for-AppleTV?</h3><p>KMP-for-AppleTV is a sample project that demonstrates how to use Kotlin Multiplatform to build applications for Apple TV. The primary goal of this repository is to provide a clear and concise example of integrating KMP into an Apple TV app, showcasing the benefits of code sharing between different platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbUog5bKdTyP4JHqOo2pyA.gif" /></figure><h3>Key Features</h3><ol><li><strong>Cross-Platform Code Sharing</strong>: Write business logic once and share it across iOS, Android, and Apple TV platforms.</li><li><strong>Simple Setup</strong>: The repository is structured to help you get started quickly with KMP for Apple TV.</li><li><strong>Modern Development Practices</strong>: Utilises the latest Kotlin and KMP features, ensuring your codebase is up-to-date with industry standards.</li><li><strong>Clear Documentation</strong>: Comprehensive README and inline comments to guide you through the project setup and development process.</li></ol><h3>Why Use Kotlin Multiplatform for Apple TV?</h3><p>Kotlin Multiplatform offers several advantages for developing Apple TV apps:</p><ul><li><strong>Code Reusability</strong>: Share a significant portion of your codebase between mobile and TV apps, reducing development time and effort.</li><li><strong>Consistency</strong>: Maintain consistent business logic and data models across platforms, minimising the risk of discrepancies and bugs.</li><li><strong>Productivity</strong>: Leverage Kotlin’s modern language features to write concise, expressive, and safe code.</li></ul><h3>Getting Started</h3><p>To get started with KMP-for-AppleTV, follow these steps:</p><ol><li><strong>Clone the Repository</strong>:</li></ol><pre>git clone https://github.com/davthecodercom/KMP-for-AppleTV.git <br>cd KMP-for-AppleTV</pre><p><strong>2. Open the Project</strong>: Open the project in your preferred IDE (IntelliJ IDEA or Android Studio).</p><p>3. <strong>Setup Apple TV Environment</strong>:</p><ul><li>Ensure you have Xcode installed.</li><li>Open the iosApp project in Xcode and configure your Apple TV target.</li></ul><p>4. <strong>Run the Application</strong>: Build and run the application on an Apple TV simulator or a physical device.</p><h3>What changes has been made?</h3><p>you can follow this commit to see what changes need to be made in order to add KMP into your Xcode project for AppleTV:</p><p><a href="https://github.com/davthecoder/KMP-for-AppleTV/commit/897eaefa49da84d6de64b92e701bc5119f4ff929">https://github.com/davthecoder/KMP-for-AppleTV/commit/897eaefa49da84d6de64b92e701bc5119f4ff929</a></p><h3>Code Structure</h3><p>The repository is organised into the following modules:</p><ul><li><strong>shared</strong>: Contains the shared business logic and data models.</li><li><strong>iosApp</strong>: Apple TV specific code and UI implementation.</li><li>/shared/src/commonMain/kotlin contains the shared code.</li><li>/shared/src/iosMain/kotlin contains the iOS-specific code.</li><li>/shared/src/tvosMain/kotlin contains the tvOS-specific code.</li></ul><h3>Contributing</h3><p>I welcome contributions to the KMP-for-AppleTV project. If you have suggestions, bug fixes, or enhancements, please feel free to open an issue or submit a pull request. Your feedback is invaluable in making this project better for everyone.</p><h3>Conclusion</h3><p>KMP-for-AppleTV is a stepping stone for developers looking to explore the potential of Kotlin multiplatform for Apple TV development. By leveraging KMP, you can create robust, maintainable, and high-performance applications with shared codebases, reducing both development time and complexity.</p><p>Check out the <a href="https://github.com/davthecodercom/KMP-for-AppleTV">KMP-for-AppleTV</a> repository on GitHub and start building your cross-platform Apple TV apps today!</p><p>I am David Cruz <a href="https://medium.com/u/4c1be6bf35fc">davthecoder</a> a software engineer with a passion for mobile application development. I have been working with Kotlin Multiplatform for a while now and I am excited about the future of this technology. I am always looking for ways to improve my skills and learn new things. I am open to collaboration and new opportunities.</p><ul><li><a href="https://github.com/davthecodercom">David Cruz</a></li><li><a href="https://twitter.com/davthecoder">Twitter</a></li><li><a href="https://www.linkedin.com/in/davthecoder/">LinkedIn</a></li><li><a href="https://www.davthecoder.com/">Website</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87c74a267ac7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The SOLID Principles Dartified]]></title>
            <link>https://davthecoder.medium.com/the-solid-principles-dartified-dbd376004ebc?source=rss-4c1be6bf35fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbd376004ebc</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[solid-principles-in-dart]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[David Cruz]]></dc:creator>
            <pubDate>Sat, 21 Oct 2023 15:39:03 GMT</pubDate>
            <atom:updated>2023-10-21T16:00:55.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*RYRfpqE2Mv6fyi3UHcrDwg.png" /><figcaption>source:<a href="https://i0.wp.com/i.postimg.cc/zB23GX8D/Solid-principles.png?w=1230&amp;ssl=1">https://i0.wp.com/i.postimg.cc/zB23GX8D/Solid-principles.png?w=1230&amp;ssl=1</a></figcaption></figure><p>Hey, fellow devs! Are you interviewing for a Flutter developer? Dart? and/or perhaps are on the brink of embarking on a new Flutter project or keen on refining your existing skills?</p><p>Firstly, kudos to you — it’s the persistent learners who genuinely progress in this constantly changing profession.</p><p>In this post, as a Flutter app developer, I’ll walk you through the process of building a fruit shop app. This playful context will not only bring some vibrancy to our exploration but also serve as a concrete setting for the SOLID principles we’re going to delve into. I’ll break down each principle using scenarios directly tied to our fruit-themed project, turning theoretical concepts into practical understanding.</p><p>While not all apps require strict adherence to these principles, understanding them and knowing when to use them can significantly enhance your Flutter codebase. So, are you ready to navigate the orchard of SOLID principles and see how they blend with Dart and Flutter in our fruit shop app journey?</p><p>Let’s dive into the first principle, tailored for our delightful fruit shop app built with Flutter :)</p><h3>S — Single Responsibility Principle (SRP)</h3><p>The Single Responsibility Principle advocates that a class should have only one reason to change. This principle acts as a linchpin in maintaining a clean, manageable, and organised codebase. In the context of our fruit shop app, adhering to the SRP can significantly ease the process of debugging and enhancing the code over time.</p><p>Let’s illustrate this with a simple example where we follow SRP and another where it doesn’t:</p><p><strong>BAD:</strong></p><pre>class FruitAndInvoice {<br>  final String fruitName;<br>  final double fruitPrice;<br>  final List&lt;double&gt; allFruitPrices;<br><br>  FruitAndInvoice(this.fruitName, this.fruitPrice, this.allFruitPrices);<br><br>  void displayFruit() {<br>    print(&#39;Fruit: $fruitName, Price: $fruitPrice&#39;);<br>  }<br><br>  double calculateTotal() {<br>    return allFruitPrices.fold(0, (total, price) =&gt; total + price);<br>  }<br><br>  void displayInvoice() {<br>    displayFruit();<br>    print(&#39;Total: ${calculateTotal()}&#39;);<br>  }<br>}</pre><p>In this FruitAndInvoice class, multiple responsibilities are bundled together, making it harder to manage and debug. A change in displaying fruit information or altering invoice calculation logic necessitates a modification in this class. This tangled design, compared to the earlier separated Fruit and Invoice classes showcase how the Single Responsibility Principle leads to a more organized, manageable, and scalable codebase, simplifying the evolution of our fruit shop app.</p><p><strong>GOOD:</strong></p><pre>class Fruit {<br>  final String name;<br>  final double price;<br><br>  Fruit(this.name, this.price);<br><br>  void displayFruit() {<br>    print(&#39;Fruit: $name, Price: $price&#39;);<br>  }<br>}<br><br>class Invoice {<br>  final List&lt;Fruit&gt; fruits;<br><br>  Invoice(this.fruits);<br><br>  double calculateTotal() {<br>    return fruits.fold(0, (total, fruit) =&gt; total + fruit.price);<br>  }<br><br>  void displayInvoice() {<br>    for (final fruit in fruits) {<br>      fruit.displayFruit();<br>    }<br>    print(&#39;Total: ${calculateTotal()}&#39;);<br>  }<br>}</pre><p>In the above snippet code, the Fruit the class holds fruit data, while the Invoice the class manages a fruit list and total price calculation. Each class follows the Single Responsibility Principle, having a distinct reason to change. For example, altering fruit data display only requires a tweak in the Fruit class, and modifying invoice calculation logic solely involves the Invoice class. Adhering to the SRP simplifies navigating our fruit shop app and fosters a clean, maintainable codebase as the app evolves over time.</p><h3>O — Open/Closed Principle (OCP)</h3><p>The Open/Closed Principle posits that software entities should be open for extension but closed for modification. This principle is pivotal in promoting a robust and maintainable codebase. In the scenario of our fruit shop app, adhering to the OCP can significantly streamline the process of extending functionalities without tampering with existing code.</p><p>Let’s elucidate this with a simple example where we follow the OCP and another where we don’t:</p><p><strong>BAD:</strong></p><pre>class Fruit {<br>  final String name;<br>  final double price;<br><br>  Fruit(this.name, this.price);<br><br>  double discountPrice(double discount) {<br>    return price - (price * discount);<br>  }<br>}<br><br>class SeasonalFruit extends Fruit {<br>  SeasonalFruit(String name, double price) : super(name, price);<br><br>  // Override discountPrice method to offer a greater discount<br>  @override<br>  double discountPrice(double discount) {<br>    return price - (price * discount * 1.5);<br>  }<br>}</pre><p>In this flawed snippet code, the SeasonalFruit class overrides the discountPrice method from the Fruit class to offer a greater discount. However, this approach modifies the existing behaviour of the Fruit class, which violates the Open/Closed Principle.</p><p><strong>GOOD:</strong></p><pre>abstract class Fruit {<br>  final String name;<br>  final double price;<br><br>  Fruit(this.name, this.price);<br><br>  double discountPrice(double discount);<br>}<br><br>class RegularFruit extends Fruit {<br>  RegularFruit(String name, double price) : super(name, price);<br><br>  @override<br>  double discountPrice(double discount) {<br>    return price - (price * discount);<br>  }<br>}<br><br>class SeasonalFruit extends Fruit {<br>  SeasonalFruit(String name, double price) : super(name, price);<br><br>  @override<br>  double discountPrice(double discount) {<br>    return price - (price * discount * 1.5);<br>  }<br>}</pre><p>In this snippet code, we’ve declared an abstract Fruit class with a discountPrice method. The RegularFruit and SeasonalFruit classes extend the Fruit class and implement the discountPrice method. This design adheres to the Open/Closed Principle by allowing new fruit types to extend the existing behaviour without modifying the Fruit class, the Fruit the class provides a blueprint for discount calculations, while the RegularFruit and SeasonalFruit classes offer specific implementations.</p><p>Each class aligns with the Open/Closed Principle, enabling distinct discount calculations. For instance, introducing a new fruit category with a different discount logic only entails creating a new class extending Fruit. Following the OCP not only facilitates extending our fruit shop app but also preserves a clean, adaptable codebase as the app matures over time.</p><h3>L — Liskov Substitution Principle (LSP)</h3><p>The Liskov Substitution Principle (LSP) prescribes that objects of a derived class should be able to replace objects of the base class without affecting the correctness of the program. This principle is instrumental in ensuring the interchangeability of objects, thereby promoting code reusability and maintainability. In the milieu of our fruit shop app, adhering to LSP can significantly simplify the process of introducing new types of fruits or other products without upsetting the existing code structure.</p><p>Let’s delineate this with a simple example where we follow LSP and another where we don’t:</p><p><strong>BAD:</strong></p><pre>class Fruit {<br>  final String name;<br>  final double price;<br><br>  Fruit(this.name, this.price);<br><br>  double discountPrice(double discount) {<br>    return price - (price * discount);<br>  }<br>}<br><br>class SpecialFruit extends Fruit {<br>  SpecialFruit(String name, double price) : super(name, price);<br><br>  @override<br>  double discountPrice(double discount) {<br>    if (discount &gt; 0.5) {<br>      throw Exception(&quot;Discount for special fruit can&#39;t be more than 50%&quot;);<br>    }<br>    return price - (price * discount);<br>  }<br>}</pre><p>In this flawed snippet code, the SpecialFruit class overrides the discountPrice method from the Fruit class and throws an exception if the discount is more than 50%. This violation of LSP makes the SpecialFruit class not substitutable for the Fruit class without altering the program&#39;s correctness.</p><p><strong>GOOD:</strong></p><pre>abstract class Fruit {<br>  final String name;<br>  final double price;<br><br>  Fruit(this.name, this.price);<br><br>  double discountPrice(double discount);<br>}<br><br>class RegularFruit extends Fruit {<br>  RegularFruit(String name, double price) : super(name, price);<br><br>  @override<br>  double discountPrice(double discount) {<br>    return price - (price * discount);<br>  }<br>}<br><br>class SpecialFruit extends Fruit {<br>  SpecialFruit(String name, double price) : super(name, price);<br><br>  @override<br>  double discountPrice(double discount) {<br>    final adjustedDiscount = discount &gt; 0.5 ? 0.5 : discount;<br>    return price - (price * adjustedDiscount);<br>  }<br>}</pre><p>In this snippet code, the SpecialFruit class modifies the discount logic without breaking the contract set by the Fruit class. The SpecialFruit class can now safely replace the Fruit class without affecting the program&#39;s correctness, adhering to the Liskov Substitution Principle, and the Fruit class sets a blueprint for discount calculations, whilst the RegularFruit and SpecialFruit classes provide specific implementations.</p><p>Each class aligns with the Liskov Substitution Principle, allowing seamless substitution and ensuring a coherent discount calculation logic. For instance, adding a new fruit category with a unique discount logic only entails creating a new class extending Fruit. Following the LSP facilitates a smoother extension of our fruit shop app&#39;s capabilities whilst preserving a clean, modular codebase as the app flourishes over time.</p><h3>I — Interface Segregation Principle (ISP)</h3><p>The Interface Segregation Principle (ISP) asserts that clients should not be forced to depend on interfaces they do not use. This principle is crucial for reducing the coupling between classes and making the codebase more modular, manageable, and adaptable to changes. In the scenario of our fruit shop app, adhering to ISP can significantly streamline the process of extending or modifying functionalities without creating ripple effects across the codebase.</p><p>Let’s elucidate this with a simple example where we follow ISP and another where we don’t:</p><p><strong>BAD:</strong></p><pre>abstract class FruitOperations {<br>  void displayFruit();<br>  double calculateDiscountPrice(double discount);<br>  void updateInventory(int quantity);<br>}<br><br>class Apple implements FruitOperations {<br>  final String name = &#39;Apple&#39;;<br>  final double price = 2.0;<br>  <br>  @override<br>  void displayFruit() {<br>    print(&#39;Fruit: $name, Price: $price&#39;);<br>  }<br>  <br>  @override<br>  double calculateDiscountPrice(double discount) {<br>    return price - (price * discount);<br>  }<br>  <br>  /**<br>    * code to update inventory<br>  **/<br>  @override<br>  void updateInventory(int quantity) {<br>    // no-op<br>  }<br>}</pre><p>In this flawed snippet code, the FruitOperations interface bundles multiple operations together, forcing the Apple class to implement all of them, even if some operations are not relevant to it. This design violates the Interface Segregation Principle.</p><p><strong>GOOD:</strong></p><pre>abstract class FruitDisplay {<br>  void displayFruit();<br>}<br><br>abstract class FruitDiscount {<br>  double calculateDiscountPrice(double discount);<br>}<br><br>abstract class FruitInventory {<br>  void updateInventory(int quantity);<br>}</pre><p>In the snippet above, we’ve segregated the operations into separate interfaces: FruitDisplay, FruitDiscount, and FruitInventory. The Apple the class can now implement only the relevant interfaces, adhering to the Interface Segregation Principle.</p><pre>class Apple implements FruitDisplay, FruitDiscount {<br>  final String name = &#39;Apple&#39;;<br>  final double price = 2.0;<br>  <br>  @override<br>  void displayFruit() {<br>    print(&#39;Fruit: $name, Price: $price&#39;);<br>  }<br>  <br>  @override<br>  double calculateDiscountPrice(double discount) {<br>    return price - (price * discount);<br>  }<br>}<br><br>class InventoryManager implements FruitInventory {<br>  @override<br>  void updateInventory(int quantity) {<br>    // code to update inventory<br>  }<br>}</pre><p>In the snippet above, each interface delineates a specific contract, allowing the Apple class and InventoryManager class to implement only the operations pertinent to them. This segregation not only aligns with the Interface Segregation Principle but also fosters a more modular and manageable codebase, simplifying the addition or modification of functionalities in our fruit shop app as it blossoms over time.</p><h3>D — Dependency Inversion Principle (DIP)</h3><p>The Dependency Inversion Principle (DIP) encourages high-level modules not to depend on low-level modules, but both should depend on abstractions. This principle is fundamental for promoting a loosely coupled architecture, making the codebase more modular, testable, and flexible. In the context of our fruit shop app, adhering to DIP can significantly facilitate the process of extending or modifying the app’s functionalities without causing widespread disruptions in the codebase.</p><p>Let’s illustrate this with a simple example where we follow DIP and another where we don’t:</p><p><strong>BAD:</strong></p><pre>class Inventory {<br>  final List&lt;Fruit&gt; fruits;<br><br>  Inventory(this.fruits);<br><br>  void listFruits() {<br>    for (final fruit in fruits) {<br>      print(&#39;Fruit: ${fruit.name}, Price: ${fruit.price}&#39;);<br>    }<br>  }<br>}<br><br>class FruitShop {<br>  final Inventory inventory;<br><br>  FruitShop(this.inventory);<br><br>  void displayInventory() {<br>    inventory.listFruits();<br>  }<br>}</pre><p>In this flawed snippet code, the FruitShop class is tightly coupled to the Inventory class, making it hard to adapt to the FruitShop class to changes in the Inventory class.</p><p><strong>GOOD:</strong></p><pre>abstract class FruitListing {<br>  void listFruits();<br>}</pre><p>In the snippet above, we’ve introduced an abstraction FruitListing which the Inventory class implements. The FruitShop the class now depends on the abstraction rather than the concrete Inventory class, aligning with the Dependency Inversion Principle.</p><pre>class Inventory implements FruitListing {<br>  final List&lt;Fruit&gt; fruits;<br><br>  Inventory(this.fruits);<br><br>  @override<br>  void listFruits() {<br>    for (final fruit in fruits) {<br>      print(&#39;Fruit: ${fruit.name}, Price: ${fruit.price}&#39;);<br>    }<br>  }<br>}<br><br>class FruitShop {<br>  final FruitListing fruitListing;<br><br>  FruitShop(this.fruitListing);<br><br>  void displayInventory() {<br>    fruitListing.listFruits();<br>  }<br>}</pre><p>In the snippet above, the FruitListing abstraction decouples the FruitShop class from the Inventory class, enabling the FruitShop class to interact with different implementations of the FruitListing interface. This not only adheres to the Dependency Inversion Principle but also fosters a more flexible, testable, and maintainable codebase, easing the process of evolving our fruit shop app&#39;s capabilities over time.</p><h3>Wrapping Up</h3><p>We’ve travelled through the orchard of SOLID principles, exploring how each principle, when applied appropriately, can significantly strengthen the structural integrity and maintainability of our Dart code, especially in a Flutter context with our whimsical fruit shop app as a backdrop.</p><p>The SOLID principles are more than mere theoretical concepts. They are the bedrock of a clean, well-organised, and adaptable codebase. By understanding and applying these principles, you not only make your code more understandable to your fellow devs (and yourself of course) but also ensure that your application can grow and evolve.</p><p>As we navigated each principle with real-world examples, the essence of a well-structured codebase in a growing Flutter application was disclosed. The beauty of SOLID lies in its simplicity over time and its powerful impact on the code we write.</p><p>Whether you’re just starting a new Flutter project or refactoring an existing one, keeping the SOLID principles in mind can be a game changer. It’s a step towards writing code that is not only functional but also clean, manageable, and ready to stand the test of time.</p><p>Thank you for reaching the end of this post. I hope this article has shed light on the importance of these fundamental principles and how they can be Dartified in your next Flutter project.</p><p>Happy coding!</p><p>davthecoder</p><p>If you have enjoyed this blog post, remember to follow me and clap this post ;).</p><p>Web: <a href="https://www.davthecoder.com/">https://www.davthecoder.com</a><br>GitHub: <a href="https://github.com/davthecodercom">https://github.com/davthecodercom</a><br>Youtube: <a href="https://youtube.com/@davthecoder">https://youtube.com/@davthecoder</a><br>Twitch: <a href="https://www.twitch.tv/davthecoder">https://www.twitch.tv/davthecoder</a><br>Instagram: <a href="https://www.instagram.com/davthecoder">https://www.instagram.com/davthecoder</a><br>Twitter: <a href="https://twitter.com/davthecoder">https://twitter.com/davthecoder</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbd376004ebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Interview Questions. Part 1]]></title>
            <link>https://davthecoder.medium.com/kotlin-interview-questions-part-1-95820d211e2d?source=rss-4c1be6bf35fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/95820d211e2d</guid>
            <category><![CDATA[interview-tips]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[David Cruz]]></dc:creator>
            <pubDate>Sat, 26 Nov 2022 21:22:39 GMT</pubDate>
            <atom:updated>2022-11-27T14:07:54.135Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Kotlin logo before a river" src="https://cdn-images-1.medium.com/max/1024/0*MMFLwCfTzMo6B94o" /><figcaption>Photo by <a href="https://unsplash.com/@mreichelt?utm_source=medium&amp;utm_medium=referral">Marc Reichelt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you are reading these lines is because you already know Kotlin and you are already or are expecting to face an interview in this field. First of all, congratulations, that means a company is giving you a chance to prove yourself, and along the following lines, I want to give you the hand and support you need to pass this critical step.</p><p>I do not want to bore you with long history about myself (I already wrote an article about that) you just need to know I did some interviews with different Android developers.</p><p>While not all the questions will be asked, it is important for you to know the concepts and meanings behind the questions and to know how to apply them, so with the answers, I did add a small example about what it is about.</p><p>Ready? then let’s start in this first part from the basics.</p><h3>1. What is Kotlin?</h3><p>Kotlin is a Statically typed programming language(<strong><em>*1</em></strong>) created by JetBrains with zero-cost Java interoperability and open-source under a license Apache 2 OSS. Currently targets Java Virtual Machine(<strong><em>JVM</em></strong>), Android and a Web Browser.</p><h3>2. How to declare a Variable?</h3><p>Variables in Kotlin can be declared by using <strong><em>var</em></strong> or <strong><em>val </em></strong>declaration.</p><pre>val name = &quot;David&quot; //IMMUTABLE<br>var surname = &quot;Cruz&quot; //MUTABLE</pre><h3>3. What is the difference between var and val declarations?</h3><p>The difference between them is <strong><em>val</em></strong> is used to declare immutable variables, while a variable with var can be re-assigned by another value of the same type. Example:</p><pre>val name = &quot;David&quot;<br>name = &quot;Roberto&quot; //This is NOT permited<br><br>var age = 39<br>age = 40 //This is permited</pre><h3>4. Can you declare the Type of a variable beforehand?</h3><p>Yes, after using the declaration and the name of your choice, you can use a colon mark following the type before the equals mark. Some examples are the following:</p><pre>val name: String = &quot;David&quot; //String (chain)<br>val age: Int = 28 //Integer (Numbers)<br>val temp: Double = 37.1 //Double (decimal numbers)<br>val isMale: Boolean = true //Boolean (true or false)</pre><h3>5. How to convert a String into an Integer type? and an Integer into a String type?</h3><p>With Kotlin, you can convert a valid number String using the inline function <strong><em>toInt()</em></strong>, and to an Integer into a String you can use <strong><em>toString()</em></strong> for example:</p><pre>// Int to String<br>val numText: String = &quot;909&quot;<br>val num: Int = numText.toInt()<br><br>println(num) //Output: 909<br>println(num is Int) //Output: true<br><br>// String to Int<br>val age: Int = 34<br>val ageText: String = age.toString()<br><br>println(ageText) //Output: 34<br>println(ageText is String) //Output: true</pre><h3><em>6. What is a constant?</em></h3><p>Constants in Kotlin are used to define a variable that has a constant value using the declaration const.</p><pre>//Initials of Java Virtual Machine<br>const val INITIALS = &quot;JVM&quot;</pre><h3>7. What is the difference between val and const val declarations?</h3><p>Both are immutable variables, but the difference is using <strong><em>val</em></strong> with the modifier const (<strong><em>const val</em></strong>) the properties are set in compile-time while using <strong><em>val</em></strong> on his own is set in runtime (<strong><em>const</em></strong> modifier cannot be used with <strong><em>var</em></strong>, neither can be used used in local variables<strong><em>).</em></strong></p><h3>8. What is the entry point in a Kotlin project?</h3><p>The entry point is the function main with an array of Strings as an argument.</p><pre>fun main(args: Array&lt;String&gt;) {<br>    println(&quot;Hello World!&quot;)<br>}<br><br>// Output: Hello World!</pre><h3>9. What usability have the array of strings passed as a parameter in the entry point?</h3><p><strong><em>args: Array&lt;String&gt;</em></strong> passed as a parameter in the entry point is used to retrieve the command line arguments.</p><h3>10. What is Null Safety in Kotlin?</h3><p>One of the biggest advantages of Kotlin is Null Safety which is an approach to prevent dreaded Null Pointer Exceptions by using nullable types, <br>e.g.: <strong><em>String?</em></strong>, <strong><em>Int?</em></strong>, <strong><em>Double?</em></strong>, <strong><em>Boolean?,</em></strong> <strong><em>Char?, …</em></strong></p><pre>var age: Int? = 45 // Nullable<br>age = null //This IS permited<br><br>var temp: Double = 40.1<br>temp = null //This is not permited</pre><p>These types can be used as wrapper types to hold null values. If on retrieving the value, the value is null, we can choose to ignore it and use a different value instead by using an Elvis operator<strong><em> </em></strong>(<strong><em>?:</em></strong>)</p><pre>var name: String? = &quot;David&quot;<br>println(name ?: &quot;No name&quot;)<br>//Output: David<br><br>name = null<br>println(name ?: &quot;No name&quot;)<br>//Output: No name</pre><h3>11. Are variables Nullable by default in Kotlin?</h3><p>No, if you declare a variable without specifying the type, the variable will be set to the type detected but non-nullable. Variables with nullable type must be declared beforehand.</p><pre>var name = &quot;David&quot; //Similar as var name: String = &quot;david&quot;<br>name = null //This IS NOT permited :(<br><br>var name: String? = &quot;David&quot;<br>name = null //This IS Permited :)</pre><h3>12. What is an Elvis Operator?</h3><p>Elvis operator is used to return a non-null value in the case scenario where the first or left value is null and is declared by a question mark and a colon (<strong><em>?:</em></strong>) e.g.:</p><pre>val firstName: String? = null<br>val secondName: String? = null<br>var thirdName: String? = &quot;David&quot;<br>pintln(firstName ?: secondName ?: thirdName)<br>//Output: David</pre><blockquote>Explanation: As the first and second values are null it jumps into the third value printing in the console output the word “David”</blockquote><blockquote>Fact: You can concatenate all Elvis operations as you like, however, it is intended to use it only in case the first value is null to give a non-null default value.</blockquote><h3>13. Kotlin has interoperability with Java. Does Kotlin allow us to use primitive types?</h3><p>No, we cannot use or declare primitive types at the language level, as in Kotlin, all are Objects. However, the JVM bytecode where it is compiled has them.</p><h3>14. For what are the double exclamation marks !! used?</h3><p>The double exclamation marks (<em>!!</em>) are used to force unwrap the nullable type to get the value, and this is something to be used with caution because if the value is null, it will crash in the runtime.</p><pre>var city: String? = &quot;London&quot;<br>println(city!!)<br>//Output: London<br><br>city = null<br>print(city!!)<br>//Output: Exception in thread &quot;main&quot; java.lang.NullPointerException</pre><h3>15. How are functions declared?</h3><p>functions in Kotlin are declared by the keyword fun, and the function can return or not a value. If the function returns a value, that type must be declared after the parenthesis and before the curly brackets with a colon.</p><p>In Kotlin, if the function does not returns a value is considered that this function returns a Unit type. However, adding a Unit as a return value is redundant.</p><pre>fun sayHello(paramOne: String, paramTwo: String): String {<br>  return &quot;Hello $paramOne $paramTwo&quot;<br>}<br>println(sayHello(&quot;David&quot;, &quot;Cruz&quot;))<br>//Output: &quot;Hello David Cruz&quot;<br><br>// Function that return Unit (Not Return value)<br>fun nameOfFunction(paramOne: String, paramTwo: String) {<br>  println(sayHello(&quot;David&quot;, &quot;Cruz&quot;))<br>}<br>println(nameOfFunction(&quot;David&quot;, &quot;Cruz&quot;))<br>//Output: &quot;Hello David Cruz&quot;<br><br><br>/* FOR REFERENCE ONLY<br>fun nameOfFunction(paramOne: String, paramTwo: String): Unit {<br>  println(sayHello(&quot;David&quot;, &quot;Cruz&quot;))<br>}<br>*/</pre><p>This is the end of the first part of the Kotlin Interview Questions series.</p><p>If you found these 15 questions easy, that is a good sign; on every part, the complexity will increase, so keep an eye on the next episode :)</p><p>Happy Interview!</p><p>Let’s Keep in touch:<br>davthecoder Web: <a href="https://www.davthecoder.com/">https://www.davthecoder.com</a><br>Medium Blog: <a href="https://davthecoder.medium.com/">https://davthecoder.medium.com/</a><br>Twitch: <a href="https://www.twitch.tv/davthecoder">https://www.twitch.tv/davthecoder</a><br>GitHub: <a href="https://github.com/davthecodercom">https://github.com/davthecodercom</a><br>Instagram: <a href="https://www.instagram.com/davthecoder">https://www.instagram.com/davthecoder</a><br>Twitter: <a href="https://twitter.com/davthecoder">https://twitter.com/davthecoder</a><br>Youtube: <a href="https://youtube.com/@davthecoder">https://youtube.com/@davthecoder</a><br>Support me on Patreon! <a href="https://www.patreon.com/davthecoder">https://www.patreon.com/davthecoder</a></p><p>(<strong><em>*1</em></strong>) <em>A statically-typed language is a language where variable types are known at compile time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95820d211e2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>