[{"content":"One of the challenges I\u0026rsquo;m facing as a tech lead while building and maintaining any service with AI is keeping living documentation up to date. It is mostly for humans, because more often than not, AI relies on code and points out the drift.\nAnother challenge is the amount and kind of document artifacts. Generating lots of prose based on code is a maintenance hell and downright dangerous, as outdated docs will mislead.\nIdeally, we should try to have the following:\nBehaviour specs, e.g. a requirement from the transaction-posting spec:\n### Requirement: Posting balances per currency A posting SHALL contain at least two entries and at most 100. For each currency in the posting, the sum of `DEBIT` amounts SHALL equal the sum of `CREDIT` amounts. #### Scenario: Unbalanced posting rejected - **WHEN** a posting debits 5730 EUR and credits 5719 EUR - **THEN** the response is `422` with code `UNBALANCED` naming the currency and both sums - **AND** nothing is recorded #### Scenario: Multi-currency posting balanced per currency - **WHEN** a posting debits and credits 11000 USD and separately debits and credits 10000 EUR - **THEN** it is recorded C4 context/container/component diagrams, e.g. the containers of the ledger:\nSequence diagram, flowchart, ER etc., e.g. the posting write path:\nOpenAPI definition, Avro Schemas and others are by nature contracts and document artifacts and should not be retold in markdown file.\nI started with an initial AI prompt to build the skeleton of a composite Gradle project for a double-entry ledger. Once the core stack and layout were established, it was time to initialise OpenSpec:\n! openspec init --tools claude Then came some tweaking around the OpenSpec config and the AI agent:\nOpenSpec config.yaml: says where living docs go and what\u0026rsquo;s in them (current state only, Mermaid, minimal, link to contracts instead of repeating them). Proposals must have a \u0026ldquo;Docs impact\u0026rdquo; section, designs must have diagrams, the last task updates the docs, and archive checks that the docs match the code. Claude hook: a PreToolUse hook blocks archiving if the docs listed in \u0026ldquo;Docs impact\u0026rdquo; weren\u0026rsquo;t updated or aren\u0026rsquo;t linked from docs/README.md. Without the hook, these rules are somewhat of a recommendation for AI, not a must.\nSetup done, next was the first API, together with its implementation:\n/opsx:explore API for posting a transaction As the command says, I explored multiple shapes of the API to finally settle on one, then went into more in-depth implementation details, like the table structure in the database, code flow, etc. Each decision was carefully weighed against pros and cons and the future evolution of the system.\nOnce I was happy with the shape of what was explored, I formally proposed this change. The exploration part is totally optional.\n/opsx:propose add-transaction-posting The AI agent produced a few Markdown files with the specs/requirements for the new feature and tasks. I reviewed them and made some corrections; as always, AI with too much or too little context adds something extra.\n/opsx:update add-transaction-posting remove balance after I repeated the cycle, and once I was happy with the outcome, I finally implemented it.\n/opsx:apply add-transaction-posting At any point, I could already open the PR and send it for review, be it when just the OpenSpec change was created or when the feature was fully implemented and its specs archived.\n/opsx:archive add-transaction-posting That done, the living documentation was also generated, as initially configured, and it needed a review as well.\nConclusion about Spec-Driven Development with AI What I liked It gives structure to the exploration of a feature and to refining it incrementally. Before, I was always creating some kind of document, but it was haphazard in structure and content. In between OpenSpec commands, I was free to chat about the design, clarify some aspects, and harden the solution. I generated some minimal yet useful docs for the project that are easy to maintain automatically with the current setup. It writes scenarios beforehand, and I can validate from a business perspective whether the system will behave as expected. It documents the alternative solutions I considered - which is great for cutting short countless future discussions around \u0026ldquo;why this way?\u0026rdquo;, \u0026ldquo;did you consider …?\u0026rdquo;, etc. The plan/scenarios/specs for a feature can be reviewed before any code is written. I felt less prone to cognitive surrender. What I liked less OpenSpec does not enforce the rules/guides I set; I had to use Claude hooks for that, and iterative review and tweaking to get the desired result. Some changes didn\u0026rsquo;t go through the OpenSpec flow, and thus the specs, living documentation and code drifted again - but it is the duty of the dev to set the guardrails so they don\u0026rsquo;t. Links Full repo can be found here OpenSpec config Living documentation Behaviour specification ","permalink":"https://adrian.md/2026/11/22/sdd-ai/","summary":"\u003cp\u003eOne of the challenges I\u0026rsquo;m facing as a tech lead while building and maintaining any service with AI is keeping living documentation up to date. It is mostly for humans, because more often than not, AI relies on code and points out the drift.\u003c/p\u003e\n\u003cp\u003eAnother challenge is the amount and kind of document artifacts. Generating lots of prose based on code is a maintenance hell and downright dangerous, as outdated docs will mislead.\u003c/p\u003e","title":"Building a Ledger with Spec-Driven Development and Maintaining Living Documentation"},{"content":"I was recently facing a problem with first requests into a double entry financial ledger service taking more than double of subsequent requests. This got me digging into Java\u0026rsquo;s Ahead-Of-Time Cache (AOT) and Spring.\nI was under the wrong impression that AOT is only about startup speedup, but looking a bit through recent AOT JEP additions found out each one will bring something to the first request.\nJEP 483: Ahead-of-Time Class Loading \u0026amp; Linking (JDK 24) JEP 515: Ahead-of-Time Method Profiling (JDK 25) JEP 516: Ahead-of-Time Object Caching with Any GC (JDK 26) So here\u0026rsquo;s the setup:\nJava 26 - because of AOT with any GC. Spring Pet Clinic REST repo, to test a usual Java REST stack. Latest Spring Boot version at the moment. k6 - to \u0026rsquo;train\u0026rsquo; the JVM and show performance under different configuration. And here the scenarios:\nbaseline-g1 - no AOT cache, default G1 garbage collector. aot-g1 - testing with AOT cache and G1. baseline-zgc - no AOT, using ZGC - concurrent garbage collection as opposed to G1 stop-the-world type, which can cause some spikes in latency (or at least I was thinking so). aot-zgc - cache + ZGC. For each scenario I ran the service with -XX:AOTCacheOutput creating the cache, then with -XX:AOTCache multiple executions to get more accurate statistics.\nThe results are not impressive but a real consistent improvement can be seen:\nG1 Garbage Collector Median Latency: AOT is ~27% better (342.53 ms vs 467.52 ms). Minimum Recorded: AOT achieved 299.04 ms, while baseline achieved 388.87 ms. Maximum Recorded: AOT hit 378.20 ms, while baseline hit 723.58 ms. ZGC Garbage Collector Median Latency: AOT is ~22% better (392.19 ms vs 501.80 ms). Minimum Recorded: AOT achieved 320.35 ms, while Baseline achieved 424.74 ms. Maximum Recorded: AOT hit 524.59 ms, while Baseline hit 579.85 ms. It wasn\u0026rsquo;t a smooth test at the beginning. My runs with AOT cache were silently failing to load cache, as a result I was getting the same latency as baseline. After some digging I found out that my problem Error occurred during initialization of VM when using AOTCache was caused by a custom Java image I was using in Docker. There is already a bug on this - JDK-8381222. After switching from eclipse-temurin:26-jre-jammy to eclipse-temurin:26-jdk-jammy, the cache finally started to work.\nEven with the seen improvement I wasn\u0026rsquo;t happy since there is a 97% worse latency between first request and subsequent ones: 433.58 ms first request vs 10.40 ms subsequent requests.\nI had to check what is happening with Spring during this first request. Starting the JVM with the Flight Recorder (-XX:StartFlightRecording) and then analyzing the dump in JDK Mission Control gave me some pretty decent insight.\nBased on the above and a bit of clicking around, I found out that Spring Boot shipped as a fat jar (so it can be run as java -jar), provides a custom class loader, since the JVM cannot natively load the classes from nested jars.\nThis class loader through loadClass invocation just delegates to JDK that doesn\u0026rsquo;t know about nested jars structure and at some point throws class not found (2). The exception handler then calls findClass (3) that actually can find the class.\nThis happens for every class that needs to be loaded from nested jars for the first time. Some of the classes are loaded at startup, but some of them like Jackson for DTO, Hibernate for the database query etc. are done at first HTTP request.\nFor the next tests I built another dockerfile that bypasses the fat jar and instead launches the app through the real main class. It\u0026rsquo;s a documented solution (see example 3), not some hacky workaround.\nAnd the results were astounding, 85.37 ms latency, as opposed to around 467.52 ms measured from baseline. That\u0026rsquo;s ~82% latency drop.\nWorth noting that aside from first request, all subsequent requests maintained a steady 8 - 9 ms latency no matter the config.\nAll the scripts to run the tests as well as full results used for this article can be found here.\n","permalink":"https://adrian.md/2026/09/03/first-request-latency/","summary":"\u003cp\u003eI was recently facing a problem with first requests into a double entry financial ledger service taking more than double of subsequent requests. This got me digging into Java\u0026rsquo;s Ahead-Of-Time Cache (AOT) and Spring.\u003c/p\u003e\n\u003cp\u003eI was under the wrong impression that AOT is only about startup speedup, but looking a bit through recent AOT JEP additions found out each one will bring something to the first request.\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eJEP 483: Ahead-of-Time Class Loading \u0026amp; Linking (JDK 24)\u003c/li\u003e\n\u003cli\u003eJEP 515: Ahead-of-Time Method Profiling (JDK 25)\u003c/li\u003e\n\u003cli\u003eJEP 516: Ahead-of-Time Object Caching with Any GC (JDK 26)\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003eSo here\u0026rsquo;s the setup:\u003c/p\u003e","title":"Improving First Request Latency in Java Spring Application"},{"content":"Are you tired of Copilot comments on your PR? Then let AI deal with it. In the following article, find a useful command for Claude Code.\nPrerequisites Claude Code gh cli brew install gh gh auth login Create Claude Code command Create file ~/.claude/commands/resolve-pr-comments.md with content:\nFetch all open/unresolved review comments on a PR and help me resolve them. ## Step 1: Determine the PR If a PR number is provided as $ARGUMENTS, use that. Otherwise, run this command first and capture the output: ``bash gh pr view --json number -q .number `` Store the result as the PR number. If the command fails or returns empty, tell me there\u0026#39;s no open PR on this branch and stop. ## Step 2: Get Repo Info Run this command and store the owner and repo name: ``bash gh repo view --json owner,name -q \u0026#39;.owner.login + \u0026#34;/\u0026#34; + .name\u0026#39; `` This gives you OWNER/REPO. Use these values in all subsequent commands. ## Step 3: Fetch Unresolved Comments Use the PR number and OWNER/REPO from previous steps. Replace OWNER, REPO, and PR_NUMBER with the actual values — do NOT use $() substitution. First, get unresolved review threads via GraphQL: `` gh api graphql -f query=\u0026#39;query { repository(owner:\u0026#34;OWNER\u0026#34;, name:\u0026#34;REPO\u0026#34;) { pullRequest(number:PR_NUMBER) { reviewThreads(first:100) { nodes { isResolved, comments(first:10) { nodes { id, body, author { login }, path, line } } } } } } }\u0026#39; `` Only include threads where `isResolved` is `false`. Skip any already-resolved threads entirely. **Important**: Filter out noise before analysis. Ignore any comments from bots like SonarQube/SonarCloud (user login containing \u0026#34;sonar\u0026#34;) that indicate passing quality gates, no issues found, or \u0026#34;Passed\u0026#34; status. Only keep Sonar comments that flag actual issues, bugs, or code smells. Also ignore other CI bot comments that are purely status updates (e.g. coverage reports that just show numbers with no actionable feedback). ## Step 4: Critical Analysis For each comment, provide a structured analysis: - **Comment**: The reviewer\u0026#39;s feedback - **File \u0026amp; Line**: Where it applies - **Assessment**: Do you agree this is a valid concern? Be honest — if the comment is nitpicky, subjective, or wrong, say so with reasoning. - **Recommendation**: One of: - **AGREE \u0026amp; FIX** — Valid point, here\u0026#39;s the proposed change - **DISCUSS** — Has merit but needs discussion, here\u0026#39;s a suggested reply - **PUSH BACK** — Disagree, here\u0026#39;s why and a suggested reply - **Proposed Change** (if fixing): Show the exact code diff ## Step 5: Present the Plan Present ALL comments with your analysis in a single summary table, then wait for my approval before making any changes. ## Step 6: Execute (only after approval) Once I confirm which comments to resolve: 1. Make the code changes for approved fixes 2. For DISCUSS/PUSH BACK items, draft reply comments 3. Stage and show me the final diff before committing Permissions This is optional, without it you\u0026rsquo;ll need to approve multiple commands.\nAdd to ~/.claude/settings.json the following:\n{ \u0026#34;permissions\u0026#34;: { \u0026#34;allow\u0026#34;: [ \u0026#34;Bash(gh pr:*)\u0026#34;, \u0026#34;Bash(gh api:*)\u0026#34;, \u0026#34;Bash(gh repo:*)\u0026#34; ] } } Note, maybe it\u0026rsquo;s worth fine tunning the permissions, instead of using the wildcard.\nUsage claude /resolve-pr-comments ","permalink":"https://adrian.md/2026/03/25/claude-resolve-pr-comments/","summary":"\u003cp\u003eAre you tired of Copilot comments on your PR? Then let AI deal with it. In the following article, find a useful command for Claude Code.\u003c/p\u003e\n\u003ch3 id=\"prerequisites\"\u003ePrerequisites\u003c/h3\u003e\n\u003cul\u003e\n\u003cli\u003eClaude Code\u003c/li\u003e\n\u003cli\u003egh cli\n\u003cul\u003e\n\u003cli\u003e\u003ccode\u003ebrew install gh\u003c/code\u003e\u003c/li\u003e\n\u003cli\u003e\u003ccode\u003egh auth login\u003c/code\u003e\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch3 id=\"create-claude-code-command\"\u003eCreate Claude Code command\u003c/h3\u003e\n\u003cp\u003eCreate file \u003ccode\u003e~/.claude/commands/resolve-pr-comments.md\u003c/code\u003e with content:\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-markdown\" data-lang=\"markdown\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eFetch all open/unresolved review comments on a PR and help me resolve them.\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"gu\"\u003e## Step 1: Determine the PR\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eIf a PR number is provided as $ARGUMENTS, use that.\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eOtherwise, run this command first and capture the output:\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e`\u003cspan class=\"sb\"\u003e`bash\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003egh pr view --json number -q .number\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e``\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003eStore the result as the PR number. If the command fails or returns empty, tell me there\u0026#39;s no open PR on this branch and stop.\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e## Step 2: Get Repo Info\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003eRun this command and store the owner and repo name:\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e``bash\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003egh repo view --json owner,name -q \u0026#39;.owner.login + \u0026#34;/\u0026#34; + .name\u0026#39;\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e``\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003eThis gives you OWNER/REPO. Use these values in all subsequent commands.\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e## Step 3: Fetch Unresolved Comments\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003eUse the PR number and OWNER/REPO from previous steps. Replace OWNER, REPO, and PR_NUMBER with the actual values — do NOT use $() substitution.\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003eFirst, get unresolved review threads via GraphQL:\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e``\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003egh api graphql -f query=\u0026#39;query { repository(owner:\u0026#34;OWNER\u0026#34;, name:\u0026#34;REPO\u0026#34;) { pullRequest(number:PR_NUMBER) { reviewThreads(first:100) { nodes { isResolved, comments(first:10) { nodes { id, body, author { login }, path, line } } } } } } }\u0026#39;\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e``\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sb\"\u003eOnly include threads where `\u003c/span\u003eisResolved\u003cspan class=\"sb\"\u003e` is `\u003c/span\u003efalse`. Skip any already-resolved threads entirely.\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"gs\"\u003e**Important**\u003c/span\u003e: Filter out noise before analysis. Ignore any comments from bots like SonarQube/SonarCloud (user login containing \u0026#34;sonar\u0026#34;) that indicate passing quality gates, no issues found, or \u0026#34;Passed\u0026#34; status. Only keep Sonar comments that flag actual issues, bugs, or code smells. Also ignore other CI bot comments that are purely status updates (e.g. coverage reports that just show numbers with no actionable feedback).\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"gu\"\u003e## Step 4: Critical Analysis\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eFor each comment, provide a structured analysis:\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003e-\u003c/span\u003e **Comment**: The reviewer\u0026#39;s feedback\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003e-\u003c/span\u003e **File \u0026amp; Line**: Where it applies\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003e-\u003c/span\u003e **Assessment**: Do you agree this is a valid concern? Be honest — if the comment is nitpicky, subjective, or wrong, say so with reasoning.\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003e-\u003c/span\u003e **Recommendation**: One of:\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e  \u003cspan class=\"k\"\u003e-\u003c/span\u003e **AGREE \u0026amp; FIX** — Valid point, here\u0026#39;s the proposed change\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e  \u003cspan class=\"k\"\u003e-\u003c/span\u003e **DISCUSS** — Has merit but needs discussion, here\u0026#39;s a suggested reply\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e  \u003cspan class=\"k\"\u003e-\u003c/span\u003e **PUSH BACK** — Disagree, here\u0026#39;s why and a suggested reply\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003e-\u003c/span\u003e **Proposed Change** (if fixing): Show the exact code diff\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"gu\"\u003e## Step 5: Present the Plan\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003ePresent ALL comments with your analysis in a single summary table, then wait for my approval before making any changes.\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"gu\"\u003e## Step 6: Execute (only after approval)\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eOnce I confirm which comments to resolve:\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003e1.\u003c/span\u003e Make the code changes for approved fixes\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003e2.\u003c/span\u003e For DISCUSS/PUSH BACK items, draft reply comments\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003e3.\u003c/span\u003e Stage and show me the final diff before committing\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003ch3 id=\"permissions\"\u003ePermissions\u003c/h3\u003e\n\u003cp\u003eThis is optional, without it you\u0026rsquo;ll need to approve multiple commands.\u003c/p\u003e","title":"Pull Request Review Resolution with Claude Code"},{"content":"In standard Maven projects, versions are hardcoded in the POM, requiring a manual update after every release. This workflow is prone to several issues that often complicate CI/CD pipelines. I will explain why this approach is problematic and show a better way to handle releases by decoupling the version and Git operations from Maven.\nLet\u0026rsquo;s first revise what Maven offers out of the box, namely the maven-release-plugin workflow:\nChange version from 0.1.0-SNAPSHOT to 0.1.0. Commit the change and create a Git release tag. Build and push the tagged version to the repository. Bump the version to 0.1.1-SNAPSHOT and commit again. Issues with Maintaining Hardcoded Versions in POM Noise in Git History Tags are required as they mark a point in Git history where we can reliably track releases. Version change commits, on the other hand, are not used in any context and add noise.\nMerge Conflicts Regardless of the branching strategy, we will eventually need to merge branches, like bringing a hotfix into the main branch. Because both branches have different hardcoded versions, an immediate merge conflict is triggered.\nThere are some options to work around this like cherry-picking and merge strategies among others, but that adds significant complexity to the CI/CD automation.\nSecurity Issues As per best practices, the main branches should be protected, preventing direct pushes, deletions, commits without a pull request etc. In mature projects, CI/CD automation typically handles releases, creating a problem: we must either manually approve every version-change PR or whitelist a bot/user to bypass branch protection rules. Both are poor options: the first defeats the purpose of automation, while the second has security risks like self-escalation via workflow edits. Here is an intersting discussion around the later one.\nThe Solution: Decouple Versioning and Git Operations from Maven Seeing the initial workflow, it is clear that Maven has two distinct roles: release orchestration and artifact deployment. To solve this, we need to separate the responsibilities between two actors:\nCI/CD: Acting as the orchestrator of the release process. Maven: Building and publishing the artifact. While the following example focuses on a multi-module project, these steps are equally valid for standard projects. You can view the full implementation in this PR, but let\u0026rsquo;s break down each step:\n1. Remove hardcoded version Update the POMs to use ${revision} instead of hardcoded versions. This should be done for the parent as well as children POMs.\nInstead of:\n\u0026lt;groupId\u0026gt;md.adrian\u0026lt;/groupId\u0026gt; \u0026lt;artifactId\u0026gt;crop-parent\u0026lt;/artifactId\u0026gt; \u0026lt;version\u0026gt;0.1.3\u0026lt;/version\u0026gt; we use:\n\u0026lt;groupId\u0026gt;md.adrian\u0026lt;/groupId\u0026gt; \u0026lt;artifactId\u0026gt;crop-parent\u0026lt;/artifactId\u0026gt; \u0026lt;version\u0026gt;${revision}\u0026lt;/version\u0026gt; 2. Define a Default Version in the Parent POM Defining a default version is necessary for local builds and IDEs to avoid errors. It can be overridden via the command line argument -Drevision=0.1.5-SNAPSHOT.\n\u0026lt;properties\u0026gt; \u0026lt;revision\u0026gt;0.1.4-SNAPSHOT\u0026lt;/revision\u0026gt; \u0026lt;/properties\u0026gt; 3. Add the Flatten Maven Plugin This should be done for two reasons: to resolve ${revision} and to remove everything that is not needed for the consumers of the artifact. The plugin actually creates other POMs. It is important to note that there are a couple of flatten modes:\nresolveCiFriendliesOnly: Useful for CI/CD pipelines, like running tests. It will only resolve ${revision} in our case, but the rest will remain as is. ossrh: Useful for flattening when publishing to Maven Central. It removes everything that the consumer of the artifact does not actually use (parent references, build plugins, profiles, etc.) and creates a clean, minimal POM. The published POM will look like this:\n\u0026lt;groupId\u0026gt;md.adrian\u0026lt;/groupId\u0026gt; \u0026lt;artifactId\u0026gt;crop\u0026lt;/artifactId\u0026gt; \u0026lt;version\u0026gt;1.0.0\u0026lt;/version\u0026gt; \u0026lt;dependencies\u0026gt; \u0026lt;dependency\u0026gt; \u0026lt;groupId\u0026gt;jakarta.persistence\u0026lt;/groupId\u0026gt; \u0026lt;artifactId\u0026gt;jakarta.persistence-api\u0026lt;/artifactId\u0026gt; \u0026lt;version\u0026gt;3.1.0\u0026lt;/version\u0026gt; \u0026lt;/dependency\u0026gt; \u0026lt;/dependencies\u0026gt; 4. Update .gitignore Add .flattened-pom.xml to our .gitignore, so that we don\u0026rsquo;t accidentally commit automatically generated flattened POMs.\n5. Update the CI/CD Pipeline Amend the Maven deploy command to pass the revision version.\nmvn deploy -Drevision=${{ steps.extract_version.outputs.version }} In this example, the version is pulled directly from the GitHub Release action, which says both what version is used and when the release occurs. Once these responsibilities are separated, it is easy to extend the logic, for instance, by implementing automatic version calculation similar to jgitver. But be carefull: in CI/CD pipeline, not in Maven.\n","permalink":"https://adrian.md/2026/01/02/decouple-version-maven/","summary":"\u003cp\u003eIn standard Maven projects, versions are hardcoded in the POM, requiring a manual update after every release. This workflow is prone to several issues that often complicate CI/CD pipelines. I will explain why this approach is problematic and show a better way to handle releases by decoupling the version and Git operations from Maven.\u003c/p\u003e\n\u003cp\u003eLet\u0026rsquo;s first revise what Maven offers out of the box, namely the \u003ccode\u003emaven-release-plugin\u003c/code\u003e workflow:\u003c/p\u003e\n\u003col\u003e\n\u003cli\u003eChange version from 0.1.0-SNAPSHOT to 0.1.0.\u003c/li\u003e\n\u003cli\u003eCommit the change and create a Git release tag.\u003c/li\u003e\n\u003cli\u003eBuild and push the tagged version to the repository.\u003c/li\u003e\n\u003cli\u003eBump the version to 0.1.1-SNAPSHOT and commit again.\u003c/li\u003e\n\u003c/ol\u003e\n\u003ch3 id=\"issues-with-maintaining-hardcoded-versions-in-pom\"\u003eIssues with Maintaining Hardcoded Versions in POM\u003c/h3\u003e\n\u003ch4 id=\"noise-in-git-history\"\u003eNoise in Git History\u003c/h4\u003e\n\u003cp\u003eTags are required as they mark a point in Git history where we can reliably track releases. Version change commits, on the other hand, are not used in any context and add noise.\u003c/p\u003e","title":"Decouple Maven Releases from Version Logic"},{"content":"I\u0026rsquo;m happy to share that I\u0026rsquo;ve added a new feature to CrOp and also moved it to a new namespace.\nIn my previous articles, I explained what problem it solves in a typical REST service. At the time, I was still missing a way to count the total result. This is a must-have in a paginated query. @Query from Spring Data JPA, for example, has a separate attribute for that - countQuery.\nSeems trivial now, as any problem in retrospect, but at the time I was getting SqmRoot not yet resolved to TableGroup error. And that was because I was using the wrong root to apply predicates for count. Storing predicates as a function that accepts another root allowed me to reapply them for count.\nBelow is an example of count. Note that it is the same query as for select, but a different execution method at the end:\n@GetMapping(\u0026#34;/pets/count\u0026#34;) Long count(PetCriteriaOperator searchCriteria) { return cropService.create(Pet.class, searchCriteria) .match(Pet_.id, PetCriteriaOperator::getId) .match(Pet_.name, PetCriteriaOperator::getNickname) .match(Pet_.birthdate, PetCriteriaOperator::getBirthdate) .match(Pet_.price, PetCriteriaOperator::getPrice) .join(Pet_.features) .match(PetFeature_.feature, PetCriteriaOperator::getFeatures) .endJoin() .match(Pet_.active, PetCriteriaOperator::getActive) .join(Pet_.petType) .match(PetType_.code, PetCriteriaOperator::getType) .join(PetType_.petCategory) .match(PetCategory_.code, PetCriteriaOperator::getCategory) .endJoin() .endJoin() .getCount(); } About the namespace, I did it for simple economic reasons - did not want to renew the old domain com.apulbere, so I published instead under md.adrian. The library can now be found at the coordinates:\n\u0026lt;dependency\u0026gt; \u0026lt;groupId\u0026gt;md.adrian\u0026lt;/groupId\u0026gt; \u0026lt;artifactId\u0026gt;crop\u0026lt;/artifactId\u0026gt; \u0026lt;version\u0026gt;0.1.3\u0026lt;/version\u0026gt; \u0026lt;/dependency\u0026gt; This project was more than just trying to solve a problem. It made me think very carefully about the design choices of an API, just a few of them:\nWas it a correct choice to use the Metamodel API? Example Pet_.name in .match(Pet_.name, PetCriteriaOperator::getNickname). Perhaps using strings and forcing the JPA provider to perform the Metamodel lookup at runtime could offer more flexibility, but less type safety. At the same time, in the examples I provided, I used a statically generated metamodel, but not everyone is a fan such tools. It\u0026rsquo;s always about compromises.\nHow should I test it? While I am currently using a demo project for integration testing, the long-term goal is to move tests closer to the source code. That means bringing a specific JPA provider and testing through it.\nDoes the API have enough flexibility for further enhancements and extensibility? Let\u0026rsquo;s say I need to add customizable validation for input parameters without breaking the existing contract. Here, I should carefully consider what the core idea and domain of the library are, and whatever needs to be added is a part of it.\nAnd perhaps the most challenging one: Does the API offer too much? Currently, once you define a filter, you automatically get every operator for that data type. For example, a string filter exposes like alongside the basics eq, neq, and in. This can be a problem if your database isn\u0026rsquo;t optimized for full-text search. I mention this because using a tool in the wrong context doesn\u0026rsquo;t make the tool itself flawed - it just means it\u0026rsquo;s being pushed beyond its intended limits.\nThe primary goal was to power a front-end data grid, and the library handles that job perfectly. Of course, every design comes with trade-offs, and I’ve tried to be as transparent as possible about those here.\n","permalink":"https://adrian.md/2025/12/22/crop-new-namespace/","summary":"\u003cp\u003eI\u0026rsquo;m happy to share that I\u0026rsquo;ve added a new feature to \u003ca href=\"https://github.com/apulbere/crop\" target=\"_blank\" rel=\"noopener\"\u003eCrOp\u003c/a\u003e and also moved it to a new namespace.\u003c/p\u003e\n\u003cp\u003eIn my \u003ca href=\"https://adrian.md/2024/07/14/crop/\"\u003eprevious articles\u003c/a\u003e, I explained what problem it solves in a typical REST service. At the time, I was still missing a way to count the total result. This is a must-have in a paginated query. \u003ca href=\"https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/Query.html\" target=\"_blank\" rel=\"noopener\"\u003e\u003ccode\u003e@Query\u003c/code\u003e\u003c/a\u003e from Spring Data JPA, for example, has a separate attribute for that - \u003ccode\u003ecountQuery\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003eSeems trivial now, as any problem in retrospect, but at the time I was getting \u003ccode\u003eSqmRoot not yet resolved to TableGroup\u003c/code\u003e error. And that was because I was using the wrong root to apply predicates for count.\nStoring predicates as a function that accepts another root allowed me to reapply them for count.\u003c/p\u003e","title":"CrOp 0.1.3: Adding Result Counts and a Look at API Trade-offs"},{"content":"ORMs promise to simplify persistence, but in practice, they introduce recurring problems.\nIn many cases, there’s no clear or well-documented justification for why an ORM was introduced in the first place. Most probably it’s adopted by default, based on assumptions such as the belief that you can switch the database vendor without changing any code or that an ORM somehow “bridges” object-oriented programming and relational databases.\nWhile intended to ease data access, ORMs often end up dictating the entire application design. Instead of designing models around business logic, we adapt them to fit ORM limitations, flattening structures, adding unnecessary relationships, or compromising encapsulation just to bypass ORM constraints. The result is a codebase where the data model drives the design and the actual logic comes second.\nSince ORMs typically map entire database tables to entities, these entities tend to get passed throughout the application. The issue? You rarely need all the fields, let alone the related entities that are pulled in by default. Projections or custom queries can help, but despite code reviews, overfetching still frequently slips through.\nWe strive for loose coupling between components for good reason. But under the hood, many ORMs create tightly coupled entity graphs through bidirectional or deeply nested relationships. The model becomes tangled, what seems like a minor change in one part can trigger unpredictable behavior elsewhere. One use case might require a lazy one-to-one mapping, while another needs it eager, both relying on the same entity. The result: conflict and performance degradation.\nWhen debugging performance issues, you’re forced to work at two layers: the ORM abstraction (JPQL, HQL, etc.) and the raw SQL it generates. This doubles the effort and mental overhead.\nORMs claim to offer vendor-agnosticism, but that illusion breaks down the moment you need a database-specific feature or optimization. Suddenly, you\u0026rsquo;re writing native queries or injecting dialect-specific logic, completely undermining the abstraction. Worse, when these two layers collide, you end up manually triggering flushes, refreshes, or other operations to keep them in sync.\nSome argue that these issues arise from developers not fully understanding the tool, and sure, there’s truth in that. But ORMs were supposed to simplify development, not require mastery of every quirk just to execute a query properly.\n","permalink":"https://adrian.md/2025/07/23/premature-orm/","summary":"\u003cp\u003eORMs promise to simplify persistence, but in practice, they introduce recurring problems.\u003c/p\u003e\n\u003cp\u003eIn many cases, there’s no clear or well-documented justification for why an ORM was introduced in the first place. Most probably it’s adopted by default, based on assumptions such as the belief that you can switch the database vendor without changing any code or that an ORM somehow “bridges” object-oriented programming and relational databases.\u003c/p\u003e\n\u003cp\u003eWhile intended to ease data access, ORMs often end up dictating the entire application design. Instead of designing models around business logic, we adapt them to fit ORM limitations, flattening structures, adding unnecessary relationships, or compromising encapsulation just to bypass ORM constraints. The result is a codebase where the data model drives the design and the actual logic comes second.\u003c/p\u003e","title":"Premature ORM-ification"},{"content":"Search functionality is so ubiquitous in any web app that at some point you start asking yourself if it can be done any easier. Introducing CrOp, a lightweight, zero dependency, and type-safe wrapper around Java Persistence Criteria API, which simplifies building queries, particularly useful within REST SQL (RSQL) context.\nLet\u0026rsquo;s dive into it\u0026rsquo;s core principles.\nZero Dependency We all know the pain of upgrading dependencies. What I find the most troublesome is going through compatibility matrices (if you are lucky enough to find them). For example, you can\u0026rsquo;t use Spring 3 with Hibernate 5. And if you built something with Hibernate 5, you\u0026rsquo;ll have to rewrite it before upgrading Spring.\nThat\u0026rsquo;s why CrOp relies on the JPA specification and is agnostic to the underlying implementation, whether it\u0026rsquo;s Hibernate, EclipseLink, Apache OpenJPA, or any other.\nType Safe CrOp guarantees compile type-safety without relying on reflection. It has specialized wrapper classes for most common data types and allows mapping only JPA\u0026rsquo;s Metamodel. Meaning for example that you cannot use a String to query a Long entity field. Your code won\u0026rsquo;t simply compile if your try to do such thing.\nOptimized Database optimization can refer to a lot of things, but what CrOp can do (for now) is to promise that it won\u0026rsquo;t add unnecessary joins. For example, you have two entities Pet and PetType with a one-to-one relationship between them, and sometimes you wish to include pet type in search. Guess what, only when the lookup parameter is present the join with PetType will happen.\n@GetMapping(\u0026#34;/pets\u0026#34;) List\u0026lt;PetRecord\u0026gt; findAll(PetCriteriaOperator searchCriteria, CriteriaOperatorOrder order, CriteriaOperatorPage page) { return cropService.create(Pet.class, searchCriteria, order, page) .match(Pet_.name, PetCriteriaOperator::getNickname) .join(Pet_.petType) .match(PetType_.code, PetCriteriaOperator::getType) .endJoin() .getResultList() .stream() .map(petMapper::map) .toList(); } Example A GET request like http://localhost:64503/pets?birthdate.gte=2010-01-11\u0026amp;nickname.like=Ba, is transformed by CrOp (via an ORM) into the following SQL:\nselect p1_0.id, p1_0.birthdate, p1_0.name, p1_0.pet_type_id from pet p1_0 where p1_0.name like ? escape \u0026#39;\u0026#39; and p1_0.birthdate\u0026gt;=? There are a couple of easy steps to achieve the above:\nAdd the dependency \u0026lt;dependency\u0026gt; \u0026lt;groupId\u0026gt;md.adrian\u0026lt;/groupId\u0026gt; \u0026lt;artifactId\u0026gt;crop\u0026lt;/artifactId\u0026gt; \u0026lt;version\u0026gt;0.1.3\u0026lt;/version\u0026gt; \u0026lt;/dependency\u0026gt; Define a DTO that contains all fields necessary for filtering. For example, if you want to do filtering on String type then you choose StringCriteriaOperator from md.adrian.crop.operator package. @Getter @Setter public class PetSearchCriteria { private StringCriteriaOperator nickname; private LocalDateCriteriaOperator birthdate; } Create an instance of the service that will parse the query. It requires EntityManager in the constructor. @Bean CriteriaOperatorService cropService(EntityManager entityManager) { return new CriteriaOperatorService(entityManager); } Finally, invoke the service\u0026rsquo;s create method with the root entity and filter object. The result is a builder that lets you match the entity\u0026rsquo;s meta-model with each field from the DTO. When done, execute the query. @GetMapping(\u0026#34;/pets\u0026#34;) List\u0026lt;PetRecord\u0026gt; search(PetSearchCriteria petSearchCriteria) { return cropService.create(Pet.class, petSearchCriteria) .match(Pet_.name, PetSearchCriteria::getNickname) .match(Pet_.birthdate, PetSearchCriteria::getBirthdate) .getResultList() .stream() .map(petMapper::map) .toList(); } For full example and to see all the capabilities of the library checkout pet-shop demo repository.\n","permalink":"https://adrian.md/2024/07/14/crop/","summary":"\u003cp\u003eSearch functionality is so ubiquitous in any web app that at some point you start asking yourself if it can be done any easier. Introducing \u003ca href=\"https://github.com/apulbere/crop\" target=\"_blank\" rel=\"noopener\"\u003eCrOp\u003c/a\u003e, a lightweight, zero dependency, and type-safe wrapper around Java Persistence Criteria API, which simplifies building queries, particularly useful within REST SQL (RSQL) context.\u003c/p\u003e\n\u003cp\u003eLet\u0026rsquo;s dive into it\u0026rsquo;s core principles.\u003c/p\u003e\n\u003ch3 id=\"zero-dependency\"\u003eZero Dependency\u003c/h3\u003e\n\u003cp\u003eWe all know the pain of upgrading dependencies. What I find the most troublesome is going through compatibility matrices (if you are lucky enough to find them). For example, you can\u0026rsquo;t use Spring 3 with Hibernate 5. And if you built something with Hibernate 5, you\u0026rsquo;ll have to rewrite it before upgrading Spring.\u003c/p\u003e","title":"Java Database Search Made Easy"},{"content":"Feature toggle is a technique that helps to change the system\u0026rsquo;s behavior without altering the code. It\u0026rsquo;s interesting how stories around it vary from the catastrophic failure of the Knight Capital Group[1] to the stellar success of the first GPS satellite[2]. In the following article, we\u0026rsquo;ll see a more typical example that all engineers have to deal with.\nDelivering a new feature according to Murphy\u0026rsquo;s Law Imagine an existing flow in a system that generates a PDF report, and then uploads it to the cloud:\n@AllArgsConstructor @Service class ReportService { PDFGenerator generator; StorageService storageService; void generateReport(Payload payload) { OutputStream reportStream = generator.generate(payload); storageService.upload(reportStream); } } Now the client wants to add a layer of authentication and sign the PDF before uploading. So let\u0026rsquo;s define an interface just for that:\ninterface SignerService { OutputStream sign(OutputStream payloadToSign); } And integrate it into the main flow:\n@AllArgsConstructor @Service class ReportService { PDFGenerator generator; SignerService signerService; StorageService storageService; void generateReport(Payload payload) { OutputStream reportStream = generator.generate(payload); OutputStream signedReportStream = signerService.sign(reportStream); storageService.upload(signedReportStream); } } Everything seems perfectly fine until uncertainties start to creep in. Let\u0026rsquo;s say we already merged into the main branch the change and even did a demo to the client using a self-signed certificate on the local environment. But shortly before deploying the new version of the system on upper environments, the DevOps informs us that they have problems installing a valid certificate.\nWhat do we do now? The main flow will certainly be broken. Not only the client won\u0026rsquo;t be able to receive his signed PDF, but he won\u0026rsquo;t receive a PDF at all. So, nothing left but to frantically revert the change, fix some conflicts on the way, run the regression, and finally prepare a new version.\nNow let\u0026rsquo;s imagine another scenario where right from the beginning we took into consideration Murphy\u0026rsquo;s law. In this scenario, even after we implemented the feature, the main flow should work as before and only when we wish so, to pass through the signing step.\n@Service class NoOpSignerService implements SignerService { @Override public OutputService sign(OutputService payloadToSign) { log.info(\u0026#34;bypassing signing step\u0026#34;); return payloadToSign; } } Above, is a noop implementation for the code to work as before. And below is another implementation that does the signing.\n@Service @Primary @ConditionalOnProperty(name = \u0026#34;activateSigning\u0026#34;, havingValue = \u0026#34;true\u0026#34;) class BCSignerService implements SignerService { @Override public OutputService sign(OutputService payloadToSign) { //... sign and return the payload } } Notice that this implementation is the primary one but Spring picks it up and injects it into the main flow only when activateSigning is true.\nStatic vs dynamic feature toggles Perhaps one of the objections to the above solution would be the fact that we have to change an environment variable (activateSigning) and do a restart. True, but this doesn\u0026rsquo;t necessarily mean that your service will be offline since you can have multiple instances and gradually replace them.\nThis approach is a static one, meaning that your application will work only with one state of the feature toggle, flipping it will not change the running system. There are certain use cases and reasons to choose the static feature toggle:\nIt\u0026rsquo;s one time only - you won\u0026rsquo;t need to go back and forth between states of the flag unless you have to \u0026ldquo;rollback\u0026rdquo; and revise it. The code is clean, testable, and modular. Notice that the feature lives in a separate class, apart from the rest of the code. The old unchanged tests still work, we just have to add a couple of test cases for the activated feature. The dynamic feature toggles are more fit for scenarios where they are dependent on user requests or the stakeholders want to control them via some management tool.\nAll things said, I think the feature toggle should be always considered during the design phase even if the client didn\u0026rsquo;t specifically request it and even if we don\u0026rsquo;t have a feature toggle discipline. We can always start small, with configuration properties as shown in this article.\n[1]How to lose half a billion dollars with bad feature flags\n[2]The Relativity Switch\n[3]Murphy\u0026rsquo;s law\n","permalink":"https://adrian.md/2023/08/22/feature-toggle/","summary":"\u003cp\u003eFeature toggle is a technique that helps to change the system\u0026rsquo;s behavior without altering the code. It\u0026rsquo;s interesting how stories around it vary from the catastrophic failure of the Knight Capital Group\u003csup\u003e[1]\u003c/sup\u003e to the stellar success of the first GPS satellite\u003csup\u003e[2]\u003c/sup\u003e.\nIn the following article, we\u0026rsquo;ll see a more typical example that all engineers have to deal with.\u003c/p\u003e\n\u003ch3 id=\"delivering-a-new-feature-according-to-murphys-law\"\u003eDelivering a new feature according to Murphy\u0026rsquo;s Law\u003c/h3\u003e\n\u003cp\u003eImagine an existing flow in a system that generates a PDF report, and then uploads it to the cloud:\u003c/p\u003e","title":"A Feature Toggle Story"},{"content":"Writing unit tests might be challenging, especially when dealing with an ongoing project with already established hard-to-break anti-patterns.\nI will go through some of the most common pitfalls I\u0026rsquo;ve encountered quite often.\nVerifying the stubs Let\u0026rsquo;s suppose we write the following piece of code:\n@AllArgsConstructor public class UserCreationService { private final UserFactory factory; private final UserRepository repository; private final NotificationService notificationService; public void create(UserCreateRequest request) { var user = factory.createEntity(request); user = repository.save(user); notificationService.notify(USER_CREATED, user.getId()); } } And then create a test for the happy path:\n@Test void userCreatedSuccessfully() { var request = new UserCreateRequest(); var userEntity = new UserEntity(randomUUID()); when(factory.createEntity(request)).thenReturn(userEntity); when(repository.save(userEntity)).then(returnsFirstArg()); userCreationService.create(request); verify(repository).save(userEntity); verify(notificationService).notify(USER_CREATED, userEntity.getId()); } The first verify is redundant. Some engineers keep verifying every single stub resulting in noise and duplicated code. Every time you modify the stub you also have to do the same for verify step. More than that, if the stub is broken, then verify will not be executed, and if the stub passes then verify will always pass. The issue is worse if the test has an @AfterEach with verifyNoMoreInteractions and strictness = Strictness.WARN. It forces you to write verify even if you don\u0026rsquo;t want to.\nVerifying the stubs should be rather an exception than a regular thing.\nTest data constants When setting up the test module for a project, often the second thing to do after adding the testing framework is to create a common test data class. In no time this class is filled up with lots of constants shared across dozen of tests.\nLet\u0026rsquo;s start enumerating the problems:\nConstants are misused. A constant like public static final String ID = \u0026quot;550e8400...\u0026quot; is set as user id, market id, and so on. There is no relation whatever between all these entities, it\u0026rsquo;s misused most probably because fits the data type and was automatically imported by IDE. What if the market id should be UUID while the user id is the username? Mutable objects are declared as constants. This is the best recipe for \u0026ldquo;Why do the tests fail on Jenkins?\u0026rdquo;. The alternatives to test data constants are factories and abstract factories. If you need a user id then declare a method in UserFactory that creates that id. This way it\u0026rsquo;s easy to change the value, make it a constant or randomly generated.\nTests know too much Using reflection to set fields, invoke a method, a constructor, change access modifier, etc. - all this done for testing purposes is always a sure sign of poorly written tests. The worst part is if you go and alter the source code for the sake of a test. Doing any of the above tricks is a sign that the code requires refactoring.\nIn conclusion, testing should show how good the code you wrote is. And one thing that many forget is that tests should adhere to the same programming principle as the base code.\n","permalink":"https://adrian.md/2023/08/11/unit-testing-anti-patterns/","summary":"\u003cp\u003eWriting unit tests might be challenging, especially when dealing with an ongoing project with already established hard-to-break anti-patterns.\u003c/p\u003e\n\u003cp\u003eI will go through some of the most common pitfalls I\u0026rsquo;ve encountered quite often.\u003c/p\u003e\n\u003ch3 id=\"verifying-the-stubs\"\u003eVerifying the stubs\u003c/h3\u003e\n\u003cp\u003eLet\u0026rsquo;s suppose we write the following piece of code:\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-java\" data-lang=\"java\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"nd\"\u003e@AllArgsConstructor\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"kd\"\u003epublic\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003eclass\u003c/span\u003e \u003cspan class=\"nc\"\u003eUserCreationService\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"p\"\u003e{\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e    \u003c/span\u003e\u003cspan class=\"kd\"\u003eprivate\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003efinal\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eUserFactory\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003efactory\u003c/span\u003e\u003cspan class=\"p\"\u003e;\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e    \u003c/span\u003e\u003cspan class=\"kd\"\u003eprivate\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003efinal\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eUserRepository\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003erepository\u003c/span\u003e\u003cspan class=\"p\"\u003e;\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e    \u003c/span\u003e\u003cspan class=\"kd\"\u003eprivate\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003efinal\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eNotificationService\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003enotificationService\u003c/span\u003e\u003cspan class=\"p\"\u003e;\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e    \u003c/span\u003e\u003cspan class=\"kd\"\u003epublic\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kt\"\u003evoid\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"nf\"\u003ecreate\u003c/span\u003e\u003cspan class=\"p\"\u003e(\u003c/span\u003e\u003cspan class=\"n\"\u003eUserCreateRequest\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003erequest\u003c/span\u003e\u003cspan class=\"p\"\u003e)\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"p\"\u003e{\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e        \u003c/span\u003e\u003cspan class=\"kd\"\u003evar\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003euser\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003efactory\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"na\"\u003ecreateEntity\u003c/span\u003e\u003cspan class=\"p\"\u003e(\u003c/span\u003e\u003cspan class=\"n\"\u003erequest\u003c/span\u003e\u003cspan class=\"p\"\u003e);\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e        \u003c/span\u003e\u003cspan class=\"n\"\u003euser\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003erepository\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"na\"\u003esave\u003c/span\u003e\u003cspan class=\"p\"\u003e(\u003c/span\u003e\u003cspan class=\"n\"\u003euser\u003c/span\u003e\u003cspan class=\"p\"\u003e);\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e        \u003c/span\u003e\u003cspan class=\"n\"\u003enotificationService\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"na\"\u003enotify\u003c/span\u003e\u003cspan class=\"p\"\u003e(\u003c/span\u003e\u003cspan class=\"n\"\u003eUSER_CREATED\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003euser\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"na\"\u003egetId\u003c/span\u003e\u003cspan class=\"p\"\u003e());\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e    \u003c/span\u003e\u003cspan class=\"p\"\u003e}\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e}\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eAnd then create a test for the happy path:\u003c/p\u003e","title":"Unit Testing Anti-Patterns"},{"content":"One of the most common features in a typical web application is the search functionality. The tricky thing is that we have to provide it via REST API and make it quite dynamic in terms of supported operators and filtrable fields. In the following paragraphs, we\u0026rsquo;ll go through what QueryDSL offers and how a lightweight extension could help.\nOut of the box, QueryDSL comes with Web Support. It boils down to having a Predicate parameter in REST controller method. The bad news is that you cannot do much of the customization. Imagine the ubiquitous example of Pet Shop, where we have to search by nickname using contains or exact match. The natural thing that comes to mind is having in a query parameter the search field, operator and value:\n/pets?nickname=like:Br or\n/pets?nickname=Britney The above example is possible if you extend QuerydslBinderCustomizer parse the parameter value, extract the operator and invoke the appropriate expression. But it is not possible if you have other data type than String. QueryDSL first looks at the Q type field and converts the value, only after that we have it in the customizer. For example, the following /pets?birthdate=between:2000-01-01,2023-01-01 will fail because the value between:2000-01-01,2023-01-01 cannot be parsed as LocalDate and we have no (correct) way to fix that.\nPresenting RSQL-QueryDSL library The philosophy behind the library is to be just a bridge between REST and QueryDSL. Things like parsing fields and operators, conversion of values, and building predicates are already well handled by Spring and QueryDSL.\nSo let\u0026rsquo;s jump straight to the example and see how it works in the Pet Shop web application.\nFirst of all we add the dependency in our POM:\n\u0026lt;dependency\u0026gt; \u0026lt;groupId\u0026gt;io.github.apulbere\u0026lt;/groupId\u0026gt; \u0026lt;artifactId\u0026gt;rsql-querydsl\u0026lt;/artifactId\u0026gt; \u0026lt;version\u0026gt;1.0\u0026lt;/version\u0026gt; \u0026lt;/dependency\u0026gt; Next, we define a DTO containing all fields that we want to use in the search:\n@Setter @Getter public class PetCriteria { LongCriteria id = LongCriteria.empty(); LocalDateCriteria born = LocalDateCriteria.empty(); StringCriteria petType = StringCriteria.empty(); StringCriteria nickname = StringCriteria.empty(); } And finally, we use the above DTO as a parameter in the controller method. Spring will automatically map request parameters to the DTO:\n@GetMapping(\u0026#34;/pets\u0026#34;) List\u0026lt;PetRecord\u0026gt; search(PetCriteria criteria, Pageable page) { var predicate = criteria.id.match(pet.id) .and(criteria.born.match(pet.birthdate)) .and(criteria.nickname.match(pet.name)) .and(criteria.petType.match(pet.type)); return petRepository.findAll(predicate, page) .stream() .map(petMapper::map) .toList(); } Now we can make a request using the parameter names matching the ones from DTO and operators natural to their types. For example, it makes sense to have LIKE with String but not with Long:\n/pets?nickname.like=Br The above request produces the following SQL:\nselect p1_0.id, p1_0.birthdate, p1_0.name, p1_0.type from pet p1_0 where lower(p1_0.name) like ? offset ? rows fetch first ? rows only Full code can be found over on GitHub.\n","permalink":"https://adrian.md/2023/01/07/querydsl-rsql/","summary":"\u003cp\u003eOne of the most common features in a typical web application is the search functionality. The tricky thing is that we have to provide it via REST API and make it quite dynamic in terms of supported operators and filtrable fields. In the following paragraphs, we\u0026rsquo;ll go through what QueryDSL offers and how a lightweight extension could help.\u003c/p\u003e\n\u003cp\u003eOut of the box, QueryDSL comes with \u003ca href=\"https://docs.spring.io/spring-data/commons/docs/current/reference/html/#core.web.type-safe\" target=\"_blank\" rel=\"noopener\"\u003eWeb Support\u003c/a\u003e. It boils down to having a Predicate parameter in REST controller method. The bad news is that you cannot do much of the customization. Imagine the ubiquitous example of Pet Shop, where we have to search by nickname using contains or exact match. The natural thing that comes to mind is having in a query parameter the search field, operator and value:\u003c/p\u003e","title":"REST Search API with QueryDSL"},{"content":"Java 11, among other features, introduced the possibility of running a single Java source file. We are going to see a practical example of this feature running with kubernetes.\napiVersion: v1 kind: ConfigMap metadata: name: java-shebang-config-map data: script.sh: | #!/usr/bin/java --source 17 public class App { public static void main(String args[]) { System.out.println(\u0026#34;Hello Java Script\u0026#34;); } } --- apiVersion: v1 kind: Pod metadata: name: app spec: volumes: - name: java-shebang-config configMap: name: java-shebang-config-map defaultMode: 0777 containers: - image: openjdk:17.0.2-oracle command: [\u0026#34;./scripts/script.sh\u0026#34;] name: app volumeMounts: - mountPath: /scripts name: java-shebang-config restartPolicy: Never kubectl create -f hello-java.yml kubectl logs app ","permalink":"https://adrian.md/2022/08/10/java-shebang-kubernetes/","summary":"\u003cp\u003eJava 11, among other features, introduced the possibility of running a single Java source file. We are going to see a practical example of this feature running with kubernetes.\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-hello-java.yml\" data-lang=\"hello-java.yml\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"nt\"\u003eapiVersion\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003ev1\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"nt\"\u003ekind\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003eConfigMap\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"nt\"\u003emetadata\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e  \u003c/span\u003e\u003cspan class=\"nt\"\u003ename\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003ejava-shebang-config-map\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"nt\"\u003edata\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e  \u003c/span\u003e\u003cspan class=\"nt\"\u003escript.sh\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e\u003cspan class=\"sd\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sd\"\u003e    #!/usr/bin/java --source 17\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sd\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sd\"\u003e    public class App {\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sd\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sd\"\u003e        public static void main(String args[]) {\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sd\"\u003e            System.out.println(\u0026#34;Hello Java Script\u0026#34;);\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sd\"\u003e        }\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"sd\"\u003e    }\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"nn\"\u003e---\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"nt\"\u003eapiVersion\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003ev1\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"nt\"\u003ekind\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003ePod\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"nt\"\u003emetadata\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e  \u003c/span\u003e\u003cspan class=\"nt\"\u003ename\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003eapp\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"nt\"\u003espec\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e  \u003c/span\u003e\u003cspan class=\"nt\"\u003evolumes\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e  \u003c/span\u003e- \u003cspan class=\"nt\"\u003ename\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003ejava-shebang-config\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e    \u003c/span\u003e\u003cspan class=\"nt\"\u003econfigMap\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e      \u003c/span\u003e\u003cspan class=\"nt\"\u003ename\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003ejava-shebang-config-map\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e      \u003c/span\u003e\u003cspan class=\"nt\"\u003edefaultMode\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"m\"\u003e0777\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e  \u003c/span\u003e\u003cspan class=\"nt\"\u003econtainers\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e  \u003c/span\u003e- \u003cspan class=\"nt\"\u003eimage\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003eopenjdk:17.0.2-oracle\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e    \u003c/span\u003e\u003cspan class=\"nt\"\u003ecommand\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"p\"\u003e[\u003c/span\u003e\u003cspan class=\"s2\"\u003e\u0026#34;./scripts/script.sh\u0026#34;\u003c/span\u003e\u003cspan class=\"p\"\u003e]\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e    \u003c/span\u003e\u003cspan class=\"nt\"\u003ename\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003eapp\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e    \u003c/span\u003e\u003cspan class=\"nt\"\u003evolumeMounts\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e      \u003c/span\u003e- \u003cspan class=\"nt\"\u003emountPath\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003e/scripts\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e        \u003c/span\u003e\u003cspan class=\"nt\"\u003ename\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003ejava-shebang-config\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e  \u003c/span\u003e\u003cspan class=\"nt\"\u003erestartPolicy\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003eNever\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cpre tabindex=\"0\"\u003e\u003ccode\u003ekubectl create -f hello-java.yml\nkubectl logs app\n\u003c/code\u003e\u003c/pre\u003e","title":"Running Java shebang with Kubernetes"},{"content":"A well-known characteristic of Java Stream is that it can be consumed only once, thus if we want to do some operations that require two passes or more through elements we have to create a new stream or develop a custom collector. Thankfully, Java 12 comes with Collectors::teeing that solves exactly this situation.\nImagine that we need a concise way to get both the min and max values of a stream.\nWe know how to do that if deal with specialized primitive streams by terminating it with operations like summarizingInt:\n@Test void shouldFindMinAndMaxInt() { IntSummaryStatistics statistics = IntStream.of(32, 42, 1, 2) .summaryStatistics(); assertEquals(42, statistics.getMax()); assertEquals(1, statistics.getMin()); } Similarly we have specialized collectors when dealing with objects:\n@Test void shouldFindMinAndMaxProduct() { record Product(String label, double price) {} var products = Stream.of( new Product(\u0026#34;T-Shirt\u0026#34;, 12.99), new Product(\u0026#34;socks\u0026#34;, 5.09), new Product(\u0026#34;pants\u0026#34;, 89.1) ); DoubleSummaryStatistics statistics = products.collect( Collectors.summarizingDouble(Product::price) ); assertEquals(89.01, statistics.getMax()); assertEquals(5.09, statistics.getMin()); } The drawback of these collectors is that we don\u0026rsquo;t know which object is the max or min we have just its value. Using Collectors::maxBy and Collectors::minBy will require to pass the stream twice.\nThankfully, the following collector alleviates this problem:\npublic static \u0026lt;T, R1, R2, R\u0026gt; Collector\u0026lt;T, ?, R\u0026gt; teeing( Collector\u0026lt;? super T, ?, R1\u0026gt; downstream1, Collector\u0026lt;? super T, ?, R2\u0026gt; downstream2, BiFunction\u0026lt;? super R1, ? super R2, R\u0026gt; merger) { //... } Collectors::teeing has three arguments first two are downstream collectors. Every stream element is processed by each of them. The third parameter is a BiFunction that merges two results into the single one, e.g. it can be a function that creates a pair.\nConsider the following record representing a movie:\nrecord Movie(String title, double rating) {} Finding the best and worst movie in a single stream pass is as simple as:\n@Test void shouldFindWorstAndBestMovie() { var m1 = new Movie(\u0026#34;Groundhog Day\u0026#34;, 8); var m2 = new Movie(\u0026#34;Stop! Or My Mom Will Shoot\u0026#34;, 4.4); var m3 = new Movie(\u0026#34;Forrest Gump\u0026#34;, 8.8); record MovieStatistics(Movie worst, Movie best) {} var ratingComparator = Comparator.comparing(Movie::rating); var movieStatistics = Stream.of(m1, m2, m3) .collect(Collectors.teeing( Collectors.minBy(ratingComparator), Collectors.maxBy(ratingComparator), (worst, best) -\u0026gt; new MovieStatistics( worst.orElse(null), best.orElse(null) ) )); assertEquals(m2, movieStatistics.worst()); assertEquals(m3, movieStatistics.best()); } The best part about teeing collector is that we can handle much more complex scenarios by combining multiple collectors downstream. Consider the following enhanced Movie record:\nrecord Movie( String title, double rating, List\u0026lt;Genre\u0026gt; genres ) {} enum Genre { DRAMA, //... } We can find titles of drama movies and their average rating:\n@Test void shouldFindDramasTitlesAndAvgRating() { List\u0026lt;Movie\u0026gt; movies = readMoviesFromCSVFile(); record MovieStatistics(List\u0026lt;String\u0026gt; titles, double avgRating) {} var movieStatistics = movies.stream() .filter(m -\u0026gt; m.genres().contains(DRAMA)) .collect(teeing( mapping(Movie::title, toList()), averagingDouble(Movie::rating), MovieStatistics::new )); var expectedTitles = List.of( \u0026#34;Pulp Fiction\u0026#34;, \u0026#34;You\u0026#39;ve Got Mail\u0026#34;, \u0026#34;Forrest Gump\u0026#34; ); assertEquals(expectedTitles.size(), movieStatistics.titles().size()); assertTrue(expectedTitles.containsAll(movieStatistics.titles())); assertEquals(8.13, movieStatistics.avgRating(), /* delta */ 2); } In the main pipeline we filter movies by genre, then in teeing collector, for one downstream we extract movie titles and collect them in a list. For the second downstream, we produce a scalar - average rating. Finally, for the merger function, we pass a constructor reference that matches types returned by both downstream collectors.\nConclusion We can solve most of the problems with one out-of-the-box collector, even when we need to collect more than a collection or a scalar.\nFull code can be found over on GitHub.\n","permalink":"https://adrian.md/2021/05/09/teeing-collector/","summary":"\u003cp\u003eA well-known characteristic of Java \u003cem\u003eStream\u003c/em\u003e is that it can be consumed only once, thus if we want to do some operations that require two passes or more through elements we have to create a new stream or develop a custom collector. Thankfully, Java 12 comes with \u003cem\u003eCollectors::teeing\u003c/em\u003e that solves exactly this situation.\u003c/p\u003e\n\u003cp\u003eImagine that we need a concise way to get both the min and max values of a stream.\u003c/p\u003e","title":"How to collect more than a single collection or a single scalar"},{"content":"In this article, we\u0026rsquo;ll have a look at how to separate an application into different modules so that it can be developed and tested in isolation of any external dependencies. As a result, we\u0026rsquo;ll obtain loosely coupled components where things like database and communication protocol can easily be replaced without any changes in the domain logic.\nFirst of all, let\u0026rsquo;s introduce a user story so that the domain logic of the example will be clear from the start:\nUser Story As a client of the bookshop I want to be able to look up books by title So that I can choose the one I like Acceptance Criteria Given a collection of books When the user types a title Then all books matching that title will be returned Is natural that the first module we create, bookshop-domain, is the one that holds domain DTOs and secondary ports (secondary, because the application itself triggers the calls to other systems).\nAs per the bookshop example, we\u0026rsquo;ll need one record to hold all book\u0026rsquo;s fields:\npublic record Book(UUID id, String title, List\u0026lt;String\u0026gt; authors) { } And another record for search criteria:\npublic record BookSearchCriteria(String title) { } The secondary port BookRepository is an interface that declares a method for obtaining all the shop\u0026rsquo;s books:\npublic interface BookRepository { List\u0026lt;Book\u0026gt; findAll(); } Note that all the classes we just defined are not tied in any way to any framework\u0026rsquo;s specific classes, interfaces, or annotations. For example, Book is annotated neither with javax.persistence nor with Jackson annotations, although our application will persist data and expose REST endpoints.\nThe second module, bookshop-core, as the previous one, is also part of domain logic. It will hold a service that does exactly what was asked from us in the user story:\n@AllArgsConstructor public class BookService { private final BookRepository bookRepository; public List\u0026lt;Book\u0026gt; findAll(BookSearchCriteria criteria) { return bookRepository.findAll() .stream() .filter(matches(criteria)) .collect(toList()); } private Predicate\u0026lt;Book\u0026gt; matches(BookSearchCriteria criteria) { return book -\u0026gt; book.title() .toLowerCase() .contains(criteria.title().toLowerCase()); } } BookService can also be called port in the hexagonal architecture as it is the class that exposes and implements the domain logic. Creating an interface first for the port it\u0026rsquo;s not always necessary, especially if the interface and implementation reside in the same module.\nThe next module we want to develop is bookshop-inmem-persistence which will hold the following adapter:\npublic class InMemBooksRepository implements BookRepository { private final List\u0026lt;Book\u0026gt; books; public InMemBooksRepository(List\u0026lt;Book\u0026gt; books) { this.books = List.copyOf(books); } @Override public List\u0026lt;Book\u0026gt; findAll() { return books; } } For the sake of simplicity, we did an in-memory implementation, but normally this module will hold all entities, JPA repositories or DAOs, and converters from entities to bookshop-domain DTOs.\nFinally, the last module, bookshop-rest, exposes the endpoint and invokes the port to our domain logic:\n@RestController @AllArgsConstructor public class BooksController implements BooksApi { private final BookService bookService; private final DomainMapper domainMapper; @Override public ResponseEntity\u0026lt;List\u0026lt;Book\u0026gt;\u0026gt; listBooks(String title) { var criteria = new BookSearchCriteria(title); var books = bookService.findAll(criteria) .stream() .map(domainMapper::map) .collect(toList()); return ResponseEntity.ok(books); } } Notice that we convert the DTO returned by the service to another DTO, generated from an OpenAPI specification.\nConclusion We have seen examples of ports and adapters in hexagonal architecture, and how to properly organize the code in a decoupled fashion.\nFull code can be found over on GitHub.\n","permalink":"https://adrian.md/2021/05/01/ports-and-adapters/","summary":"\u003cp\u003eIn this article, we\u0026rsquo;ll have a look at how to separate an application into different modules so that it can be developed and tested in isolation of any external dependencies. As a result, we\u0026rsquo;ll obtain loosely coupled components where things like database and communication protocol can easily be replaced without any changes in the domain logic.\u003c/p\u003e\n\u003cp\u003eFirst of all, let\u0026rsquo;s introduce a user story so that the domain logic of the example will be clear from the start:\u003c/p\u003e","title":"How to Organize the Code in the Ports and Adapters Architecture"},{"content":"With the rise of lambda expression and newer features, there is an increasing necessity to review some of the functional programming concepts and how are they applied in Java.\nCurrying Currying is the process of turning a function with multiple arguments into a function with fewer arguments. For example, we can turn an addition between three numbers into a single argument function:\nFunction\u0026lt;Integer, Function\u0026lt;Integer, Function\u0026lt;Integer, Integer\u0026gt;\u0026gt;\u0026gt; abc = a -\u0026gt; b -\u0026gt; c -\u0026gt; a + b + c; assert abc.apply(1).apply(2).apply(3) == 6; Which is fun, but is it really useful? Definitely! Sometimes we don\u0026rsquo;t want to repeat the same argument and cannot overload the method (to simulate default parameter):\nString buildUrl(String protocol, String base) { return protocol + \u0026#34;://\u0026#34; + base; } //... Function\u0026lt;String, String\u0026gt; secureUrlFun = base -\u0026gt; buildUrl(\u0026#34;https\u0026#34;, base); Function\u0026lt;String, String\u0026gt; unsecureUrlFun = base -\u0026gt; buildUrl(\u0026#34;http\u0026#34;, base); assert secureUrlFun.apply(\u0026#34;adrian.md\u0026#34;).equals(\u0026#34;https://adrian.md\u0026#34;); assert unsecureUrlFun.apply(\u0026#34;adrian.md\u0026#34;).equals(\u0026#34;http://adrian.md\u0026#34;); Higher-order function Function\u0026lt;String, String\u0026gt; buildSafeUrl() { return base -\u0026gt; buildUrl(\u0026#34;https\u0026#34;, base); } In the previous example, buildUrl is also called first-order while buildSafeUrl - higher-order function. The definition of later one says that it should have at least one function as an argument or return a function. This opens a whole new world of possibilities, like lazy evaluation, code reuse, and function composition.\nLet\u0026rsquo;s imagine we have the following structure of records / classes:\nrecord Plug(String type) { } record Engine(Plug plug) { } record Car(Engine engine) { } And we are given the classic boring task of extracting type from a car object. The problem is that we might have a null at any level.\nA naive engineer could slap an Optional and call it a day:\nString plugType = Optional.of(new Car(null)) .map(Car::engine) .map(Engine::plug) .map(Plug::type) .orElse(null); assert plugType == null; Spoiler alert, it\u0026rsquo;s wrong to use Optional. The only valid usage of Optional is as a return value in a method as confirmed by API note from JavaDoc. Not to mention that we didn\u0026rsquo;t create disposable wrapper objects for null check before Java 8 and there is no reason whatsoever to do these days.\nWe can solve this task by creating a null safe (higher-order) function:\ninterface NullSafeFunction\u0026lt;T, R\u0026gt; extends Function\u0026lt;T, R\u0026gt; { default \u0026lt;V\u0026gt; NullSafeFunction\u0026lt;T, V\u0026gt; andThen(Function\u0026lt;? super R, ? extends V\u0026gt; after) { return (T t) -\u0026gt; { R result = apply(t); if(result != null) { return after.apply(result); } return null; }; } static \u0026lt;T\u0026gt; NullSafeFunction\u0026lt;T, T\u0026gt; identity() { return t -\u0026gt; t; } } //... String nullPlugType = NullSafeFunction.\u0026lt;Car\u0026gt;identity() .andThen(Car::engine) .andThen(Engine::plug) .andThen(Plug::type) .apply(new Car(null)); assert nullPlugType == null; String sparkPlugType = NullSafeFunction.\u0026lt;Car\u0026gt;identity() .andThen(Car::engine) .andThen(Engine::plug) .andThen(Plug::type) .apply(new Car(new Engine(new Plug(\u0026#34;spark plug\u0026#34;)))); assert sparkPlugType.equals(\u0026#34;spark plug\u0026#34;); Breaking down the example, we can see that NullSafeFunction::andThen returns a composed function that executes the caller first and then the argument.\nTo Be Continued \u0026hellip;\n","permalink":"https://adrian.md/2021/03/16/java-functional-programming-concepts/","summary":"\u003cp\u003eWith the rise of lambda expression and newer features, there is an increasing necessity to review some of the functional programming concepts and how are they applied in Java.\u003c/p\u003e\n\u003ch3 id=\"currying\"\u003eCurrying\u003c/h3\u003e\n\u003cp\u003eCurrying is the process of turning a function with multiple arguments into a function with fewer arguments. For example, we can turn an addition between three numbers into a single argument function:\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-java\" data-lang=\"java\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"n\"\u003eFunction\u003c/span\u003e\u003cspan class=\"o\"\u003e\u0026lt;\u003c/span\u003e\u003cspan class=\"n\"\u003eInteger\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eFunction\u003c/span\u003e\u003cspan class=\"o\"\u003e\u0026lt;\u003c/span\u003e\u003cspan class=\"n\"\u003eInteger\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eFunction\u003c/span\u003e\u003cspan class=\"o\"\u003e\u0026lt;\u003c/span\u003e\u003cspan class=\"n\"\u003eInteger\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eInteger\u003c/span\u003e\u003cspan class=\"o\"\u003e\u0026gt;\u0026gt;\u0026gt;\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eabc\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ea\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"o\"\u003e-\u0026gt;\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eb\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"o\"\u003e-\u0026gt;\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ec\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"o\"\u003e-\u0026gt;\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ea\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"o\"\u003e+\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eb\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"o\"\u003e+\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ec\u003c/span\u003e\u003cspan class=\"p\"\u003e;\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003eassert\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eabc\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"na\"\u003eapply\u003c/span\u003e\u003cspan class=\"p\"\u003e(\u003c/span\u003e\u003cspan class=\"n\"\u003e1\u003c/span\u003e\u003cspan class=\"p\"\u003e).\u003c/span\u003e\u003cspan class=\"na\"\u003eapply\u003c/span\u003e\u003cspan class=\"p\"\u003e(\u003c/span\u003e\u003cspan class=\"n\"\u003e2\u003c/span\u003e\u003cspan class=\"p\"\u003e).\u003c/span\u003e\u003cspan class=\"na\"\u003eapply\u003c/span\u003e\u003cspan class=\"p\"\u003e(\u003c/span\u003e\u003cspan class=\"n\"\u003e3\u003c/span\u003e\u003cspan class=\"p\"\u003e)\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"o\"\u003e==\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003e6\u003c/span\u003e\u003cspan class=\"p\"\u003e;\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eWhich is fun, but is it really useful? Definitely! Sometimes we don\u0026rsquo;t want to repeat the same argument and cannot overload the method (to simulate default parameter):\u003c/p\u003e","title":"Functional Programming Concepts in Java"},{"content":"In this article, we\u0026rsquo;ll explore what a sealed type in Java is, how to define a class and interface as sealed and finally we\u0026rsquo;ll go through a practical example.\nSealed class syntax To have explicit control over the extensibility of a class we use identifier sealed and then permits to specify the set of classes allowed to extend:\nsealed class Advice permits BeforeAdvice, Interceptor, AfterAdvice { } non-sealed class BeforeAdvice extends Advice { } final class Interceptor extends Advice { } sealed class AfterAdvice extends Advice { } final class AfterReturningAdvice extends AfterAdvice { } There are some basic rules to keep in mind:\nsubclasses are required to specify non-sealed if a class can be extended further, final or sealed permitted subclasses must directly extend the sealed class permits is optional if classes are found in the same source file permitted direct subclasses must reside in the same package if the superclass is in an unnamed module permitted direct subclasses can reside in different packages only when we have a named module, meaning we declare a module-info.java with appropriate content Advantages of using sealed class or interface Let\u0026rsquo;s talk first about exhaustiveness and why it might come in handy.\nIf you watch closely the evolution of OpenJDK, you probably saw a couple of releases ago switch expression and how it doesn\u0026rsquo;t need anymore a default case when dealing with enums:\nenum TrafficLight { RED, YELLOW, GREEN } String signal(TrafficLight trafficLight) { return switch (trafficLight) { case RED -\u0026gt; \u0026#34;stop\u0026#34;; case GREEN -\u0026gt; \u0026#34;go\u0026#34;; }; } The above code snippet when compiled throws the error message \u0026ldquo;switch expression does not cover all possible input values\u0026rdquo;, because the values of TrafficLight are known beforehand and the compiler detects that one case is not handled.\nWhen it comes to inheritance and pattern matching, a feature which is due sometime in the next releases, we\u0026rsquo;ll be able to get rid of traditional if-else chain and use a more elegant switch expression:\nswitch (advice) { case BeforeAdvice ba -\u0026gt; ba.before(); case Interceptor i -\u0026gt; i.invoke(); case AfterAdvice aa -\u0026gt; aa.after(); }; instead of\nif (advice instanceof BeforeAdvice ba) { ba.before(); } else if (advice instanceof Interceptor i) { i.invoke(); } else if (advice instanceof AfterAdvice aa) { aa.after(); } else { throw new IllegalStateException(\u0026#34;this is not possible\u0026#34;); } Next advantage is about restricting the use of a superclass or interface. Some people already struggled with similar problem in the past and came with rather wacky solutions (e.g. Do not inherit, please).\nIt\u0026rsquo;s especially useful when the API knows how to deal only with a set of predefined subclasses. Moreover, the developer doesn\u0026rsquo;t have to do defensive programming, as we saw in the previous example.\nRestrictions If an interface is declared as sealed we cannot use it as a lambda expression or create an anonymous class. Like final, sealed property and its list of permitted subtypes, are defined in the class file so that it can be enforced at runtime:\npublic sealed interface Period permits Hour, Day, Week, Month { void print(); public static void main(String[] args) { //error: incompatible types: Period is not a functional interface Period period1 = () -\u0026gt; System.out.println(\u0026#34;lambda period\u0026#34;); //error: local classes must not extend sealed classes Period period2 = new Period() { @Override public void print() { System.out.println(\u0026#34;anonymous class\u0026#34;); } }; } } Example Let\u0026rsquo;s suppose we want to iterate over a list using the well-known head-tail method. Of course, it can be implemented in various ways, but for the sake of example we\u0026rsquo;ll do it with the help of a sealed interface:\nimport java.util.List; public sealed interface Sequence\u0026lt;T\u0026gt; permits IterableOps, Nil { static \u0026lt;T\u0026gt; Sequence\u0026lt;T\u0026gt; of(T... values) { return new IterableOps\u0026lt;\u0026gt;(List.of(values)); } } We need Sequence to be sealed because, for this particular example, we\u0026rsquo;ll always deal with only two cases: when there are some elements left in the list and when there are none (Nil), and we don\u0026rsquo;t want someone to mess with this hierarchy by \u0026ldquo;accidentally\u0026rdquo; implementing the interface.\nNext, we define Nil which is a list of nothing.\npublic final class Nil implements Sequence { public static final Nil NIL = new Nil(); } Lastly, we define IterableOps class:\nimport java.util.Iterator; public final class IterableOps\u0026lt;T\u0026gt; implements Sequence\u0026lt;T\u0026gt; { private final Iterator\u0026lt;T\u0026gt; iterator; protected IterableOps(Iterable\u0026lt;T\u0026gt; iterable) { this.iterator = iterable.iterator(); } public T head() { return iterator.next(); } public Sequence\u0026lt;T\u0026gt; tail() { return iterator.hasNext() ? this : Nil.NIL; } } In main we\u0026rsquo;ll create a list of strings and use it in a for loop. Since pattern matching with switch is not yet available, will make use of the next best thing - enhanced instanceof (JEP-305). The stop condition is when we hit Nil:\npublic static void main(String[] args) { for(var seq = Sequence.of(\u0026#34;apples\u0026#34;, \u0026#34;oranges\u0026#34;, \u0026#34;grapes\u0026#34;); seq instanceof IterableOps\u0026lt;String\u0026gt; itOps; seq = itOps.tail()) { System.out.println(itOps.head()); } } It prints out\napples oranges grapes Conclusion Without a doubt, starting with Java 15 we\u0026rsquo;ll give more consideration to whatever a class should be open for extension or sealed upon creation. The decision relies on the purpose of the class, be it code reuse, modeling various types that exist in a domain, or defending the integrity of an API.\nBibliography OpenJDK. JEP 360: Sealed Classes (Preview) Java Language Specification. Version 15 Java 15 Final Release Specification Project Amber. Data Classes and Sealed Types for Java ","permalink":"https://adrian.md/2020/08/31/java-sealed-class/","summary":"\u003cp\u003eIn this article, we\u0026rsquo;ll explore what a sealed type in Java is, how to define a class and interface as sealed and finally we\u0026rsquo;ll go through a practical example.\u003c/p\u003e\n\u003ch3 id=\"sealed-class-syntax\"\u003eSealed class syntax\u003c/h3\u003e\n\u003cp\u003eTo have explicit control over the extensibility of a class we use identifier \u003cem\u003esealed\u003c/em\u003e and then \u003cem\u003epermits\u003c/em\u003e to specify the set of classes allowed to extend:\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-java\" data-lang=\"java\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"kd\"\u003esealed\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003eclass\u003c/span\u003e \u003cspan class=\"nc\"\u003eAdvice\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003epermits\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eBeforeAdvice\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eInterceptor\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eAfterAdvice\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"p\"\u003e{\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e}\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"kd\"\u003enon-sealed\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003eclass\u003c/span\u003e \u003cspan class=\"nc\"\u003eBeforeAdvice\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003eextends\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eAdvice\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"p\"\u003e{\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e}\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"kd\"\u003efinal\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003eclass\u003c/span\u003e \u003cspan class=\"nc\"\u003eInterceptor\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003eextends\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eAdvice\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"p\"\u003e{\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e}\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"kd\"\u003esealed\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003eclass\u003c/span\u003e \u003cspan class=\"nc\"\u003eAfterAdvice\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003eextends\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eAdvice\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"p\"\u003e{\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e}\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"kd\"\u003efinal\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003eclass\u003c/span\u003e \u003cspan class=\"nc\"\u003eAfterReturningAdvice\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"kd\"\u003eextends\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eAfterAdvice\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"p\"\u003e{\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e}\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003e\u003cimg alt=\"Sealed Advice Hierarchy Diagram\" loading=\"lazy\" src=\"/images/sealed-advice-diagram.png\"\u003e\u003c/p\u003e","title":"An Introduction to Java Sealed Classes and Interfaces"},{"content":"Greetings! I\u0026rsquo;m Adrian — an enthusiastic software engineer driven by the pursuit of clean code and elegant solutions. For those seeking to connect, feel free to reach out on Linkedin.\n","permalink":"https://adrian.md/about/","summary":"\u003cp\u003eGreetings! I\u0026rsquo;m Adrian — an enthusiastic software engineer driven by the pursuit of clean code and elegant solutions. For those seeking to connect, feel free to reach out on \u003ca href=\"https://www.linkedin.com/in/apulbere/\" target=\"_blank\" rel=\"noopener\"\u003eLinkedin\u003c/a\u003e.\u003c/p\u003e","title":"About"}]