<?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 Paschal Uwakwe on Medium]]></title>
        <description><![CDATA[Stories by Paschal Uwakwe on Medium]]></description>
        <link>https://medium.com/@C0l0red?source=rss-295cbb479273------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*EKwV7MG_OjgXnAgA</url>
            <title>Stories by Paschal Uwakwe on Medium</title>
            <link>https://medium.com/@C0l0red?source=rss-295cbb479273------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:51:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@C0l0red/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[Teaching a Computer to Find Words (My Way)]]></title>
            <link>https://medium.com/@C0l0red/teaching-a-computer-to-find-words-my-way-1e19b9eeafa0?source=rss-295cbb479273------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e19b9eeafa0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Paschal Uwakwe]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 12:32:15 GMT</pubDate>
            <atom:updated>2026-02-21T12:32:15.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*_O34YlKp7UbKfEiDR6azmA@2x.jpeg" /></figure><p>Okay, so for context, I’m a big fan of word games. Scrabble, Word Cookies, Wordament (before it got ugly), 4 Pics 1 Word, Word Hunt, Word Bites and Anagrams on Game Pigeon, and I basically attempt any unfinished crossword puzzles I come across.</p><p>Once in a while, playing games like Scrabble or Anagrams, I want to know in retrospect, all possible plays I could’ve made while the game was on, and so I use online word unscramblers to find out — I would never use it to cheat, relax. And then when I got into Software Engineering, I began to wonder how easy it would be to create my own word unscrambler, you know, for the fun of it. Turns out it was not as easy for me as I thought it would be, every algorithm I could conjure up from the internet to unscramble a word would break past 10 letter words.</p><p>Just in case the word unscrambling is not familiar, in this context, it refers to having a word or sequence of letters, and finding out how many ways some or all letters can be rearranged to form new words. For instance, “team” can be unscrambled to “mate” or “meat” or “ate” or “at” or “a”. And like I said, every algorithm I could find worked well for my Kotlin code, but would always crash once I got to 10 letter words, and this made me give up on the dream; bad habit looking back, I know, I could’ve just continued with it and later found ways to make it run faster or lighter.</p><p>Around April 2024, I became unemployed, and in the pursuit of a new job, I asked friends to look out for me, and a close friend of mine told me he had a gig for me, if I could learn Rust; a language known for being difficult to learn. I wasn’t exactly booming with options and it sounded fun, so I read the Rust Book, and when I was done, I was hyped and wondered what to try building with this new, exciting language, to get more comfortable with it before the gig. And then, I recalled my old abandoned word unscrambler project that was “too slow to run in Kotlin or Java” which were the fastest languages I knew at the time — Python and Javascript obviously being much slower.</p><p>On my first attempt to convert the same code from Kotlin to Rust, it ran almost twice as fast, and while it did significantly slow down at 10 letters, it succeeded, no crash. 11, 12 and then it started to crash. This was motivation to work on my algorithm, and so I decided to make it more fun, and come up with the algorithm myself, rather than waiting for Chat GPT or Stack Overflow to save me, I wanted a challenge, and I got one.</p><h3>Word Unscrambling</h3><p>The summary was this; I used a Trie to store all the words in the Scrabble dictionary, for very fast word lookups and prefix lookups — meaning, if at least one word in the dictionary begins with this, then the search is successful, so “elec” would be successful since “elect”, “election”, “electricity” and more, start with “elec”, but full words also count as valid prefixes since the full word is a word that begins with itself, and since a full word like “elect” is still a prefix to “election”.</p><p>Then as for the actual word unscrambling algorithm, I scribbled on my notebook to find a pattern, the easiest thing that came up to me was this algorithm</p><p>You keep track of two evolving strings: the current word you’re building and the letters you haven’t used yet. At each step, the current word takes one letter from the remainders, adds it to the end and you check if it’s a valid word, then the algorithm continues with whatever letters are left. This repeats until there are no letters remaining, which means you’ve formed one complete arrangement of the original letters. Then you check whether that final string is a valid word too, step back, and try a different letter choice. By doing this over and over, the process eventually tries every possible ordering of the letters and discovers which of them form real words. This algorithm was so much simpler and so much more faster, it handled 15 letters without crashing, but noticeably slower.</p><pre>Each new point means one more level of depth of recursion.<br>Each point removed is one less level of depth of recursion<br><br>Start with the current word as empty, and the remainders as the word you want<br>to unscramble.<br>Say we wanted to find unscramble the word &quot;eat&quot;.<br><br>You start off with current = &quot;&quot; remainders=&quot;eat&quot;<br><br>1.     current = &quot;e&quot; remainders = &quot;at&quot;<br>1.1.   current = &quot;ea&quot; remainders = &quot;t&quot; <br>1.1.1. current = &quot;eat&quot; remainders = &quot;&quot; // Valid word (eat)<br>1.2.   current = &quot;et&quot; remainders = &quot;a&quot; <br>1.2.1. current = &quot;eta&quot; remainders = &quot;&quot; <br><br>2.     current = &quot;a&quot; remainders = &quot;et&quot; <br>2.1.   current = &quot;ae&quot; remainders = &quot;t&quot;<br>2.1.1. current = &quot;aet&quot; remainders = &quot;&quot;<br>2.2.   current = &quot;at&quot; remainders = &quot;e&quot; // Valid word (at)<br>2.2.1. current = &quot;ate&quot; remainders = &quot;&quot; // Valid word (ate)<br><br>3.     current = &quot;t&quot; remainders = &quot;ea&quot;<br>3.1.   current = &quot;te&quot; remainders =&quot;a&quot;<br>3.1.1. current = &quot;tea&quot; remainders = &quot;&quot; // Valid word (tea)<br>3.2.   current = &quot;ta&quot; remainders = &quot;e&quot;<br>3.2.1. current = &quot;tae&quot; remainders = &quot;&quot;</pre><p>One additional step to make this algorithm faster was pruning paths. This means when a new letter is added to the current word, rather than immediately checking if it’s a valid word, we first check if it’s a valid prefix, if so, we check if it’s a valid complete word as well and then continue. If it is not a valid prefix, there’s no need to continue with that path because no letter added to it can ever result in a valid word, and would only be a waste of time. If we were unscrambling “bloody” for instance, and we got to a point where the current word was “yd” and the remainders were “bloo”, we wouldn’t continue in that path because we know for certain that no English word begins with “yd” and adding any more letters to it will only be a waste of time and space.</p><p>At this rate, the algorithm was handling 15 letters in less than half of a second, easy, and only got noticeably slower at 21 letters, but could still be fast depending on the number of pruned paths, which varies from word to word. At this point, I was happy. But then I realized I could also use it to figure out words that can be formed from letters in a grid, so I thought to try that out as well.</p><h3>Finding Words in a Grid</h3><p>This one was easy, coming off the unscrambling algorithm, all I had to do was find an deterministic way to try every possible play on the grid, and transform that into an algorithm. My idea was to always move in the same set of directions, until you hit a dead end, then go back and find new paths using other directions, try this for every single cell in the grid. I chose to start at the top left cell, and always move down, then right, then up, then left, and repeat, hit a dead end, then go back a step, try all directions to see if there is any free cell, if yes, move in the first free direction and repeat, if no, take another step back, and do the same, until you’re back at the cell you started with. Then move to the next cell and do the same thing. Here is my rough sketch from that day, almost two years ago, to help visualize all the paths that can be explored from the top left cell only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfBCiX5z4azWwJgdRPTThQ.jpeg" /></figure><p>I later realized what I had come up with was essentially backtracking, and it was easier to run, but ran even better when I introduced pruning paths, also, avoiding a lot of unnecessary path exploration. I soon added diagonal movements, using the same idea, since some games allow you to find a path diagonally along the grid, this was a piece of cake as well.</p><p>These two simple ideas helped me feel confident building in Rust, and gave me a tool that I truly care about, as a fan of word games, and helped me think up solutions on my own. One issue I ran into soon enough was how to move the grid in my games into the two dimensional array my code expected, and ML came to mind; take a screenshot, feed it to a model that understands what a grid of letters is, and then the model translates the grid into a 2D array, but I never got around to doing that. Hopefully someday.</p><p>Thanks for reading. Here is the link to the <a href="https://github.com/C0l0red/word-finder">GitHub repository</a> if you’re interested in seeing the final solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e19b9eeafa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Race Conditions]]></title>
            <link>https://medium.com/@C0l0red/database-race-conditions-f459d94ee2d0?source=rss-295cbb479273------2</link>
            <guid isPermaLink="false">https://medium.com/p/f459d94ee2d0</guid>
            <category><![CDATA[database-transaction]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[database-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Paschal Uwakwe]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 08:20:36 GMT</pubDate>
            <atom:updated>2024-02-11T19:46:28.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Two cars racing" src="https://cdn-images-1.medium.com/max/1024/1*ykPydFhH9CzswYfejPjinw.png" /><figcaption>from: altis-dxp.com</figcaption></figure><p>Ever wondered what happens when multiple users or multiple requests or processes try to update or delete a database record at the same time? Yeah, me too. I’ll be explaining what happens in situations like that and how to plan ahead to best manage the situation depending on the nature of your application. Let’s start by understanding what a race condition is.</p><h4>Race Conditions</h4><p>Simply put, a race condition is a flaw in concurrent programming that occurs when multiple processes or threads of a program attempt to access a resource at the same time. In the context of databases, it is a condition where multiple database transactions or operations try to access and modify the same data concurrently. This could lead to serious problems.</p><p>Imagine a bank application where two owners of a joint account with a $100 balance try to withdraw $90 each at the same time. Without proper handling of race conditions, the best case scenario is that one request is faster and completes first, then the second fails because of insufficient funds, the worst case scenario is that they reach the database at the same time and both successfully withdraw $90 each — $180 in total — from an account with a $100 balance, which would be a loss for the bank, and a very dangerous loophole in the application. How can this be avoided?</p><h4>How to handle database race conditions</h4><p>There are many ways to avoid or deal with race conditions, each method with its own tradeoffs. I’ll stick with these popular ones.</p><h4>Atomic Operations</h4><p>An atomic operation is an uninterruptible and indivisible operation that executes as a single unit, meaning the operation either suceeds completely or fails completely. Most SQL statements like <strong>INSERT</strong>, <strong>UPDATE</strong>, <strong>DELETE</strong> and <strong>SELECT</strong> are atomic, and these can be utilised in some scenarios to avoid race conditions, but these situations are limited to simple operations if race conditions are a concern, operations as simple as incrementing a field are safe.</p><p>The advantage of this approach is that it is easy to implement and mostly avoids race conditions, but is limited to simple queries where only one record or column is updated. For more complex operations, a transaction would be needed to mitigate race conditions.</p><pre>// Example of using atomic operations in NestJS with TypeORM<br>@Injectable()<br>export class CounterService {<br>  constructor(<br>    @InjectRepository(Counter)<br>    private readonly counterRepository: Repository&lt;Counter&gt;,<br>  ) {}<br><br>  async incrementCounter(id: number): Promise&lt;void&gt; {<br>    await this.counterRepository.increment({ id }, &#39;value&#39;, 1);<br>  }<br>}</pre><pre>-- Example of using atomic operations in SQL<br>UPDATE counters<br>SET value = value + 1<br>WHERE id = :id;</pre><h4>Transactions</h4><p>A transaction is a statement or group of statements that are executed as a single unit of work. Transactions ensure data integrity by providing <em>ACID</em> properties; <strong>Atomicity</strong> — all operations are treated as a single unit and either fail or succeed as a whole, <strong>Consistency</strong> — the database transitions from one valid state to another valid state, <strong>Isolation</strong> — transactions are isolated from one another to avoid interference, the degree of isolation is determined by the isolation level, <strong>Durability</strong> — changes made by a transaction are permanently saved after a commit.</p><p>Transaction isolation levels provide different degrees of isolation and are suitable for different scenarios, with each level providing more isolation than the previous.</p><ol><li><strong>Read Uncommitted</strong> provides no isolation and lets transactions read uncommitted and committed changes from one another.</li><li><strong>Read Committed</strong> — the default — lets transactions see only committed changes.</li><li><strong>Repeatable Read</strong> lets transaction see committed changes made by other transactions as they existed at the start of the transaction, meaning any changes committed by other transactions after the start of this one can’t be viewed by this one.</li><li><strong>Serializable</strong> provides the most isolation as transactions are completely isolated from each other and transactions appear to execute serially, this could lead to reduced concurrency and potential performance degradation.</li></ol><p>This approach provides advantages like concurrency control, by ensuring that transactions do not interfere with each other’s data access or modifications, along with the <em>ACID</em> properties. Its downsides include complexity, overhead from locking and resource usage. It is great for scenarios where data integrity is important and outweighs the need to concurrently access data, it’s also great for multiple step operations where all operations must succeed together. Most approaches to mitigate race conditions utilise transactions.</p><pre>// Example of transferring funds between two accounts using transactions in NestJS with TypeORM<br>@Injectable()<br>export class AccountService {<br>  constructor(<br>    @InjectRepository(Account)<br>    private readonly accountRepository: Repository&lt;Account&gt;,<br>  ) {}<br>   <br>  async transferFunds(fromAccountId: number, toAccountId: number, amount: number) {<br>    return this.accountRepository.manager.transaction(async transactionalEntityManager =&gt; {<br>      const fromAccount = await transactionalEntityManager.findOne(Account, fromAccountId, { lock: { mode: &#39;pessimistic_write&#39; } });<br>      const toAccount = await transactionalEntityManager.findOne(Account, toAccountId, { lock: { mode: &#39;pessimistic_write&#39; } });<br>      <br>      if (!fromAccount || !toAccount) {<br>        throw new Error(&#39;One of the accounts does not exist.&#39;);<br>      }<br>      if (fromAccount.balance &lt; amount) {<br>        throw new Error(&#39;Insufficient funds.&#39;);<br>      }<br><br>      fromAccount.balance -= amount;<br>      toAccount.balance += amount;<br>      <br>      await transactionalEntityManager.save(fromAccount);<br>      await transactionalEntityManager.save(toAccount);<br>      <br>      return &#39;Transfer successful!&#39;;<br>    });<br>  }<br>}</pre><pre>-- Example of transferring funds between two accounts using transactions in native SQL<br><br>-- Begin a transaction<br>BEGIN TRANSACTION;<br><br>-- Lock both accounts for write access<br>SELECT * FROM accounts WHERE id IN (:fromAccountId, :toAccountId) FOR UPDATE;<br><br>-- Check if both accounts exist and have sufficient funds<br>SELECT balance INTO @fromAccountBalance FROM accounts WHERE id = :fromAccountId;<br>SELECT balance INTO @toAccountBalance FROM accounts WHERE id = :toAccountId;<br><br>IF @fromAccountBalance &lt; :amount THEN<br>    ROLLBACK;<br>    SELECT &#39;Insufficient funds.&#39; AS result;<br>ELSE<br>    -- Update balances<br>    UPDATE accounts SET balance = balance - :amount WHERE id = :fromAccountId;<br>    UPDATE accounts SET balance = balance + :amount WHERE id = :toAccountId;<br>    <br>    -- Commit the transaction<br>    COMMIT;<br>    SELECT &#39;Transfer successful!&#39; AS result;<br>END IF;</pre><h4>Locking (Pessimistic Locking)</h4><p>This is a very common solution to race conditions in general, it involves putting a lock or restricting access to a record after the first transaction accesses it for modification, any other transaction attempting to access the record has to wait for the first to complete and commit its changes.</p><p>As you’d imagine, this could lead to deadlocks and bottlenecks as other transactions have to wait for the lock to be released. Its advantages include concurrency control, simplicity and data integrity, and is a suitable choice for data modification operations where data integrity is important and outweighs the need for concurrent data access, it can also be used in high concurrency scenarios where conflicts are likely. Here’s an example utilising transactions to help control the lock, locks can work outside transactions but can be a bit trickier to manage.</p><pre>import { EntityManager } from &#39;typeorm&#39;;<br><br>// Example of using locking using NestJS and TypeORM<br>@Injectable()<br>export class AccountService {<br>  constructor(private readonly entityManager: EntityManager) {}<br><br>  async updateBalanceWithLock(accountId: number) {<br>    return await this.entityManager.transaction(async (transactionalEntityManager) =&gt; {<br>      const account = await transactionalEntityManager.findOne(Account, accountId, { lock: { mode: &#39;pessimistic_write&#39; } });<br>      // Modify account balance<br>      await transactionalEntityManager.save(account);<br>      return account;<br>    });<br>  }<br>}</pre><pre>-- Example of using pessimistic locking in a native SQL statement<br>BEGIN TRANSACTION;<br><br>-- Select and lock a specific row in a table using FOR UPDATE clause<br>SELECT * FROM accounts WHERE id = 12345 FOR UPDATE;<br><br>-- Perform operations on the locked row<br>UPDATE accounts SET balance = balance - 90 WHERE id = 12345;<br><br>COMMIT;</pre><h4>Optimistic Concurrency Control (Optimistic Locking)</h4><p>This method takes a different approach from pessimistic locking as it doesn’t preemptively lock records, but instead allows multiple transactions access the same data concurrently, and relies on detecting conflicts after multiple transactions or operations attempt to modify the same data simultaneously, during data validation or after a commit due to constraints.</p><p>This approach gives the advantage of concurrent data access that pessimistic locking lacks, it also reduces the chances of deadlocks, has low overhead and may scale more efficiently in a distributed system. Its disadvantages include increased rollback rate after conflicts are detected, waste of computation in long running transactions and conflict resolution overhead. It is a suitable solution for scenarios with low conflict chances and systems with mostly read operations, as concurrency is increased.</p><pre>// Example of using optimistic concurrency control with NestJS and TypeORM<br>@Injectable()<br>export class AccountService {<br>  constructor(<br>    @InjectRepository(Account)<br>    private readonly accountRepository: Repository&lt;Account&gt;,<br>  ) {}<br><br>  async transferFunds(fromAccountId: number, toAccountId: number, amount: number) {<br>    const fromAccount = await this.accountRepository.findOne(fromAccountId);<br>    const toAccount = await this.accountRepository.findOne(toAccountId);<br><br>    fromAccount.balance -= amount;<br>    toAccount.balance += amount;<br><br>    try {<br>      await this.accountRepository.save(fromAccount);<br>      await this.accountRepository.save(toAccount);<br>      return &#39;Transfer successful!&#39;;<br>    } catch (error) {<br>      // Handle concurrency conflict<br>      return &#39;Transfer failed due to concurrent update. Please retry.&#39;;<br>    }<br>  }<br>}</pre><pre>-- Example of using optimistic concurrency control in a native SQL statement for transferring funds between accounts<br>BEGIN TRANSACTION;<br><br>-- Read current balance of fromAccount<br>SELECT balance INTO @fromAccountBalance FROM accounts WHERE id = :fromAccountId;<br><br>-- Read current balance of toAccount<br>SELECT balance INTO @toAccountBalance FROM accounts WHERE id = :toAccountId;<br><br>-- Check if the balances have changed since reading<br>IF @fromAccountBalance = :originalFromAccountBalance AND @toAccountBalance = :originalToAccountBalance THEN<br>    -- Update balances<br>    UPDATE accounts SET balance = balance - :amount WHERE id = :fromAccountId;<br>    UPDATE accounts SET balance = balance + :amount WHERE id = :toAccountId;<br>    COMMIT;<br>    SELECT &#39;Transfer successful!&#39; AS result;<br>ELSE<br>    ROLLBACK;<br>    SELECT &#39;Transfer failed due to concurrent update. Please retry.&#39; AS result;<br>END IF;</pre><h4>Versioning and Time-stamping</h4><p>Versioning and time-stamping are both specific methods to implement optimistic concurrency control, and are really easy to implement and work with. In both approaches, each database record has a column to store a version number or a timestamp to show the last time the record was updated — typically an updatedAt column, these columns can then be used by transactions to ensure no other transaction has updated the records since they were fetched, and if so, deal with the conflict accordingly.</p><p>Both approaches have the same advantages as optimistic concurrency control, high concurrency, they are both easy to implement as versions are intuitive to work with and timestamps provide automatic ordering, they also make it really easy to detect conflicts. However, these approaches may lead to having to store an extra column, time-stamping relies on clock synchronisation between nodes in a distributed system and risks the possibility of undetected conflicts if multiple operations happen to modify the same record in a short time interval.</p><p>These approaches are a good fit for scenarios where most operations are read only, and scenarios with with low chances of conflicts, time-stamping specifically is great in a distributed system with accurate clock synchronisation between nodes and asynchronous workflows.</p><pre>// Example of using versioning in a NestJS service method with TypeORM<br>@Injectable()<br>export class ProductService {<br>  constructor(<br>    @InjectRepository(Product)<br>    private readonly productRepository: Repository&lt;Product&gt;,<br>  ) {}<br><br>  async updateProductQuantity(productId: number, newQuantity: number, currentVersion: number) {<br>    // Check if the product exists<br>    if (!(await this.productRepository.findOne(productId))) {<br>      throw new NotFoundException(&#39;Product not found.&#39;);<br>    }<br><br>    // Attempt to update the product using a raw SQL query because TypeORM has no way to update and return<br>    const query = `<br>      UPDATE products <br>      SET quantity = $1 <br>      WHERE id = $2 <br>      AND version = $3 <br>      RETURNING *<br>    `;<br>    const parameters = [newQuantity, productId, currentVersion];<br><br>    try {<br>      const updatedProduct = await this.productRepository.query(query, parameters);<br><br>      if (!updatedProduct || updatedProduct.length === 0) {<br>        throw new ConflictException(&#39;Version mismatch. Product has been updated by another transaction.&#39;);<br>      }<br><br>      // Return the updated product<br>      return updatedProduct[0];<br>    } catch (error) {<br>      // Handle errors<br>      throw new InternalServerErrorException(&#39;Failed to update product.&#39;);<br>    }<br>  }<br>}</pre><pre>-- Example of using versioning in a native SQL statement<br>UPDATE products<br>SET quantity = :newQuantity<br>WHERE id = :productId<br>  AND version = :currentVersion;</pre><h4>Event Sourcing</h4><p>Event sourcing is a design pattern for applications where the state of the application is determined by a sequence of immutable events. Rather than storing the current state of the application, the history of events that led to the current state is stored.</p><p>In event sourcing, race conditions are handled by appending events to the event log, instead of modifying a shared resource. The log also contains a history of all events, meaning it is easy to replay events incase of a failure.</p><p>Advantages of this approach include the audit trail provided by the event log which can be used to rebuild or replay events in case of a failure, graceful conflict resolution, and scalability as it can handle large volumes of concurrent writes in a distributed system. Introduced complexity is the major downside and it should not be used for basic CRUD operations, also it becomes harder to maintain consistency as the system grows. Event sourcing is great in scenarios where you need an audit trail, or lots of concurrent writes that need to be handled properly.</p><pre>// Event Entity<br>@Entity()<br>export class Event {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column()<br>  eventName: string;<br><br>  @Column(&#39;json&#39;)<br>  payload: Record&lt;string, any&gt;;<br><br>  @CreateDateColumn()<br>  createdAt: Date;<br>}<br><br>// Event Service using NestJS and TypeORM<br>@Injectable()<br>export class EventService {<br>  constructor(private readonly eventRepository: Repository&lt;Event&gt;) {}<br><br>  async recordEvent(eventName: string, payload: Record&lt;string, any&gt;): Promise&lt;void&gt; {<br>    const event = new Event();<br>    event.eventName = eventName;<br>    event.payload = payload;<br>    await this.eventRepository.save(event);<br>  }<br><br>  async getEventLog(): Promise&lt;Event[]&gt; {<br>    return this.eventRepository.find({ order: { createdAt: &#39;ASC&#39; } });<br>  }<br>}</pre><pre>-- SQL Table for Events<br>CREATE TABLE events (<br>  id SERIAL PRIMARY KEY,<br>  event_name VARCHAR(255) NOT NULL,<br>  payload JSON NOT NULL,<br>  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);<br><br>-- Inserting Events<br>INSERT INTO events (event_name, payload) VALUES (&#39;Event1&#39;, &#39;{&quot;key&quot;: &quot;value1&quot;}&#39;);<br>INSERT INTO events (event_name, payload) VALUES (&#39;Event2&#39;, &#39;{&quot;key&quot;: &quot;value2&quot;}&#39;);<br><br>-- Getting the Event Log<br>SELECT * FROM events ORDER BY created_at ASC;</pre><h4>Conclusion</h4><p>Race conditions are bound to happen in concurrent programming, how to handle it depends on your requirements and the nature of your application. To decide which is best for your scenario , examine the tradeoffs of each and decide which is most beneficial, you could adopt one or more of these approaches to solve your unique situations.</p><p>In the case of the initial example of a joint account, a pessimistic lock would be a good solution because an account balance doesn’t necessarily require concurrent access, and data integrity is extremely important.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f459d94ee2d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The SOLID Design Principles]]></title>
            <link>https://medium.com/@C0l0red/the-solid-design-principles-9014f5a3464a?source=rss-295cbb479273------2</link>
            <guid isPermaLink="false">https://medium.com/p/9014f5a3464a</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Paschal Uwakwe]]></dc:creator>
            <pubDate>Sun, 12 Mar 2023 17:45:54 GMT</pubDate>
            <atom:updated>2023-03-13T08:40:42.597Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3sxjQNjbirCQBlOEi9Cig@2x.jpeg" /></figure><p>Clean code is hard, stressful, and takes more brain power than it normally would, and oftentimes, we can’t see the payoff immediately, all we know is that we shouldn&#39;t repeat ourselves. The SOLID principles are guidelines that help you write better code. The payoff? Easier maintenance. That is the one true advantage of following these principles, when it is time to make an upgrade or any change, it is very easy.</p><p>The SOLID principles are quite popular, and usually pop-up during interviews, so I’ll be going a little in-depth, explaining the principles and showing scenarios where you could apply them to your code.</p><p>For this article, I’ll be using Kotlin, which I feel is a middle ground between Java, JavaScript, Dart, PHP, C#, Python and a bunch of languages that were influenced by Java or C, and also has an easy syntax to understand. For the few bits that may be confusing, I have code comments, and if any part isn’t clear, feel free to leave a comment.</p><h3>S — Single Responsibility Principle</h3><p>Classes are are the heart of Object Oriented Programming, and by definition, a class is a template for creating objects and implementation of their behavior. A function — or method if it is a member of a class — is a piece of code that can be run multiple times, saving the stress of rewriting.</p><p>Sometimes, the line where we decide we need a new function or a new class could get blurry, take this class for instance</p><pre><br>class User private constructor(val email: String, val password: String) {<br><br>companion object { // this is just how to create static methods and properties in Kotlin<br>  private val emailPattern = Regex(&quot;^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$&quot;)<br>  private val passwordPattern = Regex(&quot;^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@\$!%*?&amp;])[A-Za-z\\d@\$!%*?&amp;]{8,}\$&quot;)<br><br>  fun createDbUser(email: String, password: String) {<br>      // validate email and password<br>      email.matches(emailRegex) || throw Error(&quot;Email is invalid&quot;)<br>      password.matches(passwordRegex) || throw Error(&quot;Password is invalid&quot;)<br>      <br>      db.users.exists.(&quot;email&quot;, email).also { userExists: Boolean -&gt;<br>// &quot;also&quot; passes the result of a function call to an anonymous function, like &quot;then&quot; in JavaScript, but not limited to Promises<br>        if (userExists) throw Error(&quot;A user with that email already exists&quot;)<br>      }<br><br>      val hashedPassword = PasswordEncoder(password)<br>      val user = User(email, hashedPassword)<br><br>      // save user to database<br>      db.users.insert(user)<br>      db.commit()<br>    }<br>  }<br>}</pre><p>Looking at this, nothing seems off, just a User class that holds a user’s details, and a short method that persists a User in the database.</p><blockquote>Every class should have a single responsibility, a single purpose, and all its methods and properties should be in line with that purpose</blockquote><p>The User class above violates this principle, and it might not be obvious because everything about the class has to do with a User.</p><p>Firstly, this principle applies to methods or functions and modules, and the one method here might be a short one, but it is doing a lot of unrelated things, so much that the method’s functionality is not exactly obvious from the name. A method named createDbUser wouldn’t be expected to contain logic for validation, or password hashing.</p><p>A method’s name should tell any person reading or working on your code the exact thing the method does. So we could split that one method into four, like this</p><pre>fun createUser(email: String, password: String) {<br>  validate(email, password)<br>  val hashedPassword = hashPassword(password)<br>  val user = User(email, hashedPassword)<br>  saveToDb(user)<br>}<br><br>fun validate(email, password) {<br>  email.matches(emailRegex) || throw Error(&quot;Email is invalid&quot;)<br>  password.matches(passwordRegex) || throw Error(&quot;Password is invalid&quot;)<br><br>  db.users.exists.(&quot;email&quot;, email).also { userExists: Boolean -&gt; <br>// &quot;also&quot; passes the result of a function call to an anonymous function, like &quot;then&quot; in JavaScript, but not limited to Promises <br>    if (userExists) throw Error(&quot;A user with that email already exists&quot;)<br>  }<br>}<br><br>fun hashPassword(plainPassword: String): String {<br>  return PasswordEncoder(plainPassword)<br>}<br><br>fun saveToDb(user: User) {<br>  db.users.insert(user)<br>  db.commit()<br>}</pre><p>Now, the code is way longer, but more concise, and each function has a specific role which is very obvious from its name. So if we were to change our password hashing logic, no other method would be aware or need to change. However, there’s still a problem. All these methods are performing different types of operations on a User, and still violating the principle. An easy way to fix this would be to create a class for the different categories of operations to be done on a User. This is one way to go</p><pre>class SignupRequest(val email: String, val password: String) {// shorthand for a constructor and property declaration in Kotlin<br>  init { // this is a block that runs after the constructor is invoked in Kotlin<br>    email.matches(emailRegex) || throw Error(&quot;Email is invalid&quot;)<br>    password.matches(passwordRegex) || throw Error(&quot;Password is invalid&quot;)<br>  }<br><br>  companion object { // defining static properties<br>    private val emailPattern = Regex(&quot;^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$&quot;)<br>    private val passwordPattern = Regex(&quot;^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@\$!%*?&amp;])[A-Za-z\\d@\$!%*?&amp;]{8,}\$&quot;)<br>  }<br>}<br><br>class UserService { <br>  val userRepository: UserRepository = UserRepository()<br><br>  fun createUser(signupRequest: SignupRequest) {<br>    userRepository.existsByEmail(signupRequest.email).also { userExists: Boolean -&gt;<br>// &quot;also&quot; passes the result of a function call to an anonymous function, like &quot;then&quot; in JavaScript, but not limited to Promises   <br>      if (userExists) throw Error(&quot;A user with that email already exists&quot;)<br>    }<br>    val hashedPassword = hashPassword(password)<br>    val user = User(email, hashedPassword)<br>    userRepository.save(user)<br>  }<br><br>  fun hashPassword(plainPassword: String): String {<br>    return AdvancedPasswordEncoder(plainPassword)<br>  }<br>}<br><br>class UserRepository {<br>  fun existsByEmail(email: String): Boolean {<br>    return db.users.exists.(&quot;email&quot;, email)<br>  }<br><br>  fun save(user: User) {<br>    db.users.insert(user)<br>    db.commit()<br>  }<br>}<br><br>class User(val email: String, password: String) // shorthand for a constructor and property declaration in Kotlin</pre><p>Now we have four classes. A SignupRequest class to hold the input from a user, and validate the input, a UserService class to perform operations on a User, a UserRepository class that interacts with the database as relates to a User, and a User class that holds only the data of the usein the program. At this point, we have achieved true separation of concern, so much that we changed the class we were using to hash the password and the createUser method was not aware.</p><h3>O — Open-Closed Principle</h3><blockquote>Software entities — classes, methods, modules and so on — should be open for extension, but closed for modification</blockquote><p>This principle might sound a little weird at first, but the point it makes is that you should write code in such a way that you don’t need to make changes — or at least not too much — to the existing, tested code to add or change a feature. It’s closely related to the <em>Single Responsibility Principle</em>, so if you follow that, you’ll likely follow this principle often. The commonest example is hardcoding string or integer literals into a method that uses them, so if those values were to change, you would need to modify the existing code, which could lead to bugs. I’ll explain with this example that sends an iMessage or SMS depending on the user’s iPhone’s iOS version</p><pre>class IPhone {<br>  val model: String<br>  val iosVersion: Int<br>}<br><br>class User {<br>  val iPhone = IPhone()<br>  <br>  fun sendText() {<br>    if (iPhone.iosVersion &gt;= 5)<br>      sendIMessage()<br>    else <br>      sendSms()<br>  }<br>}</pre><p>This does the job, but what happens if we want our users to be able to own an Android or feature phone? That would mean more conditions to see if it’s a smartphone or if it supports rich text — Android’s version of iMessage🥱. That is a lot of modification going on in our existing code. To circumvent, we can do this</p><pre>interface Phone {<br>  val model: String<br><br>  fun sendText()<br>  fun sendIMessage()<br>  fun sendSms()<br>  fun sendRichText()<br>}<br><br>class IPhone: Phone {<br>  val iosVersion: Int <br>  <br>  override fun sendText() {<br>    if (iosVersion &gt;= 5)<br>      sendIMessage()<br>    else <br>      sendSms()<br>  }<br>}<br><br>class Samsung: Phone {<br>  val androidVersion: Int<br>  <br>  override fun sendText() {<br>    if (androidVersion &gt;= 12)<br>      sendRichText()<br>    else <br>      sendSms()<br>  }<br>}<br><br>class User {<br>  val iPhone: IPhone = IPhone()<br>  val samsung: Samsung = Samsung()<br>  <br>  fun sendText(phone: Phone) {<br>    phone.sendText()<br>  }<br>}</pre><p>Both IPhone and Samsung inherit from Phone which requires them to implement the sendText method. That way, to add a new phone type would be as easy as <strong><em>extending</em></strong> Phone, rather than <strong><em>modifying</em></strong> User, get it? Extend, not modify.</p><h3>L — Liskov Substitution Principle</h3><p>This principle is a guide to how inheritance should be used, and how to avoid abusing it. At the heart of it, inheritance is used to avoid repetition, and make code reusable, so a lot of times, it may seem logical to do something like this</p><pre>class LoginRequest {<br>  val email: String<br>  val password: String<br>}<br><br>class SignupRequest: LoginRequest {<br>  val firstName: String<br>  val lastName: String<br>  val phoneNumber: String<br>}<br><br>class User: SignupRequest {<br>  val followers: List&lt;User&gt; = mutableListOf() // creates an empty mutable list<br>}</pre><p>In reality, we’ve saved ourselves the stress of repeating a few properties, and this seems like a good thing. Here’s what the <em>Liskov Substitution Principle</em> says</p><blockquote>If one class inherits from another, then the subclass should be usable wherever the superclass is required</blockquote><p>Now, it’s obvious that the code above really violates this principle, because you cannot use a SignupRequest where a LoginRequest is needed. Most obvious reason being that SignupRequest requires more properties.</p><p>Another way to think of this principle is that, the subclass must be a <em>“type of”</em> the superclass, logically speaking. This helps when two classes are actually swappable, but you’re not sure which should be the super or base class. A good example would be User and CachedUser. They can logically be swapped with each other, so to decide which should be the superclass, we find out which is a type of which. <em>“User is a type of Cached User”</em> makes less sense than <em>“Cached User is a type of User”</em>. That way, we can logically tell that User should be the superclass.</p><h3>I — Interface Segregation Principle</h3><blockquote>Clients should not be forced to depend upon interfaces they do not use</blockquote><p>This is a pretty straightforward principle, and it discourages generic interfaces — not <em>generic typed</em> interfaces — and encourages interfaces with more specific contracts.</p><p>What does that even mean? It means when inheriting, we should not have classes inherit from classes or interfaces that contain details useless to them. Take our final solution for the <em>Open-Closed Principle</em> for instance. We know that Androids can’t send iMessages, yet Samsung inherits the method to do so, same with IPhone inheriting a sendRichText method it will never use. In cases like this, we would need to make sure no client calls these methods and end up doing this</p><pre>interface Phone {<br>  fun sendText()<br>  fun sendIMessage()<br>  fun sendSms()<br>  fun sendRichText()<br>}<br><br>class IPhone: Phone {<br>// implementation skipped<br>  override fun sendRichText() {<br>    throw NotImplementedError(&quot;iPhones can’t do this&quot;)<br>  }<br>}<br><br>class Samsung: Phone {<br>// implementation skipped<br>  override fun sendIMessage() {<br>    throw NotImplementedError(&quot;Samsungs can&#39;t send iMessages, silly&quot;)<br>  }<br>}</pre><p>This is bad practice, if it will never be used, it shouldn’t be there in the first place. Imagine adding a subclass for feature phones, BlackBerries or Windows phones that can send neither iMessages nor Rich Texts, two unimplemented methods! To solve this, we <strong><em>segregate</em></strong> the interfaces to make them more specific, like so</p><pre>interface Phone {<br>  val model: String<br><br>  fun sendText()<br>  fun sendSms()<br>}<br><br>interface ApplePhone: Phone {<br>  val iosVersion: Int<br><br>  fun sendIMessage()<br>}<br><br>interface AndroidPhone: Phone {<br>  val androidVersion: Int<br><br>  fun sendRichText()<br>}<br><br>class IPhone: ApplePhone {<br>// implementation skipped<br>}<br><br>class Samsung: AndroidPhone {<br>// implementation skipped<br>}</pre><p>With this approach, IPhone and Samsung can now implement more specific interfaces where all the methods are used, and a feature phone can implement Phone directly since it needs nothing more.</p><h3>D — Dependency Inversion Principle</h3><p>In OOP, oftentimes classes depend on one another for functionality. How this dependency comes in can be done in a couple of ways, a common way is this</p><pre>class IPhone{<br>  // implementation<br>}<br><br>class User {<br>  val iPhone: IPhone = IPhone()<br><br>  fun sendText() {<br>    // implementation<br>  }<br>}</pre><p>In this example, User depends on IPhone to send a text. And this works fine, but this makes User tightly coupled to IPhone, meaning if we wanted to update User to make a text using a Samsung, we would probably have to create a new property for the User to have another phone like we did in the example of the <em>Open-Closed Principle</em>.</p><p>One way we could solve this problem is to create an interface or superclass Phone, and pass the desired subclass name to the constructor, compare the string and instantiate accordingly, and following <em>Liskov Substitution Principle</em>, a subclass should be useable where a superclass is required, so an iPhone or Samsung can be used where a Phone is required.</p><pre>interface Phone{} // implementation skipped<br><br>class IPhone: Phone{}// implementation skipped<br><br>class Samsung: Phone{} // implementation skipped<br><br>class User {<br>  val phone: Phone<br><br>  constructor(phoneName: String) {<br>    when (phoneName) { // “when” is Kotlin’s version of &quot;switch&quot; in Java or JavaScript<br>      “IPHONE” -&gt; this.shape = IPhone()<br>      “SAMSUNG” -&gt; this.shape = Samsung()<br>      else throw Error(“Invalid phone name”)<br>    }<br>  }<br>  // the rest of the class<br>}</pre><p>Now User can use any subclass of Phone and instantiate accordingly, all without adding new properties, problem solved?</p><p>Not quite, we’re still violating the <em>Open-Closed Rule</em>, if we were to add a new subclass, we would need to <strong><em>modify</em></strong> our constructor, and besides that, if any of the Phone subclass’ constructors were to require arguments, that would require User having so much information that doesn’t concern it.</p><blockquote>High level modules shouldn’t depend on low level modules, but on abstractions</blockquote><p><em>Low level modules</em> are smaller classes that perform a specific function, like validation, and do not depend on other classes in your code, but work to help other classes — <em>High level modules</em>, like a service class — perform functions. So a high level module depends on smaller low level modules to perform functions for separation of concern. In the <em>Single Responsibility Principle</em> final example, UserService is high level, while UserRepository is low level.</p><p>This principle states that high level classes should not depend directly on the low level classes, but should depend on interfaces, which the low level classes then implement — or inherit or extend. Doing this would allow the high level classes accept any low level class that implements the interface, and not be tightly coupled to one class. How do we implement <em>dependency version</em>?</p><p>This is where <em>Dependency Injection</em> — related to, but not the same as <em>Dependency inversion</em> — comes in. It is the idea that a dependent class shouldn’t have to construct or instantiate its own dependencies, and should rather receive an object from its client — thus, the dependency gets ‘<em>injected</em>’, it is one easy way to implement <em>Dependency Inversion</em>. It goes like this</p><pre>// Phone, IPhone and Samsung definitions omitted<br>class User {<br>  val phone: Phone // dependency is the interface, not the concrete class<br><br>  constructor(phone: Phone) { // Liskov Substitution Principle<br>    this.phone = phone<br>  }<br>}<br><br>class UserClient {<br>  fun run() {<br>    val iPhone = IPhone() // dependency constructed by client<br>    val iPhoneUser = User(iPhone) // dependency injected by client<br>    <br>    val samsung = Samsung()<br>    val samsungUser = User(samsung) // a different dependency injected and it works fine<br>  }<br>}</pre><p>This way, User knows close to nothing about what Phone it’s dealing with, how it was constructed or what arguments it needs, the coupling between the two classes is now very loose, and any subclass of Phone can be swapped without ever needing to modify User.</p><p>This approach is known as constructor injection, but of course, it could also be done with a setter — setter injection.</p><h3>Conclusion</h3><p>From what we can see, the principles work hand in hand, and following one will make following the others easy, or sometimes mandatory, for consistency.</p><p>The SOLID principles won’t generally make your code shorter, not even easier to understand all the time, but they will definitely improve how easy it is to add or remove anything to existing code, and will make it easier to work in teams, since they all focus on <em>separation of concern</em> and <em>loose coupling</em>, so one team’s changes will not destroy another teams existing code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9014f5a3464a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>