RSSAmplifier

Blog

Bohdan Stupak's blog

Recent content on Bohdan Stupak's blog

wkalmar.github.ioRSS feed ↗34 posts

Latest posts

You don't need to create all properties inside a DTO to successfully deserialize

The example below might seem like very simple advice, but I found people across many codebases do not know this. This, in turn, leads to excessive usage of JsonNode class, forcing developers to lose benefits of compiler support in a strongly typed language. Consider the JSON below string json = """ { "Name": "Alice", "Age": 30, "NonExistentStringField": "foo", "NonExistingIntField": 48 } """;…

Partitioning PotgreSQL Database

Introduction In one of the projects I used to work on, we’ve employed CQRS approach with PostgreSQL as a write storage and NoSQL database as a read storage. As a safety measure, we had a special endpoint that allowed us to regenerate entire content of the read storage based on the write storage that is supposed to be the single source of truth. The story started one day when we discovered…

Using RAG architecture for generative tasks

Large language models are used widely across the industry these days. Yet still, many people are skeptical about their capabilities as they are quite prone to hallucination. For that reason, in this article, I decided to use LLM in a case where there are no incorrect answers: generating artistic text. However, even in the case of art which is highly subjective, there are still some quality gates…

Describing musical domain with F#

One of my recent projects was to create software that would automatically generate music based on a predefined set of rules. The degree of randomness I’ve planned to introduce would let me create different melodies every time, while the set of rules I was planning to create would ensure that it still would sound nice. You can access the complete source code here. Below we’ll dive more…

Composing poésie concrète with AWS Step Function

Concept Observing signs of russo-Ukrainian war fatigue I decided to come up with a poem called “Is the war over?”. I’ve labeled it as poésie concrète drawing an analogy with musique concrète - genre where music is composed of non-musical pieces of sound. In the same way, my poem is composed of search engine results for “russian war crimes” in the latest week which are…

Dynamic polymorphism: key concept to master OOP

The world of object-oriented programming is a bit confusing. It requires mastering a lot of things: SOLID principles, design patterns to name a few. This gives birth to a lot of discussions: are design patterns still relevant, is SOLID intended solely for object-oriented code? It is said that one should prefer composition to inheritance but what is the exact rule of thumb when one should choose…

Visualizing your photos on a map with React Native

Back in the looney days before russian full-scale invasion, I’ve used to travel a lot domestically and internationally. Also at that time, I had a Nokia Lumia phone with a nice widget that displayed the locations of the photos I’ve taken on a map. I enjoyed looking at it realizing how big is the world and how much I have to travel in order to discover it. While I have a similar widget…

Applying custom similarity calculation in Elasticsearch

Presently we’ve been discussing improving elasticsearch autocomplete functionality. For most cases, this is enough. However, in our case, things turned out to be not that rosy and we’ll have a look at why. Setup In our system we single document type per index. Since we have quite a lot of types in our system and the number of types and their mappings can be changed by the end-user, we…

Implementing clean architecture in Go

It has been written a lot about the clean architecture. Its main value is the ability to maintain free from side effects domain layer that allows us to test core business logic without leveraging heavy mocks. This is accomplished by writing dependency-free core domain logic and external adapters (be it database storage or API layer) that rely on the domain and not vice versa. In this article,…

Property-based tests and clean architecture are perfect fit

It has been written a lot about the clean architecture. Its main value is the ability to maintain free from side effects domain layer that allows us to test core business logic without leveraging heavy mocks. However, when it comes to designing tests for pure domain logic quite often we don’t tend to be so picky. Unit testing contains many traps such as overspecified software. But even when…

Leveraging lazy evaluation

I’m usually skeptical about leetcode tasks since this is not something you’ll encounter in your daily line-of-business code. But the idea behind this particular task has fascinated me. So I’ll break it down here. I’ll provide a bit simplified version of the task so you could capture the gist of it more easily. Write an API that generates fancy sequences using the append,…

It's not about how you inject your services, it's about how you test them

It has been written a lot about the value of unit testing and still a lot of developers may have witnessed codebases with unit tests being too brittle or rarely discovering actual defects in software. Also some have questioned default architectural style supposed to make code testable. These are the reasons why a lot of developers openly question unit-testing while others just silently sabotage…

Improving Elasticsearch-based autocomplete

Recently I’ve investigated autocomplete functionality of our system as there were a lot of complaints that it returns irrelevant results. The approach we’ve taken was pretty naive: our backend wrapped query into wildcard symbols and executed it as query_string on fields __title, title and commonInfo.RealName. Index we’ve executed search upon contained entity with _title equal 3…

Overriding JSON serializer in Giraffe

I use my side-project KyivStationWalk as a set of my opinionated takes on software architecture. No wonder I use F# here. One of the types I use in this project to describe my domain is the subway station branch. There are 3 branches in Kyiv named by their traditional colors. type Branch = | Red | Blue | Green By default Giraffe, the framework which I use as a web server, uses Newtonsoft.

Strive for short-lived synchronous communication

When interacting with a service asynchronous communication often is a preferred way. “Enterprise integration patterns” book puts it that way (which also might be a TL;DR; for the rest of the article) With synchronous communication, the caller must wait for the receiver to finish processing the call before the caller can receive the result and continue. In this way, the caller can only…

Prefer using Stream to byte[]

When working with files there are often both APIs operating byte[] and Stream so quite often people chose byte[] counterpart as it requires less ceremony or just intuitively more clear. You may think of this conclusion as far-fetched but I’ve decided to write about it after reviewing and refactoring some real-world production code. So you may find this simple trick neglected in your codebase…

DateTime.TryParse and the case of Z letter

Recently I’ve been tasked to provide date in a specific format from backend to the frontend and I’ve noticed a behavior that I’ve found a bit odd. private static void OutputDateInfo(string value) { Console.WriteLine($"Input: {value}"); if (DateTime.TryParse(value, out DateTime dateTimeValue)) { Console.WriteLine($"Setialized to universal format…

Batch processing with Directory.EnumerateFiles

In case one wants to retrieve files from catalog Directory.GetFiles is a simple answer sufficient for most scenarios. However, when you deal with a large amount of data you might need more advanced techniques. Example Let’s assume you have a big data solution and you need to process a directory that contains 200000 files. For each file, you extract some basic info public record…

Converting video with FFmpegCore

Working with multimedia is terra incognita for most of the developers since it’s something that one rarely encounters while working with usual business applications. So when I was tasked to convert video for the project I’m currently working on I was expecting to deal with some sort of old poorly maintained C++ library. So FFmpegCore was a pleasant surprise since it enables working…

Using Span<T> to improve performance of C# code

In my experience, the main thing to do in order to improve application performance is to reduce the number and duration of IO-calls. However, once this option is exercised another path that developers take is using memory on stack. Stack allows very fast allocation and deallocation although it should be used only for allocating small portions since stack size is pretty small. Also, using stack…

Refactoring string into the specific type

Introduction While the article title may sound controversial as there is clearly nothing wrong with using string in your code below I&rsquo;ll show the case where string type doesn&rsquo;t clearly communicate all the necessary properties of a domain in question. Then I&rsquo;ll show how this can be handled. You can watch full code on Github. The code Recently I was tasked to write the code which…

Building auth endpoint with Go and AWS Lambda

When I was playing around with my pet-project Kyiv Station Walk I’ve noticed that manually removing test data is tedious and I need to come up with a concept of the admin page. This required some sort of authentication endpoint. Some super-lightweight service which would check login and password against as a pair of super-user credentials. Serverless is quite useful for this simple nanoservice.…

Distributed locking with Redlock.net

Why locking things Microservice architecture becomes widely adopted these days. One of the benefits it offers is the possibility of horizontal scaling which allows us to increase the performance of our application dramatically. However, there are situations when multiple instances of service face contention for some shared resource. In such a case one of the instances would acquire a lock over…

Ignoring Operation Result when using F# async Computation Expression

Consider this simple code downloading page contents using Puppeteer-sharp. let renderHtml = async { BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision) |> Async.AwaitTask |> ignore let options = LaunchOptions() options.Headless <- true let! browser = Puppeteer.LaunchAsync(options) |> Async.AwaitTask let! page = browser.NewPageAsync() |> Async.AwaitTask page.GoToAsync("https://i.ua") |>…

Understanding Dependency Injection in .NET Core with Quartz.NET example

Introduction Quartz.NET is a handy library that allows you to schedule recurring tasks via implementing IJob interface. Yet the limitation of it is that, by default, it supports only parameterless constructor which complicates injecting external service inside of it, i.e., for implementing repository pattern. In this article, we&rsquo;ll take a look at how we can tackle this problem using standard…

Cooking angular.js with Typescript

Introduction Typescript starts to gain more and more popularity because of static typing offering its benefits. Still, some developers who are involved in supporting projects with angular.js may be stuck with lack of community offering their recipes of using angular.js together with typescript. This article will try to fill this gap. Our strategy involves shipping working product at every stage of…

Refactoring F# Imperative Code Towards Declarative

Recently, perusing the internet, I found an article which implements the trapezoidal rule in F#. open System let main() = //Function to integrate let f x = 10.0*x*x let trapezoidal a b N = let mutable xi = a let h = (b - a)/N let mutable suma = h/2.0*(f(a)+f(b)) for x in 1 .. System.Convert.ToInt32(N) do let mutable xi1 = xi + h suma <- suma + h*f(xi1) xi <- xi1 suma //some usage example let fromA…

End-to-end Testing of Your Web Applications with Canopy

Why Canopy Stabilization Layer Built on Top of Selenium One of the most crucial concepts of canopy is reliability - when performing an action framework tries during time span specified via elementTimeout or compareTimeout or pageTimeout before failing which improves experience during writing tests. Expressiveness The syntax looks pretty self-explanatory: "Bio should contain twitter link" &&& fun _…

&#34;Method can be made static&#34; May Hide OO Design Flaw

Introduction Wandering through codebases, I&rsquo;ve encountered some examples of code where Microsoft Code Analysis issues the above-mentioned warning. Although the fix seems straightforward, the warning itself may hide a more subtle issue connected to object responsibility assignment. Toy Example Let&rsquo;s take a look at the following code: public class EmailConstructor { private const string…

Querying Last.fm web API with F#

Introduction Let&rsquo;s imagine that you have an edgy musical taste so you would like to recommend to your friends only those artists which are the most mainstream. If you have a profile on last.fm, then you could write a small tool which would query and process your listening statistics to automate this task. My tool for this job is F# programming language and I&rsquo;ll show you some benefits…

Registry Redirection when using 32-bit Application on 64-bit Windows

This article will guide you through Windows registry redirection feature, which might seem quite unintuitive at first acquaintance. ##The Code Consider the following situation. We have code that writes to HKEY_LOCAL_MACHINE registry on 64-bit OS. var softwareSubKey = Registry.LocalMachine.OpenSubKey ("Software", RegistryKeyPermissionCheck.ReadWriteSubTree);…

Pure CSS Salesforce-like progressbar Control

Introduction This article covers several CSS techniques: using LESS, using display: flex and some CSS hacks. You can download the complete source code on github. Using LESS LESS is CSS preprocessor which allows extending CSS with some useful features. You can learn more about it here. In this project, I use LESS variables and functions which as you can see later, allow me to work with colors in a…

Money Precision Issues

Many developers like MONEY data type as it tends to be faster during computations and byte cheaper (arguably). Still in the next few examples, I am going to show an issue that can lead to possible loss of precision. Let us try the following code: decalare @d1 money, @d2 money, @res money set @d1 = 18.4172 set @d2 = 1.00 set @res = @d2/@d1 select @res The actual result is 0,054297 and by all…

Some Common Mistakes When Querying SQL Database

Introduction When I started learning SQL, I found out several issues which I thought to be interesting to share. For our needs, let&rsquo;s use AdventureWorks2012 database, which can be obtained here. 1. Don&rsquo;t Forget about NULL Let us execute the following query: select Count(*) from Sales.SalesOrderDetail The result will be: Filtering by CarrierTrackingNumber: select Count(*) from…