<?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 Kevin Masur on Medium]]></title>
        <description><![CDATA[Stories by Kevin Masur on Medium]]></description>
        <link>https://medium.com/@kevinamasur?source=rss-bd967ca38ef8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qMOp1rRiWtuXQa_4FES4LQ.png</url>
            <title>Stories by Kevin Masur on Medium</title>
            <link>https://medium.com/@kevinamasur?source=rss-bd967ca38ef8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:22:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kevinamasur/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[When SQL Transactions Can Cause Trouble]]></title>
            <link>https://levelup.gitconnected.com/when-transactions-can-cause-trouble-a42a0d2cab91?source=rss-bd967ca38ef8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a42a0d2cab91</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Kevin Masur]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 02:02:12 GMT</pubDate>
            <atom:updated>2025-04-24T22:39:17.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-E2eqdhHruQH4QXsLwVHQ.jpeg" /><figcaption><a href="https://unsplash.com/photos/a-person-holding-a-credit-card-next-to-a-calculator-Ksgjx0tyuCY?utm_content=creditShareLink&amp;utm_medium=referral&amp;utm_source=unsplash">https://unsplash.com/photos/a-person-holding-a-credit-card-next-to-a-calculator-Ksgjx0tyuCY?utm_content=creditShareLink&amp;utm_medium=referral&amp;utm_source=unsplash</a></figcaption></figure><p>When working with SQL, you get used to the idea of doing writes inside of transactions. Frequently, your writes require writing data to multiple tables, and you only want the writes to be all or nothing, rather than only some of the data persisting if an exception or issue occurs mid-way through.</p><p>But transactions come at a cost (there’s never a truly free lunch is there), and one of those costs is locking. Specifically, to ensure the data inside of the transaction is not modified by anything else until the transaction is completed, the data being modified by the transaction needs to be locked for the duration of the transaction (The consequences of the A and the I in ACID).</p><p>Generally speaking in SQL, these locks come in 3 basic flavors, Row locks, Page locks, and Table locks. SQL databases will, generally speaking, try to grab the lowest level of locking it can based on your query. So it will favor only locking a single row, over a whole page of data, and favor locking a whole page of data over a whole table. Which one it chooses is based on how much data you&#39;re modifying, how big your page or tables are, and what flavor of SQL database you’re using.</p><p>Most of the time, you are likely just inserting, updating, or deleting single rows in multiple tables inside of a transaction. This will lock those rows until the transaction completes. That means, any other requests attempting to write or in some cases read those rows of data, will wait on the lock to release (the transaction to complete) before being able to access or modify the data.</p><p>However, if you start having transactions that span larger sections of a table, such as updating all records with a certain value, the database may decide that your transaction might be better served to grab a page or table-level lock rather than grabbing row locks for each row. This can cause other database transactions to get stuck waiting for the lock to be released before they can make their changes, even for unrelated data. If the locks are held long enough, or start piling onto each other faster than they can be cleared out, you could end up locking up your whole system.</p><p>So what can you do about it?</p><h3>Avoid long-running transactions</h3><p>Keep your transaction focused on what it needs to do to get the job done. Taking on extra processing that could be done before or after the transaction starts or completes just means you will be holding onto the locks longer than you need to. For example, external network calls, view or output logic, or even logging should be moved outside the transaction boundary in your code where possible.</p><h3>Keep your transaction boundaries focused on what needs to go together</h3><p>It can be easy sometimes to just start a transaction at the beginning of a unit of work and commit it at the end. But you might be better served to treat a unit of work as 2, 3, or more distinct transactions. It depends on whether your unit of work can be broken up into chunks like this, even if something were to cause it to fail part of the way through. But it can be important to consider.</p><p>Even if you want a single transaction, you should manage it yourself and avoid using configurations in your framework that auto manage the transaction boundary at the start and end of requests</p><h3>Work in batches or against rows rather than large clauses</h3><p>Your transaction will favor row locks when it can. So try to avoid having large transactions work against a whole table when possible. Updating or deleting large chunks of data by a where clause can be simple, but if the transaction is held for a long time it can lead to many requests getting stuck on the locks. Batch process the records instead, especially if there is other processing going on during the transaction that will cause it to be held for a long time.</p><h3>An Example of when it went wrong</h3><p>We recently had an issue where one of our audit log tables that is frequently written to started blocking many requests to it. This lead to slow response times and threads getting backed up on the server. It turns out, we had a batch process that wasn’t committing the transaction between batches. Eventually, it grabbed a table lock on the audit log table, and all requests ground to a halt.</p><p>We had the choice of having to wait until the batch process job was fully completed and committed its transaction, or to cancel the transaction. While cancelling the transaction sounds like an obvious choice, undoing the transaction takes time for the database to unwind all of the changes it was in the process of making. So we had to try and quickly determine which would be faster.</p><p>TLDR</p><ul><li>Keep your database transactions short and focused on only the changes that matter</li><li>Avoid or minimize any non-database related work while a transaction is open</li><li>When doing a large batch process, make sure to commit the transaction between batches and start a new transaction</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a42a0d2cab91" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/when-transactions-can-cause-trouble-a42a0d2cab91">When SQL Transactions Can Cause Trouble</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Null Pointer Everyone Missed]]></title>
            <link>https://levelup.gitconnected.com/the-null-pointer-everyone-missed-4ba780a8499e?source=rss-bd967ca38ef8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ba780a8499e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[null-safety]]></category>
            <category><![CDATA[autoboxing]]></category>
            <dc:creator><![CDATA[Kevin Masur]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 14:13:24 GMT</pubDate>
            <atom:updated>2025-03-19T14:13:24.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="https://unsplash.com/photos/brown-cardboard-box-_JBGjZFFYRk?utm_content=creditShareLink&amp;utm_medium=referral&amp;utm_source=unsplash" src="https://cdn-images-1.medium.com/max/1024/1*89RBDk4_Pst4tw2scDxFVg.jpeg" /><figcaption><a href="https://unsplash.com/photos/brown-cardboard-box-_JBGjZFFYRk?utm_content=creditShareLink&amp;utm_medium=referral&amp;utm_source=unsplash">https://unsplash.com/photos/brown-cardboard-box-_JBGjZFFYRk?utm_content=creditShareLink&amp;utm_medium=referral&amp;utm_source=unsplash</a></figcaption></figure><p>After writing Java for some years, you get used to seeing and debugging null pointer exceptions (<a href="https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/">the billion-dollar mistake</a>). Usually, it’s quite simple, you see a line like this:</p><pre>foo.action()</pre><p>And you know that foo is null, and you need to work you’re way back on why foo could be null. Sometimes it’s trickier when you chain method calls:</p><pre>foo.bar().bizz().action()</pre><p>And it can be tough to determine if foo is null, or the result of bar() or bizz() is null. But you either add some logging, pull it up in the debugger, or you backtrace against all three and eventually figure it out.</p><p>The point is, you look at the line, and can immediately recognize what could be causing a null pointer.</p><p>But last week we got a null pointer on a line like this, and it gave me some pause:</p><pre>if (USER_TYPE == personUserType)</pre><p>Huh?</p><p>We aren’t calling any methods on an object, how can we end up with a null pointer?</p><p>USER_TYPE is a static final constant int, so we know that it isn’t null. But let me expand the code out a bit.</p><pre>Integer personUserType = person.getUserType();<br>if (USER_TYPE == personUserType)</pre><p>Did you catch it?</p><p>personUserType is the object wrapper Integer, not the primitive int. But of course, USER_TYPE is a primitive integer. So to do the comparison, Java will automatically <a href="https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html"><em>unbox</em></a> the personUserType to a primitive int for you. But null isn’t a valid value for a primitive int, hence the null pointer exception.</p><p>Of course, the unit tests covered valid values and zero, but not <em>null</em> for the value of personUserType. So don’t forget to check for the null!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ba780a8499e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-null-pointer-everyone-missed-4ba780a8499e">The Null Pointer Everyone Missed</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to choose Maven or Gradle]]></title>
            <link>https://levelup.gitconnected.com/when-to-choose-maven-or-gradle-4a6cffcce3f2?source=rss-bd967ca38ef8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a6cffcce3f2</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javabuildtool]]></category>
            <dc:creator><![CDATA[Kevin Masur]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 01:06:26 GMT</pubDate>
            <atom:updated>2025-03-18T01:40:52.497Z</atom:updated>
            <content:encoded><![CDATA[<p>In the Java ecosystem, there’s really only two modern build tools most projects use, Gradle and Maven. I have found that after using both of them for various projects that both have their advantages and disadvantages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vn8n9dma5SPLlIhpfA3GQQ.jpeg" /></figure><h3>Maven</h3><p><a href="https://maven.apache.org/">Maven</a> is an open source Apache project that has been around for over 20 years and has been the go to build tool for most Java projects for most of that time. It’s popularity is in it’s simplicity. Instead of writing code to build other code, it uses convention over configuration. You define an XML POM file with your projects dependencies and package information and Maven does the rest. As long as you follow all of the patterns and rules it has about how your project is structured, everything will just work.</p><h4>Maven — The good:</h4><p>The standardization makes Maven a great choice for simple projects that don’t require a lot of customizations in their build process. It’s also great for beginners, as it’s very easy to learn and generally speaking just works. Commands are always the same, the order of the build steps are set in stone, and if you have used Maven in one project, using it in any future projects will work exactly the same way.</p><p>It’s also has really good backwards compatibility and is really easy to maintain long term. Maven POM files from 15 years ago still work fine on the latest version of Maven. Generally speaking, once you make your POM file, aside from updating dependencies and version numbers, your likely never going to touch it to actually upgrade / improve it again.</p><h4>Maven — The bad:</h4><p>If you require your build to have any sort of custom steps, file manipulations, or setup, then Maven starts to go off the rails. As the POM XML file only allows configuration, you can’t easily run any custom scripts or external tools with Maven. Instead, Maven allows custom scripts and extensions through plugins. However, if you can’t find a Maven plugin to do what you need, or if the plugin doesn’t allow for configuration options that you need, you can quickly get stuck.</p><p>You can run into this issue for even relatively simple build requirements like converting file types, or copying files from one location to another or running a shell script. Maven wants you to structure your whole project in a way to avoid these types of file manipulations, but if your project requires them for some reason, than Maven can become much more challenging.</p><h4>Maven — The Meh:</h4><p>Maven POM files can be very verbose. Though easy to read due to their XML format, some people can find them to be larger than they need to be (for example, compared to JSON formatting). The one advantage to the XML format is that it allows for IDE autocomplete and shows you what options are available for XML tags and attributes. Which makes figuring out what options are available when configuring your POM file much easier.</p><h3>Gradle</h3><p><a href="https://gradle.org/">Gradle</a> is a little newer to the game and is distributed as free software (though not open source). It has been gaining in popularity over time as it offers more features and improvements over Maven. Gradle uses a Groovy like syntax for configuring and scripting your build. Gradle also makes use of convention over configurtion like Maven around how your project is structured and how your build is executed. However, it allows for more customization than Maven and embedding scripts into your build.</p><h4>Gradle — The good:</h4><p>One of Gradles biggest features is the build cache and up-to-date checking. The Gradle build cache allows your build to cache the output of steps and skip building them if they haven’t changed. This can drastically reduce build times for large projects, especially while doing development work that often only makes small changes in a project that may not require rebuilding everything.</p><p>The ability to write custom scripts into your build allows for greatly expanding what your build process can do. Especially for legacy projects that may still be using custom scripts for some steps, migrating them to Gradle is much easier.</p><p>Gradle also allows for more complex and customizable dependency resolution. This is especially useful if your writing libraries and don’t want your libraries dependencies to be exposed to consumers of your library.</p><p>Gradle also has a paid enterprise server that can integrate with the build cache to share the build cache outputs across machines and help debug build issues. For large organizations that are frequently building large codebases, this can be a huge time saver. Though for smaller organizations or projects, it likely won’t make sense.</p><h4>Gradle — The bad:</h4><p>Gradle updates major versions every couple of years and will often deprecate and remove some functions, syntax, or options with every release. So trying to keep a long running project up to date with the latest version of gradle can be more difficult than you would expect. And even if the changes to your build script may be minor, if you rely on plugins to run parts of your build, you have to hope the plugin developers have been keeping the plugin up to date as well.</p><h4>Gradle — The Meh:</h4><p>The ability to add custom scripts and more configuration comes at a cost, and that cost is readability and simplicity. A gradle build file in two projects can look completely different and both would still work. While doing simple dependency and version updates can still be simple in gradle, any other build updates can be harder to read or maintain.</p><h3>So what would I choose?</h3><p>In most projects, I would still choose Maven for most use cases. It’s easy to understand, maintain, and is a proven standard that most Java developers know.</p><h4>However…</h4><p>I still think Gradle is the better choice in some circumstances:</p><ul><li>If you have a large legacy codebase that requires a number of customizations to keep working, then Gradle is a much better option.</li><li>If you have a large mono-repo or modular monolith that fully builds a large codebase, then Gradles build cache and other build performance optimizations can save you a lot of time waiting for builds to complete.</li><li>If working on an Android project where Gradle is the recommended build tool by Google, then stick with the default option.</li></ul><p>But for most codebases, especially those that don’t have a very long or complicated build process, Maven is an obvious choice that will keep you focused on writing code, rather than constantly fiddling with your build.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a6cffcce3f2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/when-to-choose-maven-or-gradle-4a6cffcce3f2">When to choose Maven or Gradle</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What a good culture around pull requests looks like]]></title>
            <link>https://levelup.gitconnected.com/what-a-good-culture-around-pull-requests-looks-like-cf426eab917c?source=rss-bd967ca38ef8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf426eab917c</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[pull-request]]></category>
            <dc:creator><![CDATA[Kevin Masur]]></dc:creator>
            <pubDate>Sun, 23 Jun 2024 16:50:53 GMT</pubDate>
            <atom:updated>2024-06-23T16:50:53.777Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dPhtEd-QLS3Jz5cCKEqOvg.png" /><figcaption>Photo by <a href="https://unsplash.com/@clemono?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Clem Onojeghuo</a> on <a href="https://unsplash.com/photos/a-close-up-of-a-red-door-with-a-metal-handle-gBnHMsAOWrs?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Some may argue that pull requests are an inefficient or bad practice, however I find they are still useful in many projects. However, to get all of those benefits you still need to have a good culture around how your teams treat pull requests. Here are the things I find lead to a good culture around pull requests.</p><h3>Quality is considered important</h3><p>For developers to take pull requests seriously, quality needs to be considered important within your organization. If getting it done fast is rewarded more than doing quality work, pull requests will seem like a blocker rather than a way to improve your codebase and your developers.</p><p>The other important point here is that while you can get away with speed over quality for a while, eventually you will start to slow down making future changes due to the high technical debt you have accrued.</p><h3>Be humble</h3><p>If you are having to read through the comments others have left on your code, be humble. They are not trying to insult or belittle you. Everyone makes mistakes, and everyone views things from their own lense of experience. Take their feedback and at least consider it as if you might be the one who’s wrong, rather than just immediately trying to defend why you are right. Sometimes you will be right, sometimes you won’t. Truly consider which is the case before acting on it.</p><h3>Be kind</h3><p>If you are leaving comments on someone else’s code, be kind. Try to be direct about the issue, but not mean or insulting. Don’t mock or mention anything about the developer personally. Keep it simple and professional.</p><h3>Everyone should feel empowered to review</h3><p>It doesn’t matter if the reviewer is an intern on their first day, or if the code was written by a developer with 30 years of experience. Everyone’s input can be valuable, and everyone&#39;s code could be improved.</p><p>If something is hard to understand, difficult to read, or seems repetitive, anyone can provide that feedback. They don’t need to know the context to give feedback on how readable your code is. Sometimes, having a lack of context can provide good insight into your code for how hard it is for someone new to read.</p><p>And if you have a strong culture around everyone reviewing pull requests, you should never be waiting long to get feedback or approvals.</p><h3>It’s a great learning experience</h3><p>Everyone can learn something by reviewing someone else’s code or having their code reviewed. Better practices or patterns, or useful tools and tricks. Reviews shouldn’t just be used to improve the code in the review, it should be a way for both the reviewers and developer to improve their skills.</p><p>And once you receive that feedback, you will start writing your future code keeping that feedback in mind going forward. So you will write better code from the start in the future, rather than waiting for the PR to get the same feedback over and over again.</p><h3>It is a great time to include quality control tools</h3><p>Linking builds to pull requests that run automation tests and preventing merging without a passing build is a great way to ensure the build is always passing on the trunk.</p><p>Code quality tools can also be integrated to prevent pull requests from merging if quality gates are not met. They can also be integrated into the PR to include feedback within the code diff. Tools like SonarQube allow for showing code smells and your code coverage in your diff. This makes spotting code smells and missed code coverage a breeze. Linters, security scanning, and any number of tools could be integrated into your pull requests to ensure issues are fixed at review time.</p><h3>Teams shouldn’t be silos</h3><p>Teams should review code from their own team, but they should also review code from other teams. Reviewers can often focus on certain issues and ignore others. By having reviewers from outside your team, you can get a wider range of knowledge and feedback. Otherwise, your code quality will live in an echo chamber.</p><h3>Fix the small stuff</h3><p>Yes, it can be a little annoying when you get comments on formatting, naming, or other nitpicky issues. But unless it’s purely a matter of preference, I would encourage you to fix it. Those small comments are often so quick and easy to fix that it’s faster to fix them than argue about them. And if they do make the code a little cleaner, you’d be surprised how quickly the little things can start to pile up in a codebase.</p><h3>Review it before you open it</h3><p>Don’t waste people&#39;s time on the stuff you could have caught yourself. Before you click the open pull request button, review your code the same way you would someone else’s. I often find little issues or things I forgot to clean up when I give my work one last final review. Don’t end up looking like a chump. Only put up code for review that’s ready.</p><h3>Tests should get reviewed as well as production code</h3><p>While I will admit to not putting the same due diligence into automated test code that I do into production code, tests should still be reviewed.</p><p>They should be clean and easy to read, the same as the rest of the code. They should cover all of the expected cases, and setup and validate those cases properly. And they should avoid doing things that would make the test brittle.</p><h3>Keep your changes within scope</h3><p>Comments in a pull request are fine. But sometimes those comments might be outside of the scope of your changes. When that happens, do your best to open a separate pull request right away to address just the comment.</p><p>Conversely, don’t delay making changes that are within the scope of your pull request. Saying you’ll fix it in the next one can lead to things getting missed, and changes being harder to review later when unnecessary changes seem to be happening in other PRs.</p><h3>Avoid Privileged Reviewers</h3><p>It can be tempting to only allow certain experts to review code, but if this is done for the whole codebase it can lead to an anti-pattern. Only allowing a small privileged reviewer group leads to a slow turnaround time on reviews. It can also hurt the trust between the developers and the reviewers.</p><p>If you have a small number of specific, specialized areas of your codebase that only have a few people who can provide valid feedback, then you might be able to get away with this for just those areas. But avoid wide-ranging rules like review councils or only senior developers can review code mandates. It’s slow, stunts developer growth, and puts the burden of quality onto a small number of people, rather than on everyone.</p><h3>Keep your changes small and with a single focus</h3><p>Large PRs are hard and slow to review. And that leads to your changes getting reviewed slowly, or getting an overwhelming amount of feedback. Keep it small and focused and you will have feedback and approvals in no time.</p><p>Occasionally things require larger changes. When that’s the case, I often make a feature branch and make smaller PRs into that branch for review. That way, all of the parts were reviewed individually, and then at the end, the whole of the changes can be reviewed together. Just keep your feature branch up to date with the trunk as often as you can, and try to get it merged as quickly as possible. Avoid long-running feature branches.</p><h3>Know when it’s not good enough</h3><p>When reviewing be clear on how important certain changes are. Don’t be afraid to block changes that aren’t meeting the quality standards. But make sure the developer knows what’s expected of them to get your approval. Also, while it’s fine to notice something else later, don’t constantly move the goalposts on someone. It can be frustrating to have to deal with 4 or 5 iterations of your comments that could have been provided from the start.</p><h3>Document your best practices somewhere</h3><p>This can be a useful doc for new developers to review so they don’t feel blindsided when they open their first pull request. It’s also good for documenting why doing things a certain way can be important.</p><p>This should be a living document, that anyone can update and improve over time. I have found that some things I considered a best practice a few years ago have now been replaced by an even better way of doing things. When things change, update and link the doc.</p><h3>Conclusion</h3><p>Above are the practices I have found are the best way to get the most out of pull requests in your organization. Are there any you felt that I have missed? Or perhaps anything on the list you disagree with? Or any you wish you saw more of in your organization?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf426eab917c" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/what-a-good-culture-around-pull-requests-looks-like-cf426eab917c">What a good culture around pull requests looks like</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to handle composite keys]]></title>
            <link>https://medium.com/@kevinamasur/how-to-handle-composite-keys-3310be374aca?source=rss-bd967ca38ef8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3310be374aca</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Kevin Masur]]></dc:creator>
            <pubDate>Sun, 31 Dec 2023 19:02:56 GMT</pubDate>
            <atom:updated>2023-12-31T19:02:56.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4SOcWjOVSu-8BKmrMkt2eg.jpeg" /><figcaption>Photo by Aphiwat chuangchoem: <a href="https://www.pexels.com/photo/light-bulb-and-keys-on-table-347226/">https://www.pexels.com/photo/light-bulb-and-keys-on-table-347226/</a></figcaption></figure><p>Composite keys are when a combination of data is required to define the “key” for your map or cache lookup. An example of this might be where you need to cache values based on a customer name as well as a users role. In a case like this, your cache would need to be able to store unique values based on on each of these two (or more) criteria.</p><p>There’s a few different ways composite keys can be handled in code.</p><p><strong>Combine the criteria into a string</strong></p><p>The first answer most jump to is combining the criteria into a string to use as the key. It’s simple and doesn’t take a lot of effort:</p><pre>private String getMapKey(Long userId, String userLocale) {<br>  return userId + &quot;.&quot; userLocale;<br>}</pre><p>This is a pretty basic way to handle the problem. Using a string key can make debugging and investigations easier, as the cache key is in a human readable format. But, there’s a few problems to be aware of with this approach:</p><ol><li>It requires a new string be created on every interaction with the map. Though this string allocation is generally small, if the map is accessed frequently, it can lead to a large number of allocations that take time and need to be garbage collected. The size of the string allocation can also be larger depending on how large the components of your key are or how many you have.</li><li>You need to ensure that the composite key you create can’t get spoofed into another key value:</li></ol><pre>public String getMapKey(Integer groupId, Integer accessType) {<br>  return groupId.toString() + accessType.toString();<br>} </pre><p>In the above, if you had groupId = 1 and accessType = 23, that would be the same cache key as groupId = 12 and accessType = 3. By adding a separator character between the strings, you can prevent this kind of overlap. But be careful about optional parts of a key:</p><pre>public String getMapKey(String userProvidedString, String extensionName) {<br>  return userProvidedString + (extensionName == null ? &quot;&quot; : (&quot;.&quot; + extensionName));<br>}</pre><p>In the above example, extensionName is an optional part of the key. If the extensionName is optional, userProvidedString could include a separator and valid extensionName and get access to cache data it shouldn’t have had access too.</p><p>When using strings, you’ll want to think about how you are combining your data to avoid any collisions in the keys. Especially around any user generated input for the key.</p><p><strong>Use nested maps/caches</strong></p><p>Another option is to not combine the keys at all, and instead, nest your data structures (Maps of Maps of Maps):</p><pre>Map&lt;Integer, Map&lt;String, String&gt;&gt; groupAndLocaleMap = new HashMap&lt;&gt;();<br><br>groupAndLocaleMap.computeIfAbsent(userId, k -&gt; new HashMap()).put(userLocale, mapValue);</pre><p>This has the advantage of not needing to allocate any new memory when interacting with the maps. As the passed in values for the keys are already allocated. And while you will need to do multiple lookups to get to the final value, the maps will be smaller.</p><p>But the downsides to this approach is it gets more complicated the deeper down the nesting goes. Even with only two levels, the map initialization can look confusing. When you start dealing with 3 or more pieces of data, this can lead to making your code very verbose. On top of that, each level requires null checking to avoid null pointers.</p><p>Some “key parts” also might not work well as a map key. Arrays or collections don’t have default equals methods that compare their contents. So you would either need to implement them, or use another alternative.</p><p>Using nested maps could also become less space efficient depending on how unique each level of your keys are.</p><p><strong>Create a composite key object</strong></p><p>The last option is instead of combining the key values into a string, make a custom object for the key instead:</p><pre>    private class MapKey {<br>        private final int userId;<br>        private final String userLocale;<br><br>        public MapKey(int userId, String userLocale) {<br>            this.userId = userId;<br>            this.userLocale = userLocale;<br>        }<br><br>        @Override<br>        public boolean equals(Object o) {<br>            if (this == o) return true;<br>            if (o == null || getClass() != o.getClass()) return false;<br>            MapKey mapKey = (MapKey) o;<br>            return userId == mapKey.userId &amp;&amp; Objects.equals(userLocale, mapKey.userLocale);<br>        }<br><br>        @Override<br>        public int hashCode() {<br>            return Objects.hash(userId, userLocale);<br>        }<br>    }</pre><p>While every interaction still requires a new memory allocation for a new object. The object key allocation is significantly smaller than the one needed for a composite string. The reason for this is because the parts that make up the key don’t need to get reallocated as strings. Instead, only the wrapping object key requires new memory.</p><p>A composite key object can also allow for customizations in the key equality and hashcode implementations. Such as ignoring capitalization in a string, or using an array or collection as part of a key.</p><p>The downsides here though are that again, it requires a lot more code than a composite string does. And it requires ensuring you have a valid equals and hashcode contracts in the key class for your map.</p><p><strong>So which should I choose?</strong></p><p>Generally speaking, I would suggest using a composite string key. It’s simple and easy to understand, requires the least code, and is easiest to debug later. While it is likely the slowest performing, writing simple, readable code is generally more important than the benefits you would get using one of the other two options. Remember:</p><blockquote>“Premature optimization is the root of all evil” Donald Knuth</blockquote><p>If you don’t have evidence or a reason to believe that your map/cache lookup is going to be a performance bottleneck, go with readability.</p><p>But if you ARE in a scenario where the throughput to your map or cache is very high, than it might be good to switch to one of the other two options. Let’s see how all 3 compare to each other performance wise, as well as with their memory allocation size.</p><p>To test the 3 scenarios above, I wrote code that would replicate the same implementation of all 3 scenarios for a composite key. The key itself consists of an integer value, a string value, and a long value. All three implementations used the same test data on each run to build the keys. All runs were executed with 1 million records in the map (java’s hashmap was used). 3 runs were done building the key with different combinations of key sizes:</p><ul><li>100 ints, 100 strings, 100 longs — 1 million unique keys</li><li>1 int, 1 string, 1,000,000 longs— 1 million unique keys</li><li>1,000,000 ints, 1 string, 1 long — 1 million unique keys</li></ul><p>First, let’s look how much space each map takes up in the heap. This is important, because it affects how much memory is needed to run your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_g47Ck-9A52T95ca2OsYCQ.png" /><figcaption>Retained size of the map(s) in MB (captured by heap dump after map creation)</figcaption></figure><p>There’s one interesting obvious note to make here, in the last scenario (1,000,000 ints) the nested maps size is significantly larger than the others. This is because in this scenario, the nested maps create 1 first level map with 1 million entries, then for the second and third levels, it creates 1 million maps with only one entry. All those nested maps store extra overhead and are mostly empty. This is obviously an edge case, but I wanted to show it to make a point. When using the nest maps implementation, the uniqueness (and the ordering of that uniqueness) matters a lot. If you reverse the order to 1, 1, 1 million, you actually get the lowest storage requirement.</p><p>In the other two scenarios, the nested mapping is the most efficient, with the custom key object coming in second, and the string keys coming in last.</p><p>Next, let’s look at the time it takes to create each of these maps from scratch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*py6CEUMMFPmQ8wlJm_iUuQ.png" /><figcaption>Metrics grabbed using intellij profiler and looking at CPU timings of the map(s) creation method</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iO7ffCHxyd7_Yjf5GLQPNQ.png" /><figcaption>Metrics grabbed using intellij profiler and looking at memory allocations of the map(s) creation method</figcaption></figure><p>Again, we see the nested maps performing the worst in the 1 million-1–1 scenario for memory allocation, but even then it out performs the others in CPU time. In the above we can also see how the String key performs the worst in all cases. While using a custom key object being slightly slower and requiring more memory allocation than the nested keys.</p><p>Lastly, let’s look at the highest throughput scenario, how effective is it to read. We ran 1 million read operations (1 for each key created), we did not include any nonexistent keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GhsJY50w9DRKnEZx0SZUaQ.png" /><figcaption>Metrics grabbed using intellij profiler and looking at CPU timings of the map(s) lookup method (1 million reads)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x1032HLR5PGt5Smouo-aNw.png" /><figcaption>Metrics grabbed using intellij profiler and looking at memory allocations of the map(s) lookup method (1 million reads)</figcaption></figure><p>This is where we really see how slow the string based key lookup is. It is by far the slowest, and allocates the most memory of any of the 3 options by far. The custom key object performs “close” to the nested maps implementation, but is still consistently slower by a small margin.</p><p>However, in lookup memory allocations, notice how well the nested maps shines. No that’s not a glitch in the graph, looking up a value in the nested maps requires no extra memory allocations to do the lookup. How is that possible?</p><p>Well, when combining the composite objects into a string key, you need to allocate memory for a new string object every time:</p><pre>private String lookup(int key1, String key2, long key3) {<br>  return map.get(key1 + &quot;.&quot; + key2 + &quot;.&quot; + key3);<br>}</pre><p>When using a composite key, you still need to allocate memory for a new key object. But because the members of that object are already created and referenced, it still allocates much less than a new string:</p><pre>private String lookup(int key1, String key2, long key3) {<br>  return map.get(new MapKey(key1, key2, key3));<br>}</pre><p>But the nested maps implementation requires no new memory allocation on lookup. You are reusing the given parts as keys to each of the nested maps:</p><pre>private String lookup(int key1, String key2, long key3) {<br>  return map.get(key1).get(key2).get(key3);<br>}</pre><p>So based on the above, which is the most performant?</p><p>It’s easy to see that the nested maps comes out on top in almost all scenarios. If your looking for raw performance in most use cases, it’s likely the best option. Though you should perform your own testing to confirm for your use cases.</p><p>The key object makes for a very good general purpose option when nested maps become impractical or impossible to use for your implementation. And the composite string key, though easiest to implement, is almost always going to be the slowest.</p><p>The last point to consider when looking to implement composite keys is that you can combine the above. For example, you could use nested maps for the first level or two, and then use a composite key object for simplifying the deeper levels. This could still keep your data partitioned for fast lookups while still optimizing storage and lookup performance. And keep your code readable as well.</p><h4>TLDR;</h4><p>Most of the time, just keep it simple. Combine your composite keys into a string key for storage in a map or cache if that is the easiest option and performance is not a major concern.</p><p>In the scenarios where performance is critical, make sure to do your own testing. But using nested maps will be the most performant in most cases. It will also likely have the smallest storage requirements. And composite keys are still a performant alternative when nesting mappings becomes impractical.</p><pre>Want to connect?<br>Linked-In: https://www.linkedin.com/in/kevin-masur-b537b8192</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3310be374aca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>