<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
<title type="text">That Which Inspires Awe</title>
<generator uri="https://github.com/jekyll/jekyll">Jekyll</generator>
<link rel="self" type="application/atom+xml" href="https://blog.indrek.io/feed.xml" />
<link rel="alternate" type="text/html" href="https://blog.indrek.io" />
<updated>2026-10-31T15:23:54+00:00</updated>
<id>https://blog.indrek.io/</id>
<author>
  <name></name>
  <uri>https://blog.indrek.io/</uri>
  
</author>


<entry>
  <title type="html"><![CDATA[Dealing With LWLock:LockManager Wait Events in Aurora Postgres]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/dealing-with-lwlock-lockmanager-wait-events-in-aurora-postgres/" />
  <id>https://blog.indrek.io/articles/dealing-with-lwlock-lockmanager-wait-events-in-aurora-postgres</id>
  <updated>2024-12-02 15:40:57 +0000T00:00:00-00:00</updated>
  <published>2024-12-02T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;h2 id=&quot;lightweight-what&quot;&gt;Lightweight What?&lt;/h2&gt;

&lt;p&gt;In Postgres, lightweight locks, or &lt;em&gt;lwlocks&lt;/em&gt;, control access to datastructures in shared memory.
Unlike table or row locks, lightweight locks are usually held for a very short time and are not bound to the ongoing transaction.
As a database client, you don’t have direct control over when these locks are acquired.
They operate under the hood and are managed by Postgres itself.&lt;/p&gt;

&lt;p&gt;This post is going to explore Postgres’ lock manager, lwlocks, fast-path locking and how to combat &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LWLock:LockManager&lt;/code&gt; wait events.&lt;/p&gt;

&lt;h2 id=&quot;lwlocks-and-the-lock-manager&quot;&gt;LWLocks and the Lock Manager&lt;/h2&gt;

&lt;p&gt;Whenever you interact with a relation (a table or an index) in Postgres, the system acquires a lock on it.
These locks are often referred to as heavyweight locks.
It might seem counter-intuitive, but even read queries acquire locks that Postgres needs to keep track of.&lt;/p&gt;

&lt;p&gt;To accelerate lock acquisition, Postgres uses a mechanism called &lt;a href=&quot;https://github.com/postgres/postgres/blob/4766438aa317e85f3d762847b2b009f91f530b6f/src/backend/storage/lmgr/README#L257&quot;&gt;fast-path locking&lt;/a&gt;.
This technique is used in scenarios where “weak” relation locks are used (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AccessShareLock&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RowShareLock&lt;/code&gt;, or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RowExclusiveLock&lt;/code&gt;) and only when the system can quickly verify that no conflicting locks could possibly be
present.&lt;/p&gt;

&lt;p&gt;Each transaction is allowed to take &lt;a href=&quot;https://github.com/postgres/postgres/blob/8afff7d6db25ab52f155d8a220f692d7d6d84152/src/include/storage/proc.h#L86&quot;&gt;16 fast-path locks&lt;/a&gt;.&lt;/p&gt;

&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/*
 * We allow a small number of &quot;weak&quot; relation locks (AccessShareLock,
 * RowShareLock, RowExclusiveLock) to be recorded in the PGPROC structure
 * rather than the main lock table.  This eases contention on the lock
 * manager LWLocks.  See storage/lmgr/README for additional details.
 */&lt;/span&gt;
&lt;span class=&quot;cp&quot;&gt;#define		FP_LOCK_SLOTS_PER_BACKEND 16
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Once the limit is exceeded, further lock acquisitions have to go through the lock manager.
Depending on the type of workload, this can create lock acquisition contention and slow down your workload.&lt;/p&gt;

&lt;h2 id=&quot;lets-see-fast-path-in-action&quot;&gt;Let’s See Fast-Path in Action&lt;/h2&gt;

&lt;p&gt;To better understand fast-path, it helps to go through the motions and see it for yourself.
The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pg_locks&lt;/code&gt; view shows information about locks held by active processes.
The column &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fastpath&lt;/code&gt; will be set to true when the lock was taken via fast path.&lt;/p&gt;

&lt;p&gt;Let’s perform the following experiment.
In one database session, we’re going to start a transaction and then perform multiple select queries on different tables.
This way, we’re going to acquire a lock on each relation.
At the same time, let’s open up another database session and let’s observe the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pg_locks&lt;/code&gt; table.&lt;/p&gt;

&lt;p&gt;Start a new transaction and perform select statements.
For this scenario, I’ve created multiple empty tables.&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;begin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;select&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In the second database session, view &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pg_locks&lt;/code&gt;;&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;select&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;relation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;regclass&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;locktype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;mode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fastpath&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pg_locks&lt;/span&gt; 
&lt;span class=&quot;k&quot;&gt;where&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pid&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pg_backend_pid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;-- filter out the locks acquired by this query&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Pid 51 is the backend process from the first database session.
We can see two locks.
The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AccessShareLock&lt;/code&gt; is acquired by the select statement on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;test1&lt;/code&gt; table.
The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ExclusiveLock&lt;/code&gt;, on the other hand, is a lock on the virtual transaction ID.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; relation |  locktype  | pid |      mode       | fastpath 
----------+------------+-----+-----------------+----------
 test1    | relation   |  51 | AccessShareLock | t
          | virtualxid |  51 | ExclusiveLock   | t
(2 rows)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In the first database session, if we continue to perform additional select statements on relations we haven’t touched yet, we can see that the amount of locks acquired by pid 51 is going to grow.&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;-- in the first database session&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;select&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; relation |  locktype  | pid |      mode       | fastpath 
----------+------------+-----+-----------------+----------
 test2    | relation   |  51 | AccessShareLock | t
 test1    | relation   |  51 | AccessShareLock | t
          | virtualxid |  51 | ExclusiveLock   | t
(3 rows)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Fast path doesn’t apply only to select statements.
We can also &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;INSERT&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UPDATE&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DELETE&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;-- in the first database session&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;insert&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;into&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test1&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;id&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;values&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;&apos;hello&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;update&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;set&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;&apos;hello&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now we can see that two more relation locks have appeared.
The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RowExclusiveLocks&lt;/code&gt; are acquired when inserting, updating or when performing deletes.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; relation |   locktype    | pid |       mode       | fastpath 
----------+---------------+-----+------------------+----------
 test2    | relation      |  51 | AccessShareLock  | t
 test2    | relation      |  51 | RowExclusiveLock | t
 test1    | relation      |  51 | AccessShareLock  | t
 test1    | relation      |  51 | RowExclusiveLock | t
          | virtualxid    |  51 | ExclusiveLock    | t
          | transactionid |  51 | ExclusiveLock    | f
(6 rows)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Up to this point, all the operations have acquired fast path locks.
If we continue to acquire new locks on relations, we will eventually hit the limit of 16 fast-path locks per transaction.
Once the limit has been exceeded, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fastpath&lt;/code&gt; column will be set to false for any new lock.
Therefore, new lock acquisitions have to go through the lock manager.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; relation |   locktype    | pid |       mode       | fastpath 
----------+---------------+-----+------------------+----------
...
 test17   | relation      |  51 | AccessShareLock  | f
(21 rows)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;a-plethora-of-indices&quot;&gt;A Plethora of Indices&lt;/h2&gt;

&lt;p&gt;In the previous example, we focused on operations involving individual tables without any indexes.
However, in real-world scenarios, indexes play a critical role in everyday queries.
As a result, locks must be acquired on indexes as well.
To demonstrate this, let’s create a table with multiple indexes.&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;create&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;table&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;many_indexes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;id&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bigserial&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;primary&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;g&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;o&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Imagine that every column in this table is indexed.
Let’s perform a select on the table and see which locks get acquired.&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;begin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;select&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;many_indexes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;-- in another db session, let&apos;s run&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;select&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;relation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;regclass&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;locktype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;mode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fastpath&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pg_locks&lt;/span&gt; 
&lt;span class=&quot;k&quot;&gt;where&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pid&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pg_backend_pid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;     relation      |  locktype  | pid |      mode       | fastpath 
-------------------+------------+-----+-----------------+----------
 n_idx             | relation   |  51 | AccessShareLock | t
 m_idx             | relation   |  51 | AccessShareLock | t
 l_idx             | relation   |  51 | AccessShareLock | t
 k_idx             | relation   |  51 | AccessShareLock | t
 j_idx             | relation   |  51 | AccessShareLock | t
 i_idx             | relation   |  51 | AccessShareLock | t
 h_idx             | relation   |  51 | AccessShareLock | t
 g_idx             | relation   |  51 | AccessShareLock | t
 f_idx             | relation   |  51 | AccessShareLock | t
 e_idx             | relation   |  51 | AccessShareLock | t
 d_idx             | relation   |  51 | AccessShareLock | t
 c_idx             | relation   |  51 | AccessShareLock | t
 b_idx             | relation   |  51 | AccessShareLock | t
 a_idx             | relation   |  51 | AccessShareLock | t
 many_indexes_pkey | relation   |  51 | AccessShareLock | t
 many_indexes      | relation   |  51 | AccessShareLock | t
                   | virtualxid |  51 | ExclusiveLock   | t
 p_idx             | relation   |  51 | AccessShareLock | f
 o_idx             | relation   |  51 | AccessShareLock | f
 q_idx             | relation   |  51 | AccessShareLock | f
(20 rows)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In addition to the table itself, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AccessShareLock&lt;/code&gt; is acquired on all indexes.
Notice that for a couple of indexes, fastpath is set to false.
With a query on a single table with a lot of indexes, we were able to reach the limit of 16 fast-path locks per transaction.&lt;/p&gt;

&lt;p&gt;So far, we’ve focused on selecting individual tables and observed that indexes also count toward the fast-path lock limit.
However, in relational databases, a common access pattern involves joining multiple tables.
During a join operation, locks are acquired on every relation involved—this includes all tables and their associated indexes.&lt;/p&gt;

&lt;h2 id=&quot;lockmanager&quot;&gt;LockManager&lt;/h2&gt;

&lt;p&gt;When fast-path cannot be used, locks need to be recorded in a &lt;a href=&quot;https://github.com/postgres/postgres/blob/master/src/backend/storage/lmgr/lock.c&quot;&gt;shared memory hash table&lt;/a&gt;.
In Postgres, the hash table &lt;a href=&quot;https://github.com/postgres/postgres/blob/4766438aa317e85f3d762847b2b009f91f530b6f/src/include/storage/lwlock.h#L96-L97&quot;&gt;is divided into 16 partitions&lt;/a&gt;.&lt;/p&gt;

&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/* Number of partitions the shared lock tables are divided into */&lt;/span&gt;
&lt;span class=&quot;cp&quot;&gt;#define LOG2_NUM_LOCK_PARTITIONS  4
#define NUM_LOCK_PARTITIONS  (1 &amp;lt;&amp;lt; LOG2_NUM_LOCK_PARTITIONS)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This allows for greater concurrency.
Only the partition where the acquired lock falls into needs to be locked and not the entire hash table.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
	&lt;a href=&quot;https://blog.indrek.io/images/2024-12-02-dealing-with-lwlock-lockmanager-wait-events-in-aurora-postgres/hash-table.png&quot; class=&quot;image-popup&quot;&gt;&lt;img src=&quot;https://blog.indrek.io/images/2024-12-02-dealing-with-lwlock-lockmanager-wait-events-in-aurora-postgres/hash-table.png&quot; alt=&quot;Diagram displaying the lock manager hash that&apos;s divided into 16 partitions&quot; /&gt;&lt;/a&gt;
	&lt;figcaption&gt;Lock manager&apos;s hash table is divided into 16 partitions to improve concurrency&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;However, in high traffic databases with frequent non-fast-path lock acquisitions, even the 16 partitions can become a bottleneck.
This is exactly what the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LWLock:LockManager&lt;/code&gt; wait event indicates: a process is attempting to access a partition in the shared hash table but cannot proceed because the partition is already locked.&lt;/p&gt;

&lt;h2 id=&quot;summon-lwlocklockmanager-wait-event&quot;&gt;Summon &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LWLock:LockManager&lt;/code&gt; Wait Event&lt;/h2&gt;

&lt;p&gt;Now that we have a basic overview of the lock manager and fast-path locking, let’s perform another experiment.
Let’s create a scenario where we can see &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LWLock:LockManager&lt;/code&gt; wait events in action.&lt;/p&gt;

&lt;p&gt;For this scenario, I’ve created an Aurora Postgres 15 instance and an EC2 instance that’s acting as a database client.
I used fairly large instance sizes (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;c5.12xlarge&lt;/code&gt; for the EC2 instance and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;db.r6i.4xlarge&lt;/code&gt; for Aurora Postgres).
My goal is to run many concurrent threads and process a large amount of database queries in parallel.
Since &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LWLock:LockManager&lt;/code&gt; wait event is a sign of lock manager contention, I’m hoping that a high amount of parallelism makes it easier to reproduce the issue.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
	&lt;a href=&quot;https://blog.indrek.io/images/2024-12-02-dealing-with-lwlock-lockmanager-wait-events-in-aurora-postgres/scenario.png&quot; class=&quot;image-popup&quot;&gt;&lt;img src=&quot;https://blog.indrek.io/images/2024-12-02-dealing-with-lwlock-lockmanager-wait-events-in-aurora-postgres/scenario.png&quot; alt=&quot;Architecture diagram showing pgbench running on an EC2 instance and it&apos;s making queries to an Aurora Postgres 15 database&quot; /&gt;&lt;/a&gt;
	&lt;figcaption&gt;Test scenario setup. EC2 instance running pgbench will execute sql queries against an Aurora Postgres database.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;The database contains 20 tables, appropriately named &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;test1&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;test2&lt;/code&gt;, and so on up to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;test20&lt;/code&gt;.
For the purposes of this test, the table schema is not important.
All tables are empty.&lt;/p&gt;

&lt;p&gt;We’re going to use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pgbench&lt;/code&gt; to run the following SQL script.&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;begin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;select&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;select&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;...&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;select&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;commit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;It performs a transaction during which all tables get selected.
We learned previously that we have 16 fast-path locks per transaction.
Acquiring more than 16 locks should cause a situation where some locks have to be acquired via the lock manager.&lt;/p&gt;

&lt;p&gt;During the test, pgbench will run for 240 seconds, creating 40 threads and 800 database connections.
These threads will repeatedly run the SQL script, simulating a high-concurrency workload.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;pgbench -f test.sql -T 240 -c 800 -j 40 -U postgres \
  -h database-2-instance-1.cky0tsfnwec5.eu-central-1.rds.amazonaws.com postgres
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Looking at RDS Performance Insights after the experiment, we can clearly see the presence of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LWLock:LockManager&lt;/code&gt; wait events.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
	&lt;a href=&quot;https://blog.indrek.io/images/2024-12-02-dealing-with-lwlock-lockmanager-wait-events-in-aurora-postgres/test_results.png&quot; class=&quot;image-popup&quot;&gt;&lt;img src=&quot;https://blog.indrek.io/images/2024-12-02-dealing-with-lwlock-lockmanager-wait-events-in-aurora-postgres/test_results.png&quot; alt=&quot;A diagram from RDS Performance Insights. It depicts a graph where CPU time is spent. Some time is spent on LWLock:LockManager wait events&quot; /&gt;&lt;/a&gt;
	&lt;figcaption&gt;LWLock:LockManager wait events depicted in purple. Max vCPUs equals 16.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;To make sure our understanding of fast-path locking and lock manager is correct, let’s reduce the number of select statements in the test script to below 16.&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;begin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;select&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;select&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;...&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;select&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;commit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This should ensures that fast-path locking is always used.
When rerunning the test, my expectation is that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LWLock:LockManager&lt;/code&gt; wait events should disappear because lock manager isn’t used anymore to keep track of lock acquisitions.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
	&lt;a href=&quot;https://blog.indrek.io/images/2024-12-02-dealing-with-lwlock-lockmanager-wait-events-in-aurora-postgres/test_with_fast_path_locking.png&quot; class=&quot;image-popup&quot;&gt;&lt;img src=&quot;https://blog.indrek.io/images/2024-12-02-dealing-with-lwlock-lockmanager-wait-events-in-aurora-postgres/test_with_fast_path_locking.png&quot; alt=&quot;A diagram from RDS Performance Insights. It depicts a graph where CPU time is spent. Some time is spent on LWLock:LockManager wait events&quot; /&gt;&lt;/a&gt;
	&lt;figcaption&gt;No more LWLockManager wait events when only fast-path locking is used&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;As expected, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LWLock:LockManager&lt;/code&gt; wait events have disappeared.&lt;/p&gt;

&lt;h2 id=&quot;how-might-this-happen-in-production-systems&quot;&gt;How Might This Happen in Production Systems&lt;/h2&gt;

&lt;p&gt;If your application suddenly experiences &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LWLock:LockManager&lt;/code&gt; wait events that slow it down, it’s a good idea to review recent changes in the application code.
Perhaps a frequently executed code path has been modified, causing it to acquire a additional locks.
While a few extra locks might not sound dangerous at first, if a frequently executed transaction starts to acquire more non-fast-path locks, this could put pressure on the lock manager and create contention.&lt;/p&gt;

&lt;p&gt;A common strategy in Postgres is to partition a large table by time periods.
For instance, an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;orders&lt;/code&gt; table might be divided into monthly segments.
A partition in Postgres is essentially a separate table with its own indexes.
As a result, queries that have to scan multiple partitions are also going to acquire more locks and &lt;a href=&quot;https://www.kylehailey.com/post/postgres-partition-pains-lockmanager-waits&quot;&gt;this can lead to LockManager wait events&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;LockManager wait events can also be triggered by a sudden surge in traffic.
An application might have a steady baseline of non-fast-path lock acquisitions that don’t cause any problems.
But when the incoming traffic increases, LockManager can suddenly reach a limit and noticeable wait events start to appear.&lt;/p&gt;

&lt;h2 id=&quot;how-to-deal-with-lockmanager-wait-events&quot;&gt;How to Deal With LockManager Wait Events?&lt;/h2&gt;

&lt;p&gt;There’s no one-size-fits-all solution, as every workload is unique.
However, here are some strategies to consider:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Manage transaction scope&lt;/strong&gt;: As applications grow, the amount of work performed within a single transaction often increases. Consider whether some transactions can be simplified or reduced in scope to minimize locking contention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Monitor ORM behavior&lt;/strong&gt;: Object-Relational Mapping (ORM) libraries may over-fetch data by joining multiple tables unnecessarily. Review query patterns generated by your ORM and optimize where possible.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Optimize table partitioning&lt;/strong&gt;: If using table partitioning, carefully manage the size and number of partitions. Ensure that your queries use the partition key to avoid scanning multiple partitions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Implement client-side caching&lt;/strong&gt;: Caching query results on the client side can reduce the need for repeated database queries and lock acquisition, lowering the chances of LockManager wait events.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use reader instances&lt;/strong&gt;: Distributing query load across multiple reader instances reduces the per-instance LockManager load.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Review your indexes&lt;/strong&gt;: Periodically review your indexes and remove any that are unused to reduce unnecessary locking overhead.&lt;/li&gt;
&lt;/ul&gt;


  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/dealing-with-lwlock-lockmanager-wait-events-in-aurora-postgres/&quot;&gt;Dealing With LWLock:LockManager Wait Events in Aurora Postgres&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on December 02, 2024.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[How to Safely Alter a Busy Table in Postgres]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/how-to-safely-alter-a-busy-table-in-postgres/" />
  <id>https://blog.indrek.io/articles/how-to-safely-alter-a-busy-table-in-postgres</id>
  <updated>2024-10-13 23:17:18 +0000T00:00:00-00:00</updated>
  <published>2024-10-13T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;As you introduce new features to your application, you will almost certainly need to evolve your database schema.
However, in Postgres, there are a couple of things you need to understand before you start issuing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ALTER TABLE&lt;/code&gt; commands if you want to avoid bringing your application to a grinding halt.&lt;/p&gt;

&lt;h2 id=&quot;table-locks&quot;&gt;Table Locks&lt;/h2&gt;

&lt;p&gt;Postgres provides &lt;a href=&quot;https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-TABLES&quot;&gt;various modes for locking a table&lt;/a&gt;.
When it comes to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ALTER TABLE&lt;/code&gt; command, it acquires the strongest table lock available: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AccessExclusiveLock&lt;/code&gt;.
This lock ensures that the holder is the only transaction accessing the table in any way.
No other transaction is allowed to read from or write to the table while the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ALTER TABLE&lt;/code&gt; operation is executing.&lt;/p&gt;

&lt;p&gt;For tables with low traffic, this usually isn’t a problem.
A simple addition of a column is typically very fast and it doesn’t hinder the application’s performance.
However, things get more complicated when you need to alter a table that receives a lot of concurrent transactions.
To better understand the problem, let’s look at the following example scenario.&lt;/p&gt;

&lt;h2 id=&quot;example&quot;&gt;Example&lt;/h2&gt;

&lt;p&gt;The following simulates a query that an application might issue.
It starts a transaction and queries for accounts.
A select query acquires an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AccessShareLock&lt;/code&gt; on the table.
Notice that the transaction isn’t immediately committed.
This simulates a scenario where the application might be doing some work before committing the transaction.&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;begin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;select&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;accounts&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Next, in another database session, let’s simulate a schema migration.&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;alter&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;table&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;accounts&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;add&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;column&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;age&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;When the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ALTER TABLE&lt;/code&gt; command is issued, you’ll see that the statement never finishes.
This is because the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ALTER TABLE&lt;/code&gt; transaction tries to acquire an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AccessExclusiveLock&lt;/code&gt; on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;accounts&lt;/code&gt; table but is unable to do so because there’s an existing read transaction on the table.
As mentioned earlier, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AccessExclusiveLock&lt;/code&gt; guarantees that the holder of the lock is the only transaction working on the table.
This also means that when there are existing locks on the table, the transaction has to wait until all existing locks on the table are released.&lt;/p&gt;

&lt;p&gt;In this scenario, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;accounts&lt;/code&gt; table receives a lot of transactions.
In a new database session, let’s simulate another query from the application.&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;select&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;accounts&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Once we execute this query, we immediately notice that it doesn’t return anything.
The query just hangs.
It tries to acquire an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AccessShareLock&lt;/code&gt; lock on the table but is unable to do so because of the transaction created in the previous step.&lt;/p&gt;

&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ALTER TABLE&lt;/code&gt; transaction isn’t able to proceed.
It joined a wait queue.
The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AccessShareLock&lt;/code&gt; required by the final select query is incompatible with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AccessExclusiveLock&lt;/code&gt;.
Therefore the final select query also has to join the wait queue.&lt;/p&gt;

&lt;figure&gt;
	&lt;a href=&quot;https://blog.indrek.io/images/2024-10-13-how-to-safely-alter-a-busy-table-in-postgres/diagram.png&quot; class=&quot;image-popup&quot;&gt;&lt;img src=&quot;https://blog.indrek.io/images/2024-10-13-how-to-safely-alter-a-busy-table-in-postgres/diagram.png&quot; alt=&quot;Diagram displaying the transactions in the wait queue&quot; /&gt;&lt;/a&gt;
	&lt;figcaption&gt;Alter table statement is blocked by the ongoing transaction. A select from the accounts table is blocked by the alter table statement.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;To sum up, in a busy table, it may be very difficult to acquire an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AccessExclusiveLock&lt;/code&gt; that’s required by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ALTER TABLE&lt;/code&gt; commands.
It’s surprisingly easy to accidentally bring your application to a grinding halt.
If the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ALTER TABLE&lt;/code&gt; transaction cannot acquire the lock immediately, you’re denying access to the table for everybody.&lt;/p&gt;

&lt;h2 id=&quot;how-to-not-mess-up&quot;&gt;How to Not Mess Up&lt;/h2&gt;

&lt;p&gt;An easy way to avoid accidental service disruptions is to define a &lt;a href=&quot;https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-LOCK-TIMEOUT&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lock_timeout&lt;/code&gt;&lt;/a&gt; for the database migration.
This ensures that Postgres will abort the statement if it waits longer than the specified amount of time while attempting to acquire a lock on a table.&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;begin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;set&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lock_timeout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;&apos;1s&apos;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;alter&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;table&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;accounts&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;add&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;column&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;age&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;commit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;If the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ALTER TABLE&lt;/code&gt; statement cannot acquire a lock on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;accounts&lt;/code&gt; table within one second, the statement is cancelled with the following error.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;ERROR:  canceling statement due to lock timeout
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The value of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lock_timeout&lt;/code&gt; should be set to something small.
Keep in mind, in the worst case scenario, this is how long you’re blocking all other transactions from accessing the table.&lt;/p&gt;

&lt;p&gt;With busy tables, however, you might find that you need to perform the migration multiple times until it executes successfully.
Therefore, if you can and your tooling supports it, it makes sense to retry the migration automatically several times.&lt;/p&gt;

&lt;p&gt;You might also want to consider when to perform the schema migration.
For example, your database might be processing fewer transactions during the night.
Performing the migration during low traffic periods increases the likelihood of success.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Most schema migration operations in Postgres acquire exclusive locks.
In databases that process a lot of transactions, acquiring the lock can take a significant amount of time.
If the lock isn’t acquired quickly, it can result in blocked transactions and even application downtime.
To avoid any negative outcomes, it’s strongly advised to configure a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lock_timeout&lt;/code&gt;.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/how-to-safely-alter-a-busy-table-in-postgres/&quot;&gt;How to Safely Alter a Busy Table in Postgres&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on October 13, 2024.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[Improve the Quality of Your Tests With Mutation Testing]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/improve-the-quality-of-your-tests-with-mutation-testing/" />
  <id>https://blog.indrek.io/articles/improve-the-quality-of-your-tests-with-mutation-testing</id>
  <updated>2024-04-012 12:05:18 +0200T00:00:00-00:00</updated>
  <published>2024-04-12T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;As software engineers, we write tests to ensure the correctness of our code.
By rerunning tests after each change, we can quickly identify if any modifications have inadvertently introduced new bugs or broken existing functionality.
The existing set of tests form a safety net that allows us to move faster with less risk of breaking things.
But how can we validate the quality of the tests themselves?
This post will explore the concept of mutation testing, a potential answer to that very question.&lt;/p&gt;

&lt;h2 id=&quot;what-is-mutation-testing&quot;&gt;What is Mutation Testing?&lt;/h2&gt;

&lt;p&gt;Imagine a scenario where you edit existing functionality but accidentally introduce a bug.
This can happen to any of us.
All is well and good if your tests start to fail.
A failing test means that the functionality is sufficiently covered with tests.
Your safety net prevented a potential issue.
However, if no tests fail after you introduce the bug, it may indicate that certain parts of the code are not being properly tested or that the tests themselves are inadequate.&lt;/p&gt;

&lt;p&gt;This is essentially the premise behind mutation testing.
&lt;strong&gt;Instead of you introducing bugs accidentally, a mutation testing tool will do that deliberately.&lt;/strong&gt;
A mutation testing tool introduces a change of behavior to the code.
Consider, for example, negating or removing a conditional, or returning &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; from a method call.
The altered version of the code is referred to as a &lt;em&gt;mutant&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Tests are executed after each mutation.
The mutant is &lt;em&gt;killed&lt;/em&gt; if at least one test fails, indicating that the tests discovered a noticable change in behavior.
If no tests fail, the mutant &lt;em&gt;has survived&lt;/em&gt;, suggesting there are gaps in our tests or we have tests that never fail.
However, in some cases, it can also mean that the code itself is meaningless and isn’t actually needed.&lt;/p&gt;

&lt;p&gt;We can draw a parallel to chaos engineering.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Chaos Engineering is the discipline of experimenting on a system in order to build confidence in the system’s capability to withstand turbulent conditions in production.&lt;/p&gt;
  &lt;footer&gt;&lt;a href=&quot;https://principlesofchaos.org/&quot;&gt;Principles of Chaos Engineering&lt;/a&gt;&lt;/footer&gt;
&lt;/blockquote&gt;

&lt;p&gt;Mutation testing, however, &lt;em&gt;experiments&lt;/em&gt; on our code and it’s goal is to introduce changes that make the tests fail.
This helps us to discover weaknesses in our test suite.&lt;/p&gt;

&lt;h2 id=&quot;show-me-the-code&quot;&gt;Show me the Code&lt;/h2&gt;

&lt;p&gt;Let’s have a look at an example scenario using &lt;a href=&quot;https://pitest.org/&quot;&gt;PIT&lt;/a&gt;, a mutation testing tool for Java.
The following is the method under test.
It calculates income tax using dual rates.
All income up to 10,000 is charged with 20% and everything above 10,000 is charged with 25%.
Ignore the fact that we’re dealing with money and we use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;double&lt;/code&gt;.
It’s just an example.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;IncomeTaxCalculator&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;INCOME_TAX_20&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;INCOME_TAX_25&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.25&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;INCOME_TAX_25_BRACKET&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;10_000.00&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;calculateIncomeTax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;income&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;incomeTax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.00&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;remainingTaxableIncome&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;income&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;income&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;INCOME_TAX_25_BRACKET&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;kt&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;incomeOver25PercentBracket&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;income&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;INCOME_TAX_25_BRACKET&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;incomeTax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;incomeOver25PercentBracket&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;INCOME_TAX_25&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;remainingTaxableIncome&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;incomeOver25PercentBracket&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;incomeTax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;remainingTaxableIncome&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;INCOME_TAX_20&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Let’s create our first test.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nd&quot;&gt;@Test&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;calculateTaxBracket20&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;assertEquals&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1600.00&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;IncomeTaxCalculator&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;calculateIncomeTax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8_000.00&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The following is the PIT mutation testing report.
It shows which mutations were applied and whether the mutants were killed or not.
It resembles a code coverage report.
We can clearly see that the if-branch of the code was never executed.&lt;/p&gt;

&lt;style&gt;
/* PIT report tables, themed for the blog */
.prose table.src {
  --pit-covered: rgba(140, 190, 110, 0.13);
  --pit-uncovered: rgba(235, 105, 85, 0.15);
  --pit-killed: rgba(140, 190, 110, 0.38);
  --pit-survived: rgba(235, 105, 85, 0.42);
  display: table;
  width: calc(100% + 3rem);
  margin-inline: -1.5rem;
  border-collapse: separate;
  border-spacing: 0;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: var(--bg-sunk);
  font-family: var(--font-code);
  font-size: 0.8125rem;
  line-height: 1.75;
  overflow: visible;
}
.prose table.src td {
  padding: 0;
  border: 0;
  vertical-align: top;
  white-space: nowrap;
}
.prose table.src tr:first-child td { padding-top: 0.875rem; }
.prose table.src tr:last-child td { padding-bottom: 0.875rem; }
.prose table.src tr &gt; td:first-child {
  width: 1%;
  padding-inline: 1.25rem 0.75rem;
  text-align: right;
  color: var(--muted);
  font-variant-numeric: tabular-nums;
  user-select: none;
}
.prose table.src tr &gt; td:first-child a { color: inherit; text-decoration: none; }
.prose table.src tr &gt; td:nth-child(2) {
  width: 1%;
  padding-inline: 0.25rem;
  text-align: center;
}
.prose table.src pre {
  margin: 0;
  padding: 0 1.25rem 0 0.75rem;
  border: 0;
  border-radius: 0;
  background: none;
  overflow: visible;
  font-size: inherit;
  line-height: inherit;
  color: var(--text);
}
.prose table.src pre span { background: none; }

/* Line coverage tints the whole row */
.prose table.src td.covered,
.prose table.src tr:has(&gt; td.covered) &gt; td { background: var(--pit-covered); }
.prose table.src td.uncovered,
.prose table.src tr:has(&gt; td.uncovered) &gt; td { background: var(--pit-uncovered); }
.prose table.src td.na { background: none; }

/* Mutation count pill */
.prose table.src .pop {
  position: relative;
  display: inline-block;
}
.prose table.src .pop &gt; a {
  display: inline-block;
  min-width: 1.6rem;
  padding: 0 0.4rem;
  border-radius: 999px;
  color: var(--text-strong);
  font-weight: 600;
  line-height: 1.4rem;
  text-decoration: none;
}
.prose table.src .pop &gt; a:empty { display: none; }
.prose table.src td.killed .pop &gt; a { background: var(--pit-killed); }
.prose table.src td.survived .pop &gt; a { background: var(--pit-survived); }

/* Mutation list popup */
.prose table.src .pop &gt; span {
  display: none;
  position: absolute;
  z-index: 10;
  top: calc(100% + 0.4rem);
  left: -0.5rem;
  width: 30rem;
  max-width: 80vw;
  padding: 0.875rem 1.125rem;
  border: 1px solid var(--line-strong);
  border-radius: var(--radius-sm);
  background: var(--bg-raised);
  box-shadow: var(--shadow);
  color: var(--text);
  font-family: var(--font-text);
  font-size: 0.875rem;
  line-height: 1.55;
  text-align: left;
  white-space: normal;
}
.prose table.src .pop:hover &gt; span,
.prose table.src .pop:focus-within &gt; span { display: block; }
.prose table.src .pop &gt; a:empty + span { display: none; }

/* Mutations list below the source */
.prose table.src tr:has(h2) &gt; td {
  padding-top: 1.25rem;
  border-top: 1px solid var(--line);
}
.prose table.src tr:nth-last-child(1 of :has(td.na, td.covered, td.uncovered)) &gt; td { padding-bottom: 0.875rem; }
.prose table.src h2 {
  margin: 0 0 0.5rem 0.75rem;
  font-size: 1.25rem;
  line-height: 1.3;
}
.prose table.src td &gt; a[name] { color: inherit; text-decoration: none; }
.prose table.src td p {
  display: flex;
  align-items: baseline;
  gap: 0.6rem;
  margin: 0 1.25rem 0 0.75rem;
  color: var(--text);
}
.prose table.src td p::before {
  content: &quot;&quot;;
  width: 0.5rem;
  height: 0.5rem;
  flex: none;
  border-radius: 50%;
  background: var(--muted);
  transform: translateY(-0.05em);
}
.prose table.src td p.KILLED::before { background: rgb(140, 190, 110); }
.prose table.src td p.SURVIVED::before,
.prose table.src td p.NO_COVERAGE::before { background: rgb(235, 105, 85); }
.prose table.src td p .pop { color: var(--muted); }

@media (max-width: 46em) {
  .prose table.src {
    display: block;
    width: auto;
    margin-inline: calc(-1 * var(--gutter));
    overflow-x: auto;
    border-radius: 0;
    border-inline: 0;
  }
}
&lt;/style&gt;

&lt;table class=&quot;src&quot;&gt;



&lt;tbody&gt;&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_1&quot;&gt;
1
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_1&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;package test.pit;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_2&quot;&gt;
2
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_2&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;uncovered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_3&quot;&gt;
3
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_3&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;uncovered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;class IncomeTaxCalculator {&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_4&quot;&gt;
4
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_4&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_5&quot;&gt;
5
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_5&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;    private static final double INCOME_TAX_20 = 0.2;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_6&quot;&gt;
6
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_6&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;    private static final double INCOME_TAX_25 = 0.25;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_7&quot;&gt;
7
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_7&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;    private static final double INCOME_TAX_25_BRACKET = 10_000.00;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_8&quot;&gt;
8
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_8&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_9&quot;&gt;
9
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_9&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;    public static double calculateIncomeTax(double income) {&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;covered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_10&quot;&gt;
10
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_10&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;covered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;        var incomeTax = 0.00;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;covered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_11&quot;&gt;
11
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_11&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;covered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;        var remainingTaxableIncome = income;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_12&quot;&gt;
12
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_12&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;covered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_13&quot;&gt;
13
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;survived&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_13&quot;&gt;2&lt;/a&gt;
&lt;span&gt;
1. calculateIncomeTax : changed conditional boundary → SURVIVED&lt;br /&gt;
2. calculateIncomeTax : negated conditional → KILLED&lt;br /&gt;

&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;covered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;survived&quot;&gt;        if (income &amp;gt; INCOME_TAX_25_BRACKET) {&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;uncovered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_14&quot;&gt;
14
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;survived&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_14&quot;&gt;1&lt;/a&gt;
&lt;span&gt;
1. calculateIncomeTax : Replaced double subtraction with addition → NO_COVERAGE&lt;br /&gt;

&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;uncovered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;survived&quot;&gt;            var incomeOver25PercentBracket = income - INCOME_TAX_25_BRACKET;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;uncovered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_15&quot;&gt;
15
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;survived&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_15&quot;&gt;2&lt;/a&gt;
&lt;span&gt;
1. calculateIncomeTax : Replaced double multiplication with division → NO_COVERAGE&lt;br /&gt;
2. calculateIncomeTax : Replaced double addition with subtraction → NO_COVERAGE&lt;br /&gt;

&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;uncovered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;survived&quot;&gt;            incomeTax += incomeOver25PercentBracket * INCOME_TAX_25;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;uncovered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_16&quot;&gt;
16
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;survived&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_16&quot;&gt;1&lt;/a&gt;
&lt;span&gt;
1. calculateIncomeTax : Replaced double subtraction with addition → NO_COVERAGE&lt;br /&gt;

&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;uncovered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;survived&quot;&gt;            remainingTaxableIncome -= incomeOver25PercentBracket;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_17&quot;&gt;
17
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_17&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;        }&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_18&quot;&gt;
18
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_18&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;covered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_19&quot;&gt;
19
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;killed&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_19&quot;&gt;3&lt;/a&gt;
&lt;span&gt;
1. calculateIncomeTax : replaced double return with 0.0d for test/pit/IncomeTaxCalculator::calculateIncomeTax → KILLED&lt;br /&gt;
2. calculateIncomeTax : Replaced double addition with subtraction → KILLED&lt;br /&gt;
3. calculateIncomeTax : Replaced double multiplication with division → KILLED&lt;br /&gt;

&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;covered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;killed&quot;&gt;        return incomeTax + (remainingTaxableIncome * INCOME_TAX_20);&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_20&quot;&gt;
20
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_20&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;    }&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@510da778_21&quot;&gt;
21
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@510da778_21&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;}&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;



&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;h2&gt;Mutations&lt;/h2&gt;&lt;/td&gt;&lt;/tr&gt;

&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;#org.pitest.mutationtest.report.html.SourceFile@510da778_13&quot;&gt;13&lt;/a&gt;&lt;/td&gt; 
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;

&lt;a name=&quot;grouporg.pitest.mutationtest.report.html.SourceFile@510da778_13&quot;&gt; 

&lt;p class=&quot;KILLED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;1.&lt;span&gt;&lt;b&gt;1&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;test.pit.IncomeTaxCalculatorTest.[engine:junit-jupiter]/[class:test.pit.IncomeTaxCalculatorTest]/[method:calculateTaxBracket20()]&lt;/span&gt;&lt;/span&gt; negated conditional → KILLED&lt;/p&gt; &lt;p class=&quot;SURVIVED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;2.&lt;span&gt;&lt;b&gt;2&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;none&lt;/span&gt;&lt;/span&gt; changed conditional boundary → SURVIVED&lt;/p&gt; 
&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;#org.pitest.mutationtest.report.html.SourceFile@510da778_14&quot;&gt;14&lt;/a&gt;&lt;/td&gt; 
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;

&lt;a name=&quot;grouporg.pitest.mutationtest.report.html.SourceFile@510da778_14&quot;&gt; 

&lt;p class=&quot;NO_COVERAGE&quot;&gt;&lt;span class=&quot;pop&quot;&gt;1.&lt;span&gt;&lt;b&gt;1&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;none&lt;/span&gt;&lt;/span&gt; Replaced double subtraction with addition → NO_COVERAGE&lt;/p&gt; 
&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;#org.pitest.mutationtest.report.html.SourceFile@510da778_15&quot;&gt;15&lt;/a&gt;&lt;/td&gt; 
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;

&lt;a name=&quot;grouporg.pitest.mutationtest.report.html.SourceFile@510da778_15&quot;&gt; 

&lt;p class=&quot;NO_COVERAGE&quot;&gt;&lt;span class=&quot;pop&quot;&gt;1.&lt;span&gt;&lt;b&gt;1&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;none&lt;/span&gt;&lt;/span&gt; Replaced double multiplication with division → NO_COVERAGE&lt;/p&gt; &lt;p class=&quot;NO_COVERAGE&quot;&gt;&lt;span class=&quot;pop&quot;&gt;2.&lt;span&gt;&lt;b&gt;2&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;none&lt;/span&gt;&lt;/span&gt; Replaced double addition with subtraction → NO_COVERAGE&lt;/p&gt; 
&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;#org.pitest.mutationtest.report.html.SourceFile@510da778_16&quot;&gt;16&lt;/a&gt;&lt;/td&gt; 
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;

&lt;a name=&quot;grouporg.pitest.mutationtest.report.html.SourceFile@510da778_16&quot;&gt; 

&lt;p class=&quot;NO_COVERAGE&quot;&gt;&lt;span class=&quot;pop&quot;&gt;1.&lt;span&gt;&lt;b&gt;1&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;none&lt;/span&gt;&lt;/span&gt; Replaced double subtraction with addition → NO_COVERAGE&lt;/p&gt; 
&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;#org.pitest.mutationtest.report.html.SourceFile@510da778_19&quot;&gt;19&lt;/a&gt;&lt;/td&gt; 
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;

&lt;a name=&quot;grouporg.pitest.mutationtest.report.html.SourceFile@510da778_19&quot;&gt; 

&lt;p class=&quot;KILLED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;1.&lt;span&gt;&lt;b&gt;1&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;test.pit.IncomeTaxCalculatorTest.[engine:junit-jupiter]/[class:test.pit.IncomeTaxCalculatorTest]/[method:calculateTaxBracket20()]&lt;/span&gt;&lt;/span&gt; replaced double return with 0.0d for test/pit/IncomeTaxCalculator::calculateIncomeTax → KILLED&lt;/p&gt; &lt;p class=&quot;KILLED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;2.&lt;span&gt;&lt;b&gt;2&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;test.pit.IncomeTaxCalculatorTest.[engine:junit-jupiter]/[class:test.pit.IncomeTaxCalculatorTest]/[method:calculateTaxBracket20()]&lt;/span&gt;&lt;/span&gt; Replaced double addition with subtraction → KILLED&lt;/p&gt; &lt;p class=&quot;KILLED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;3.&lt;span&gt;&lt;b&gt;3&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;test.pit.IncomeTaxCalculatorTest.[engine:junit-jupiter]/[class:test.pit.IncomeTaxCalculatorTest]/[method:calculateTaxBracket20()]&lt;/span&gt;&lt;/span&gt; Replaced double multiplication with division → KILLED&lt;/p&gt; 
&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;

&lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;To kill the mutants from the if-branch, we need to add couple more tests.
Let’s add a test where the income is greater than 10,000 and let’s also test the boundary condition.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nd&quot;&gt;@Test&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;calculateTaxBracket25&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;assertEquals&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4500.00&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;IncomeTaxCalculator&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;calculateIncomeTax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;20_000.00&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;nd&quot;&gt;@Test&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;calculateTaxExactlyAtBracket&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;assertEquals&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2000.00&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;IncomeTaxCalculator&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;calculateIncomeTax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;10_000.00&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The report looks better now, but not perfect.&lt;/p&gt;

&lt;table class=&quot;src&quot;&gt;



&lt;tbody&gt;&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_1&quot;&gt;
1
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_1&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;package test.pit;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_2&quot;&gt;
2
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_2&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;uncovered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_3&quot;&gt;
3
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_3&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;uncovered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;class IncomeTaxCalculator {&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_4&quot;&gt;
4
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_4&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_5&quot;&gt;
5
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_5&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;    private static final double INCOME_TAX_20 = 0.2;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_6&quot;&gt;
6
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_6&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;    private static final double INCOME_TAX_25 = 0.25;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_7&quot;&gt;
7
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_7&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;    private static final double INCOME_TAX_25_BRACKET = 10_000.00;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_8&quot;&gt;
8
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_8&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_9&quot;&gt;
9
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_9&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;    public static double calculateIncomeTax(double income) {&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;covered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_10&quot;&gt;
10
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_10&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;covered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;        var incomeTax = 0.00;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;covered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_11&quot;&gt;
11
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_11&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;covered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;        var remainingTaxableIncome = income;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_12&quot;&gt;
12
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_12&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;covered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_13&quot;&gt;
13
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;survived&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_13&quot;&gt;2&lt;/a&gt;
&lt;span&gt;
1. calculateIncomeTax : changed conditional boundary → SURVIVED&lt;br /&gt;
2. calculateIncomeTax : negated conditional → KILLED&lt;br /&gt;

&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;covered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;survived&quot;&gt;        if (income &amp;gt; INCOME_TAX_25_BRACKET) {&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;covered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_14&quot;&gt;
14
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;killed&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_14&quot;&gt;1&lt;/a&gt;
&lt;span&gt;
1. calculateIncomeTax : Replaced double subtraction with addition → KILLED&lt;br /&gt;

&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;covered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;killed&quot;&gt;            var incomeOver25PercentBracket = income - INCOME_TAX_25_BRACKET;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;covered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_15&quot;&gt;
15
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;killed&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_15&quot;&gt;2&lt;/a&gt;
&lt;span&gt;
1. calculateIncomeTax : Replaced double multiplication with division → KILLED&lt;br /&gt;
2. calculateIncomeTax : Replaced double addition with subtraction → KILLED&lt;br /&gt;

&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;covered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;killed&quot;&gt;            incomeTax += incomeOver25PercentBracket * INCOME_TAX_25;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;covered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_16&quot;&gt;
16
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;killed&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_16&quot;&gt;1&lt;/a&gt;
&lt;span&gt;
1. calculateIncomeTax : Replaced double subtraction with addition → KILLED&lt;br /&gt;

&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;covered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;killed&quot;&gt;            remainingTaxableIncome -= incomeOver25PercentBracket;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_17&quot;&gt;
17
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_17&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;        }&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_18&quot;&gt;
18
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_18&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;covered&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_19&quot;&gt;
19
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;killed&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_19&quot;&gt;3&lt;/a&gt;
&lt;span&gt;
1. calculateIncomeTax : replaced double return with 0.0d for test/pit/IncomeTaxCalculator::calculateIncomeTax → KILLED&lt;br /&gt;
2. calculateIncomeTax : Replaced double addition with subtraction → KILLED&lt;br /&gt;
3. calculateIncomeTax : Replaced double multiplication with division → KILLED&lt;br /&gt;

&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;covered&quot;&gt;&lt;pre&gt;&lt;span class=&quot;killed&quot;&gt;        return incomeTax + (remainingTaxableIncome * INCOME_TAX_20);&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_20&quot;&gt;
20
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_20&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;    }&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;


&lt;tr&gt;
&lt;td class=&quot;na&quot;&gt;
&lt;a name=&quot;org.pitest.mutationtest.report.html.SourceFile@2fac80a8_21&quot;&gt;
21
&lt;/a&gt;&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;
&lt;span class=&quot;pop&quot;&gt;
&lt;a href=&quot;#grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_21&quot;&gt;&lt;/a&gt;
&lt;span&gt;
&lt;/span&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;td class=&quot;&quot;&gt;&lt;pre&gt;&lt;span class=&quot;&quot;&gt;}&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;



&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;h2&gt;Mutations&lt;/h2&gt;&lt;/td&gt;&lt;/tr&gt;

&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;#org.pitest.mutationtest.report.html.SourceFile@2fac80a8_13&quot;&gt;13&lt;/a&gt;&lt;/td&gt; 
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;

&lt;a name=&quot;grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_13&quot;&gt; 

&lt;p class=&quot;KILLED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;1.&lt;span&gt;&lt;b&gt;1&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;test.pit.IncomeTaxCalculatorTest.[engine:junit-jupiter]/[class:test.pit.IncomeTaxCalculatorTest]/[method:calculateTaxBracket25()]&lt;/span&gt;&lt;/span&gt; negated conditional → KILLED&lt;/p&gt; &lt;p class=&quot;SURVIVED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;2.&lt;span&gt;&lt;b&gt;2&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;none&lt;/span&gt;&lt;/span&gt; changed conditional boundary → SURVIVED&lt;/p&gt; 
&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;#org.pitest.mutationtest.report.html.SourceFile@2fac80a8_14&quot;&gt;14&lt;/a&gt;&lt;/td&gt; 
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;

&lt;a name=&quot;grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_14&quot;&gt; 

&lt;p class=&quot;KILLED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;1.&lt;span&gt;&lt;b&gt;1&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;test.pit.IncomeTaxCalculatorTest.[engine:junit-jupiter]/[class:test.pit.IncomeTaxCalculatorTest]/[method:calculateTaxBracket25()]&lt;/span&gt;&lt;/span&gt; Replaced double subtraction with addition → KILLED&lt;/p&gt; 
&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;#org.pitest.mutationtest.report.html.SourceFile@2fac80a8_15&quot;&gt;15&lt;/a&gt;&lt;/td&gt; 
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;

&lt;a name=&quot;grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_15&quot;&gt; 

&lt;p class=&quot;KILLED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;1.&lt;span&gt;&lt;b&gt;1&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;test.pit.IncomeTaxCalculatorTest.[engine:junit-jupiter]/[class:test.pit.IncomeTaxCalculatorTest]/[method:calculateTaxBracket25()]&lt;/span&gt;&lt;/span&gt; Replaced double multiplication with division → KILLED&lt;/p&gt; &lt;p class=&quot;KILLED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;2.&lt;span&gt;&lt;b&gt;2&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;test.pit.IncomeTaxCalculatorTest.[engine:junit-jupiter]/[class:test.pit.IncomeTaxCalculatorTest]/[method:calculateTaxBracket25()]&lt;/span&gt;&lt;/span&gt; Replaced double addition with subtraction → KILLED&lt;/p&gt; 
&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;#org.pitest.mutationtest.report.html.SourceFile@2fac80a8_16&quot;&gt;16&lt;/a&gt;&lt;/td&gt; 
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;

&lt;a name=&quot;grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_16&quot;&gt; 

&lt;p class=&quot;KILLED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;1.&lt;span&gt;&lt;b&gt;1&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;test.pit.IncomeTaxCalculatorTest.[engine:junit-jupiter]/[class:test.pit.IncomeTaxCalculatorTest]/[method:calculateTaxBracket25()]&lt;/span&gt;&lt;/span&gt; Replaced double subtraction with addition → KILLED&lt;/p&gt; 
&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;#org.pitest.mutationtest.report.html.SourceFile@2fac80a8_19&quot;&gt;19&lt;/a&gt;&lt;/td&gt; 
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;

&lt;a name=&quot;grouporg.pitest.mutationtest.report.html.SourceFile@2fac80a8_19&quot;&gt; 

&lt;p class=&quot;KILLED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;1.&lt;span&gt;&lt;b&gt;1&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;test.pit.IncomeTaxCalculatorTest.[engine:junit-jupiter]/[class:test.pit.IncomeTaxCalculatorTest]/[method:calculateTaxBracket25()]&lt;/span&gt;&lt;/span&gt; replaced double return with 0.0d for test/pit/IncomeTaxCalculator::calculateIncomeTax → KILLED&lt;/p&gt; &lt;p class=&quot;KILLED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;2.&lt;span&gt;&lt;b&gt;2&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;test.pit.IncomeTaxCalculatorTest.[engine:junit-jupiter]/[class:test.pit.IncomeTaxCalculatorTest]/[method:calculateTaxBracket25()]&lt;/span&gt;&lt;/span&gt; Replaced double addition with subtraction → KILLED&lt;/p&gt; &lt;p class=&quot;KILLED&quot;&gt;&lt;span class=&quot;pop&quot;&gt;3.&lt;span&gt;&lt;b&gt;3&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Location : &lt;/b&gt;calculateIncomeTax&lt;br /&gt;&lt;b&gt;Killed by : &lt;/b&gt;test.pit.IncomeTaxCalculatorTest.[engine:junit-jupiter]/[class:test.pit.IncomeTaxCalculatorTest]/[method:calculateTaxBracket25()]&lt;/span&gt;&lt;/span&gt; Replaced double multiplication with division → KILLED&lt;/p&gt; 
&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;

&lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;There’s still a surviving &lt;em&gt;conditional boundary&lt;/em&gt; mutant on line number 13.
In this case, the mutatation changes the condition to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;income &amp;gt;= INCOME_TAX_25_BRACKET&lt;/code&gt; but it has no effect on the outcome of the tests.
According to mutation testing rules, this is a potential gap in the tests but if we read the code, we can see that it cannot affect the end result because 25% tax is charged on everything that’s above 10,000.
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;income - INCOME_TAX_25_BRACKET&lt;/code&gt; evaluates 0 when &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;income&lt;/code&gt; is 10,000.&lt;/p&gt;

&lt;p&gt;Sometimes, mutation testing can produce results where you, the author, have to evaluate whether it’s significant.
It could be that the code under test is not needed or the code could be rewritten.
For example, in our case we could remove the if-sentence altogether and get a 100% green mutation test result with the following implementation.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;calculateIncomeTax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;income&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;incomeTax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.00&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;remainingTaxableIncome&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;income&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;kt&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;incomeOver25PercentBracket&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Math&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;income&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;INCOME_TAX_25_BRACKET&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;incomeTax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;incomeOver25PercentBracket&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;INCOME_TAX_25&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;remainingTaxableIncome&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;incomeOver25PercentBracket&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;incomeTax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;remainingTaxableIncome&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;INCOME_TAX_20&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Use common sense.
Mutation testing cannot evaluate the readability or the performance of the code.
Arguably, having the if-sentence present makes it very clear that 25% tax is applied to everything above 10,000.
Additionally, the new implementation performs unnecessary work when &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;income &amp;lt;= 10_000&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;code-coverage-anybody&quot;&gt;Code Coverage Anybody?&lt;/h2&gt;

&lt;p&gt;When we try to understand the quality of our test suite, discussions often lead to measuring code coverage.
At first glance, there’s a similarity between mutation testing and code coverage, especially when we look at the red and green lines of code in the mutation testing report.&lt;/p&gt;

&lt;p&gt;Code coverage tells you which lines of code were executed during a test.
Technically, you can get 100% line coverage with a single test but that doesn’t guarantee the test executed all possible code paths.
You need to specifically measure branch coverage if you’re interested in all the possible decision points in the code.
What’s more, you can get 100% line coverage even if you don’t assert anything.
Therefore, measuring code coverage alone cannot protect you against poorly maintained tests.
But that doesn’t mean code coverage is a completely useless metric though.
You need to understand what you’re measuring.&lt;/p&gt;

&lt;h2 id=&quot;is-mutation-testing-the-end-all-be-all&quot;&gt;Is Mutation Testing the end-all be-all?&lt;/h2&gt;

&lt;p&gt;Mutation testing is an interesting way to discover gaps in our tests and a tool we can include into our toolbox.
However, like any tool, it comes with its own set of challenges.
Even on a relatively small codebase, the number of generated mutations can grow very high.
Now imagine a scenario where the entire test suite takes a minute to finish, and there are 1000 mutations.
Mutation testing would take approximataely 17 hours to finish.&lt;/p&gt;

&lt;p&gt;Of course, there are optimisations that can be done:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;limiting the number of mutations generated for each run&lt;/li&gt;
  &lt;li&gt;limiting the types of mutations included into each run&lt;/li&gt;
  &lt;li&gt;excluding tests&lt;/li&gt;
  &lt;li&gt;excluding code under test&lt;/li&gt;
  &lt;li&gt;PIT has an &lt;a href=&quot;https://pitest.org/quickstart/incremental_analysis/&quot;&gt;incremental analysis feature&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Due to the scalability issues, mutation testing is probably not something you want to run on your CI/CD pipeline on every commit.
Instead, consider running it on a schedule automatically or you could run it locally on a smaller scale, only on the source files you’re working with.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Mutation testing is a method for testing the quality of the tests.
It works by making small changes, or &lt;em&gt;mutations&lt;/em&gt;, in your code to see if your tests can find the errors.
At first glance, it’s similar to measuring code coverage, which tells you how much of your code is tested, but mutation testing also checks how well your tests work.
These two methods are different and complement each other.
Remember, the aim isn’t to kill all mutants but to make your tests better.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/improve-the-quality-of-your-tests-with-mutation-testing/&quot;&gt;Improve the Quality of Your Tests With Mutation Testing&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on April 12, 2024.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[Accessing EC2 Instances with AWS SSM]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/access-ec2-instance-with-aws-ssm/" />
  <id>https://blog.indrek.io/articles/access-ec2-instance-with-aws-ssm</id>
  <updated>2024-04-07 12:05:18 +0200T00:00:00-00:00</updated>
  <published>2024-04-07T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;The traditional way of accessing servers is to use SSH.
This, however, comes with configuration overhead.
First of all, the server has to be accessible over the network.
You need to carve out a path for SSH to work.
This can bring extra challenges, especially in an environment where you want to keep the server in a private network.
Secondly, you’re faced with the overhead of managing SSH keys.
This post will show you how to use AWS Systems Mananger (SSM) to start a remote session to an EC2 instance, eliminating the need to configure SSH.&lt;/p&gt;

&lt;h2 id=&quot;iam-instance-profile&quot;&gt;IAM Instance Profile&lt;/h2&gt;

&lt;p&gt;To be able to start an SSM session to an EC2 instance, Systems Manger needs to have access to your instances.
We can do that with IAM roles.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Go to the IAM Console and create a new Role&lt;/li&gt;
  &lt;li&gt;For the trusted entity type, select &lt;strong&gt;“AWS service”&lt;/strong&gt; and select EC2 for the use case&lt;/li&gt;
  &lt;li&gt;When configuring permissions, select the AWS managed &lt;strong&gt;“AmazonSSMManagedInstanceCore”&lt;/strong&gt; policy&lt;/li&gt;
  &lt;li&gt;Finally, give the role a name, say, &lt;strong&gt;“SSMAccess”&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;create-aws-ec2-instance&quot;&gt;Create AWS EC2 Instance&lt;/h2&gt;

&lt;p&gt;When you launch a new EC2 instance, don’t forget attach the &lt;strong&gt;SSMAccess&lt;/strong&gt; IAM instance profile.&lt;/p&gt;

&lt;p class=&quot;notice--warning&quot;&gt;
&lt;strong&gt;Keep in mind&lt;/strong&gt; that the EC2 instance needs to have the SSM agent installed. &lt;a href=&quot;https://docs.aws.amazon.com/systems-manager/latest/userguide/ami-preinstalled-agent.html&quot;&gt;It&apos;s preinstalled on some Amazon Machine Images (AMIs) provided by AWS&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;And that’s it.
The newly launched EC2 instance should be accessible once it’s fired up.
However, if you wish to access an EC2 instance that doesn’t have a public IP or doesn’t have a route to the &lt;a href=&quot;https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html&quot;&gt;Internet Gateway&lt;/a&gt;, additional configuration is required.&lt;/p&gt;

&lt;h2 id=&quot;configure-access-to-private-ec2-instances&quot;&gt;Configure Access to Private EC2 Instances&lt;/h2&gt;

&lt;p&gt;We need to create VPC endpoints to be able to access private EC2 instances via SSM.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Go to the VPC console and select Endpoints&lt;/li&gt;
  &lt;li&gt;Create a new Endpoint and give it a name&lt;/li&gt;
  &lt;li&gt;Select AWS services from the service category&lt;/li&gt;
  &lt;li&gt;Select the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;com.amazonaws.[region].ssm&lt;/code&gt; service&lt;/li&gt;
  &lt;li&gt;Select your VPC and associate the endpoint with the subnets you’re using&lt;/li&gt;
  &lt;li&gt;In security groups, you need to select a security group that allows outbound HTTPS (port 443) traffic to Systems Manager endpoints. Create one if it doesn’t already exist. Keep in mind that this is the same security group that should be associated with the EC2 instance.&lt;/li&gt;
  &lt;li&gt;Finally, create the endpoint&lt;/li&gt;
  &lt;li&gt;Repeat the steps to create another endpoint, but this time select the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;com.amazonaws.[region].ec2messages&lt;/code&gt; service&lt;/li&gt;
  &lt;li&gt;Repeat the steps again to create an additional endpoint, but this time select the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;com.amazonaws.[region].ssmmessages&lt;/code&gt; service&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;start-session-via-awscli&quot;&gt;Start Session via &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;awscli&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;awscli&lt;/code&gt; can be used to start a session with the EC2 instance.
Before you do so, make sure you have &lt;a href=&quot;https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html&quot;&gt;installed the Session Manager plugin for AWS CLI&lt;/a&gt;.
Once that’s done, you should be good to go.&lt;/p&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;aws ssm start-session &lt;span class=&quot;nt&quot;&gt;--target&lt;/span&gt; &amp;lt;ec2-instance-id&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;If everything is configured correctly, you should have a newly established terinal session to your EC2 instance.&lt;/p&gt;

&lt;p&gt;Alternatively, you can also start a session using the AWS EC2 console.
Select the EC2 instance and click the “Connect” option.
Select “Session Manager” and click “Connect” again.
This will open a terminal session in your browser.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/access-ec2-instance-with-aws-ssm/&quot;&gt;Accessing EC2 Instances with AWS SSM&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on April 07, 2024.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[What's inside the Nginx Ingress Controller?]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/whats-inside-the-nginx-ingress-controller/" />
  <id>https://blog.indrek.io/articles/whats-inside-the-nginx-ingress-controller</id>
  <updated>2024-03-15 12:05:18 +0200T00:00:00-00:00</updated>
  <published>2024-03-03T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;When working with applications in Kubernetes, there’s a high chance that you’ve come across the &lt;a href=&quot;https://github.com/kubernetes/ingress-nginx&quot;&gt;Nginx Ingress Controller&lt;/a&gt;.
But what exactly makes it &lt;em&gt;Nginx&lt;/em&gt;?
From the application developer’s perspective, we usually don’t think about the implementation of the Ingress Controller.
We use the Ingress API to define the virtual host and declare routes to services.
In this post, we’ll explore the inner workings of the Nginx Ingress Controller and show you that it’s essentially an Nginx reverse proxy running in a container.&lt;/p&gt;

&lt;h2 id=&quot;where-can-i-find-nginx&quot;&gt;Where Can I Find Nginx?&lt;/h2&gt;

&lt;p&gt;To answer the question, let’s take out our trusty old &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kubectl&lt;/code&gt; and pry open an Nginx Ingress Controller.&lt;/p&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nv&quot;&gt;$ &lt;/span&gt;kubectl get pods &lt;span class=&quot;nt&quot;&gt;-n&lt;/span&gt; ingress-nginx

NAME                                        READY   STATUS      RESTARTS   AGE
ingress-nginx-controller-7dcdbcff84-bf6sn   1/1     Running     0          40s
ingress-nginx-controller-7dcdbcff84-mvkkj   1/1     Running     0          2m12s
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Let’s exec into a pod and explore.&lt;/p&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nv&quot;&gt;$ &lt;/span&gt;kubectl &lt;span class=&quot;nb&quot;&gt;exec&lt;/span&gt; &lt;span class=&quot;nt&quot;&gt;--stdin&lt;/span&gt; &lt;span class=&quot;nt&quot;&gt;--tty&lt;/span&gt; &lt;span class=&quot;nt&quot;&gt;-n&lt;/span&gt; ingress-nginx ingress-nginx-controller-7dcdbcff84-bf6sn &lt;span class=&quot;nt&quot;&gt;--&lt;/span&gt; /bin/bash
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;At &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/etc/nginx&lt;/code&gt; we can find a file called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nginx.conf&lt;/code&gt;.
The file name should be familiar if you’ve ever set up an Nginx reverse proxy.
This is the main configuration file for the Nginx web server.&lt;/p&gt;

&lt;p&gt;The default configuration file is pretty dense.
Feel free to look inside but in the context of this post the details of the configuration aren’t relevant.
The following is a rough outline.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;http {
  
    # Server configuration
    server {
        listen 80;
        server_name localhost;
        location / {
        }
    }

    server {
        location / {
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;http&lt;/code&gt; block configures the HTTP server&lt;/li&gt;
  &lt;li&gt;Each &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;server&lt;/code&gt; block represents a virtual server that listens for HTTP requests on a specific host name and port&lt;/li&gt;
  &lt;li&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;location&lt;/code&gt; block is used to define how the server should handle different URLs within a given server block&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the grand scheme of things, the configuration’s structure is fairly similar to the ingress resource rules where we define hosts and paths. 
Let’s dig deeper and see what happens when we create a new ingress.&lt;/p&gt;

&lt;h2 id=&quot;create-a-new-ingress&quot;&gt;Create a New Ingress&lt;/h2&gt;

&lt;p&gt;To better understand how the Nginx Ingress works, let’s create a new ingress.
The following configuration creates a Kubernetes deployment, service and an ingress for &lt;a href=&quot;https://github.com/jmalloc/echo-server&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;echo-server&lt;/code&gt;&lt;/a&gt;, a simple HTTP server that echoes the information about the incoming HTTP request back to the client.&lt;/p&gt;
&lt;div class=&quot;language-yaml highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;na&quot;&gt;apiVersion&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;apps/v1&lt;/span&gt;
&lt;span class=&quot;na&quot;&gt;kind&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;Deployment&lt;/span&gt;
&lt;span class=&quot;na&quot;&gt;metadata&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;echo-server&lt;/span&gt;
&lt;span class=&quot;na&quot;&gt;spec&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;replicas&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;m&quot;&gt;3&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;selector&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;na&quot;&gt;matchLabels&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
      &lt;span class=&quot;na&quot;&gt;app&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;echo-server&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;template&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;na&quot;&gt;metadata&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
      &lt;span class=&quot;na&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;na&quot;&gt;app&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;echo-server&lt;/span&gt;
    &lt;span class=&quot;na&quot;&gt;spec&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
      &lt;span class=&quot;na&quot;&gt;containers&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;pi&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;echo-server&lt;/span&gt;
          &lt;span class=&quot;na&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;jmalloc/echo-server&lt;/span&gt;
          &lt;span class=&quot;na&quot;&gt;ports&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;pi&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;http-port&lt;/span&gt;
              &lt;span class=&quot;na&quot;&gt;containerPort&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;m&quot;&gt;8080&lt;/span&gt;
&lt;span class=&quot;nn&quot;&gt;---&lt;/span&gt;
&lt;span class=&quot;na&quot;&gt;apiVersion&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;v1&lt;/span&gt;
&lt;span class=&quot;na&quot;&gt;kind&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;Service&lt;/span&gt;
&lt;span class=&quot;na&quot;&gt;metadata&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;echo-service&lt;/span&gt;
&lt;span class=&quot;na&quot;&gt;spec&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;ports&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;pi&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;http-port&lt;/span&gt;
      &lt;span class=&quot;na&quot;&gt;port&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;m&quot;&gt;80&lt;/span&gt;
      &lt;span class=&quot;na&quot;&gt;targetPort&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;http-port&lt;/span&gt;
      &lt;span class=&quot;na&quot;&gt;protocol&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;TCP&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;selector&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;na&quot;&gt;app&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;echo-server&lt;/span&gt;
&lt;span class=&quot;nn&quot;&gt;---&lt;/span&gt;
&lt;span class=&quot;na&quot;&gt;apiVersion&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;networking.k8s.io/v1&lt;/span&gt;
&lt;span class=&quot;na&quot;&gt;kind&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;Ingress&lt;/span&gt;
&lt;span class=&quot;na&quot;&gt;metadata&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;echo-ingress&lt;/span&gt;
&lt;span class=&quot;na&quot;&gt;spec&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;ingressClassName&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;nginx&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;rules&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;pi&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;host&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;foo.com&lt;/span&gt;
      &lt;span class=&quot;na&quot;&gt;http&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;na&quot;&gt;paths&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;pi&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;
          &lt;span class=&quot;na&quot;&gt;pathType&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;Prefix&lt;/span&gt;
          &lt;span class=&quot;na&quot;&gt;backend&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;na&quot;&gt;service&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
              &lt;span class=&quot;na&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;echo-service&lt;/span&gt;
              &lt;span class=&quot;na&quot;&gt;port&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;na&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;http-port&lt;/span&gt;
        &lt;span class=&quot;pi&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;/bar&lt;/span&gt;
          &lt;span class=&quot;na&quot;&gt;pathType&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;Prefix&lt;/span&gt;
          &lt;span class=&quot;na&quot;&gt;backend&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;na&quot;&gt;service&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
              &lt;span class=&quot;na&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;echo-service&lt;/span&gt;
              &lt;span class=&quot;na&quot;&gt;port&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;na&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;pi&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;http-port&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Have a look at the ingress configuration.
Take note of the host &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foo.com&lt;/code&gt; and the two paths.&lt;/p&gt;

&lt;p&gt;Assuming the entire configuration is in a file named &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;echo-server.yml&lt;/code&gt;, let’s create the Kubernetes resources using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kubectl&lt;/code&gt;.&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ kubectl apply -f echo-server.yml
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;When we now look at the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nginx.conf&lt;/code&gt; file, a new server block has appeared for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foo.com&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;## start server foo.com
server {
	server_name foo.com ;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foo.com&lt;/code&gt; server block has three location blocks defined.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;location /bar/ {
  ...

location = /bar {
  ...

location / {
  ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Based on this observation, we can conclude that whenever the state of the objects in the Kubernetes cluster changes, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nginx.conf&lt;/code&gt; file is updated accordingly.&lt;/p&gt;

&lt;h2 id=&quot;proxy-upstream&quot;&gt;Proxy Upstream&lt;/h2&gt;

&lt;p&gt;In the context of a Kubernetes ingress, Nginx acts as a reverse proxy.
It accepts HTTP connections and proxies them to upstream backends, which in our case are pods.
Let’s look at the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nginx.conf&lt;/code&gt; again and see where the upstream backends are defined.&lt;/p&gt;

&lt;p&gt;In the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foo.com&lt;/code&gt; server location blocks, we can see the following.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;proxy_pass http://upstream_balancer;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And if we look at the upstream block, it’s defined as follows.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;upstream upstream_balancer {
	server 0.0.0.1:1234; # placeholder
	
	balancer_by_lua_block {
		tcp_udp_balancer.balance()
	}
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Usually, when defining Nginx upstream servers manually, we list all the servers in the upstream block.
However, Nginx Ingress Controller doesn’t do that.
If it did, the configuration would have to be reloaded every time a pod is added or removed.
Instead, it uses the &lt;a href=&quot;https://github.com/openresty/lua-nginx-module&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lua-nginx-module&lt;/code&gt;&lt;/a&gt; to update the upstream configuration.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;In a relatively big cluster with frequently deploying apps this feature [lua-nginx-module] saves significant number of Nginx reloads which can otherwise affect response latency, load balancing quality (after every reload Nginx resets the state of load balancing) and so on.&lt;/p&gt;

  &lt;footer&gt;&lt;a href=&quot;https://kubernetes.github.io/ingress-nginx/how-it-works/#avoiding-reloads-on-endpoints-changes&quot;&gt;Avoiding reloads on Endpoints changes &amp;mdash; Nginx Ingress Controller Documentation&lt;/a&gt;&lt;/footer&gt;
&lt;/blockquote&gt;

&lt;p&gt;The Nginx Ingress Controller has a binary called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dbg&lt;/code&gt; in the root directory which we can use to list the current upstream backends.&lt;/p&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nv&quot;&gt;$ &lt;/span&gt;/dbg backends all
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The command will output a JSON array containing all currently configured backends.
In our case, the one we’re interested in is the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;echo-service&lt;/code&gt;.
The following output is considerably truncated.
In reality, the array has more entries and the objects have more attributes that aren’t significant in the context of this post.&lt;/p&gt;

&lt;div class=&quot;language-json highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;default-echo-service-http-port&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;endpoints&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;address&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;10.244.1.60&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;port&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;8080&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;address&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;10.244.0.129&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;port&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;8080&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;address&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;10.244.0.69&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;port&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;8080&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The list of endpoints in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dbg&lt;/code&gt; output matches the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;echo-service&lt;/code&gt; k8s endpoints.&lt;/p&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nv&quot;&gt;$ &lt;/span&gt;kubectl get endpoints echo-service
NAME           ENDPOINTS                                             AGE
echo-service   10.244.0.129:8080,10.244.0.69:8080,10.244.1.60:8080   15m
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Essentially, these are the IP addreses of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;echo-service&lt;/code&gt; pods.&lt;/p&gt;

&lt;h2 id=&quot;how-nginxconf-gets-updated&quot;&gt;How &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nginx.conf&lt;/code&gt; Gets Updated&lt;/h2&gt;

&lt;p&gt;In addition to the Nginx binary, the Nginx Ingress Controller container has a process called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nginx-ingress-controller&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nv&quot;&gt;$ &lt;/span&gt;ps &lt;span class=&quot;nt&quot;&gt;-a&lt;/span&gt;
PID   USER     TIME  COMMAND
    1 www-data  0:00 /usr/bin/dumb-init &lt;span class=&quot;nt&quot;&gt;--&lt;/span&gt; /nginx-ingress-controller &lt;span class=&quot;nt&quot;&gt;--publish-service&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;ingress-nginx/ingress-nginx-controller &lt;span class=&quot;nt&quot;&gt;--election-id&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;ingress-nginx-leader &lt;span class=&quot;nt&quot;&gt;--controller-class&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;k8s.io/ingress-nginx &lt;span class=&quot;nt&quot;&gt;--ingress-cla&lt;/span&gt;
    7 www-data  0:00 /nginx-ingress-controller &lt;span class=&quot;nt&quot;&gt;--publish-service&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;ingress-nginx/ingress-nginx-controller &lt;span class=&quot;nt&quot;&gt;--election-id&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;ingress-nginx-leader &lt;span class=&quot;nt&quot;&gt;--controller-class&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;k8s.io/ingress-nginx &lt;span class=&quot;nt&quot;&gt;--ingress-class&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;nginx &lt;span class=&quot;nt&quot;&gt;--configmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;i
   19 www-data  0:00 nginx: master process /usr/bin/nginx &lt;span class=&quot;nt&quot;&gt;-c&lt;/span&gt; /etc/nginx/nginx.conf
   25 www-data  0:00 nginx: worker process
   26 www-data  0:00 nginx: cache manager process
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;It’s a &lt;a href=&quot;https://kubernetes.io/docs/concepts/architecture/controller/&quot;&gt;Kubernetes controller&lt;/a&gt; that talks to the Kubernetes API server and &lt;a href=&quot;https://kubernetes.github.io/ingress-nginx/how-it-works/#nginx-model&quot;&gt;watches for changes in the state of the cluster&lt;/a&gt;.
If Kubernetes resources such as Ingresses, Services, Endpoints, Secrets or Configmaps are updated, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nginx-ingress-controller&lt;/code&gt; will update the Nginx configuration file and reload the configuration if needed.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;In the book &lt;a href=&quot;https://www.oreilly.com/library/view/fundamentals-of-software/9781663728357/&quot;&gt;Fundamentals of Software Architecture&lt;/a&gt;, the authors defined the first law of software architecture: &lt;em&gt;“Everything in software architecture is a trade-off”&lt;/em&gt;.
To be able to assess the trade-offs properly, it’s good to have a deeper understanding of the components we’re working with and not treat them as black boxes.
Knowing how things work under the hood is a superpower.&lt;/p&gt;

&lt;p&gt;When it comes to the Nginx Ingress Controller, we’ve learned that it’s essentially an Nginx reverse proxy running in a container with some extra functionality that keeps the configuration in sync with the state of the Kubernetes cluster.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/whats-inside-the-nginx-ingress-controller/&quot;&gt;What's inside the Nginx Ingress Controller?&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on March 03, 2024.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[The Three Ways of DevOps]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/3-ways-of-devops/" />
  <id>https://blog.indrek.io/articles/3-ways-of-devops</id>
  <updated>2020-07-13 18:56:18 +0300T00:00:00-00:00</updated>
  <published>2020-06-14T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;If you ask three people to describe DevOps, you’ll get four different answers.
Sometimes, developers doing operations work is branded as DevOps.
Others say it’s about the automation of infrastructure and deployments.
Occasionally, you can see that DevOps is a modern title for sysadmins.
We can see that the term has a &lt;em&gt;buzzword&lt;/em&gt; status.
So what’s the truth then?
What is DevOps?
In this post, I’ll try to shed some light on the meaning by summarizing the three core principles of DevOps—&lt;em&gt;the three ways&lt;/em&gt;—according to &lt;a href=&quot;https://amzn.to/3bAWtC0&quot;&gt;&lt;em&gt;The DevOps Handbook&lt;/em&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;1-principles-of-flow&quot;&gt;1. Principles of Flow&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;The First Way&lt;/em&gt; of DevOps is about creating a smooth flow of work through the different functional areas in an organization, from gathering requirements to operating software in production.
Emphasis is put on the global goals of the entire system, not on the local objectives of individual departments.
To make the concept more clear, let’s have a look at a couple of key takeaways.&lt;/p&gt;

&lt;h3 id=&quot;11-reduce-batch-size&quot;&gt;1.1 Reduce Batch Size&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Work-in-progress (WIP)&lt;/em&gt; is the amount of work that has been started but is not yet completed.
&lt;a href=&quot;https://medium.com/@Adrien_Liard/why-you-should-limit-work-in-progress-and-stop-multitasking-ba7ecd4670f&quot; title=&quot;Why you should limit work in progress and stop multitasking&quot;&gt;A high amount of WIP is a sign of multitasking&lt;/a&gt; and can hinder the flow of work.
To constrain WIP, we should reduce batch sizes.
The idea originates from &lt;a href=&quot;https://en.wikipedia.org/wiki/Lean_manufacturing&quot; title=&quot;Lean manufacturing&quot;&gt;Lean Manufacturing&lt;/a&gt;.
It was common in manufacturing to produce components in large batches.
Setting up new machinery and switching between jobs was costly and time-consuming.
Therefore, it was considered practical to create as many parts as possible once machinery had been set up.&lt;/p&gt;

&lt;p&gt;For example, a car production plant would produce a lot of body panels to reduce the number of changeovers.
This, however, creates a large amount of WIP.
&lt;a href=&quot;https://guillermo-roman.com/my-holiday-card-pipeline-a-visual-representation-of-the-effects-of-work-in-progress/&quot; title=&quot;A Visual Representation of the Effects of Work In Progress&quot;&gt;The variability in the flow of work cascades through the entire manufacturing plant, resulting in longer lead times&lt;/a&gt;.
Imagine what would happen if a flaw was found in the body panels when a car was being assembled?
Most likely, the entire batch has to be discarded and reproduced.
Producing large batches delays feedback, and in case of errors, more work has to be redone.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2020-04-01-3-ways-of-devops/car_assembly.jpg&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Cars being assembled in an assembly line. &lt;a href=&quot;https://unsplash.com/photos/QMjCzOGeglA&quot;&gt;Image by Carlos Aranda.&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;The same ideas apply to software development.
However, instead of machinery and body panels, we’re dealing with code.
Every commit into version control increases the batch size in the &lt;a href=&quot;https://www.atlassian.com/continuous-delivery/principles/value-stream-mapping&quot;&gt;software development value stream&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;The batch size is the unit at which work-products move between stages in a development process.&lt;/p&gt;
  &lt;footer&gt;&lt;strong&gt;Eric Ries&lt;/strong&gt; &amp;mdash; &lt;a href=&quot;http://www.startuplessonslearned.com/2009/02/work-in-small-batches.html&quot;&gt;StartUp Lessons Learned&lt;/a&gt;&lt;/footer&gt;
&lt;/blockquote&gt;

&lt;p&gt;A classic example is an annual production deployment schedule.
If a deployment is done once a year, the batch size is enormous; a year’s worth being is deployed in a single step.
Similarly to the car plant, if anything goes wrong, the entire batch has to be rolled back.
Extra effort must then be put into redoing work that was considered done.
And to add insult to injury, it’s challenging to find and fix the issues that caused the deployment to fail if introduced, say, 6 months ago.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2020-04-01-3-ways-of-devops/large-batch.png&quot; alt=&quot;Diagram depicting time on the x-axis and number of changes on the y-axis. The more time passes, the larger the batch size.&quot; /&gt;
  &lt;figcaption&gt;Large batch size, lots of changes over time. &lt;a href=&quot;https://www.slideshare.net/jallspaw/ops-metametrics-the-currency-you-pay-for-change-4608108&quot;&gt;Ops Meta-Metrics by John Allspaw&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Similar issues can be seen when long-lived &lt;a href=&quot;https://martinfowler.com/bliki/FeatureBranch.html&quot;&gt;feature branches&lt;/a&gt; are used.
The longer a branch stays isolated and the more changes it sees, the larger the batch size.
Over time, it becomes increasingly difficult to integrate it back to the mainline.
The potential for merge conflicts is high.
Since feedback is delayed, the potential for rework is high.
These factors are disruptive to the flow of work and increase deployment lead times.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2020-04-01-3-ways-of-devops/small-batch.png&quot; alt=&quot;Diagram depicting time on the x-axis and number of changes on the y-axis. Doing deployments more frequently means that each each deployment contains a smaller amount of changes.&quot; /&gt;
  &lt;figcaption&gt;Smaller batch size, fewer changes over time. &lt;a href=&quot;https://www.slideshare.net/jallspaw/ops-metametrics-the-currency-you-pay-for-change-4608108&quot;&gt;Ops Meta-Metrics by John Allspaw&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;To improve deployment lead times, we have to make batch sizes smaller.
Long-lived feature branches are discouraged.
We can get faster feedback if we integrated early and often and deployed software in smaller increments.
If we continue to reduce the batch size, we eventually arrive at a &lt;a href=&quot;https://dzone.com/articles/pattern-of-the-month-single-piece-flow&quot; title=&quot;Pattern of the Month: Single Piece Flow&quot;&gt;&lt;em&gt;single piece flow&lt;/em&gt;&lt;/a&gt;, where every commit flows through the entire software development value stream.
Once all automated checks have passed, changes end up in production.&lt;/p&gt;

&lt;p&gt;Teams that can pull that off make use of practices such as &lt;a href=&quot;https://trunkbaseddevelopment.com/&quot;&gt;trunk-based development&lt;/a&gt;, &lt;a href=&quot;https://martinfowler.com/articles/continuousIntegration.html&quot;&gt;continuous integration&lt;/a&gt;, &lt;a href=&quot;https://martinfowler.com/bliki/ContinuousDelivery.html&quot;&gt;continuous delivery&lt;/a&gt;, and &lt;a href=&quot;https://en.wikipedia.org/wiki/Continuous_deployment&quot;&gt;continuous deployment&lt;/a&gt;.
They’ve invested in test automation and have designed their software for low-risk releases.
They’ve also organized themselves so that the number of required hand-offs is minimized.
Hand-offs require communication and coordination.
Unfortunately, even under the best circumstances, some knowledge gets lost.
This is a potential spot where errors can creep in, and work can pile up, disrupting the flow and increasing deployment lead times.&lt;/p&gt;

&lt;h3 id=&quot;12-eliminate-constraints&quot;&gt;1.2 Eliminate Constraints&lt;/h3&gt;

&lt;p&gt;Continually identifying and eliminating constraints in our work is the key to improving throughput and reducing lead times.
In &lt;a href=&quot;https://amzn.to/2yDMvRD&quot;&gt;Beyond the Goal: Theory of Constraints&lt;/a&gt;, the author Dr. Goldratt states&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;In any value stream, there is always a direction of flow, and there is always one and only one constraint; any improvement not made at that constraint is an illusion.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;An example from a technology value stream is &lt;em&gt;environment creation&lt;/em&gt;.
If it takes hours to set up a testing environment, any improvements we do to work that happens before it in a value stream is an illusion.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2020-04-01-3-ways-of-devops/value-stream.png&quot; alt=&quot;Image of a deployment pipeline with three steps: build, create test environment and run integration tests. The step of creating a test environment takes considerably more time that the others (2 hours). Build and integration testing step take 10 and 15 minutes respectively.&quot; /&gt;
&lt;/figure&gt;

&lt;p&gt;For instance, if we reduce our build time from 10 to 3 minutes, we get faster builds.
But nothing gets done faster overall.
Environment creation is still a blocker.
What’s worse, WIP is increased.
New builds pile up even more quickly now, waiting to be deployed to the test environment.
Since environment creation blocks new work from passing through, steps that should happen after are starved of work.
We should find the constraint in our value stream, eliminate it, and then find the next one.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2020-04-01-3-ways-of-devops/dam.jpg&quot; alt=&quot;Hoover Dam&quot; /&gt;
  &lt;figcaption&gt;A constraint is like a dam. It blocks work from passing through, collecting it up upstream. Downstream, on the other hand, is starved of work. &lt;a href=&quot;https://unsplash.com/photos/Ul-1-YbuyX4&quot;&gt;Image by Cédric Dhaenens&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h2 id=&quot;2-principles-of-feedback&quot;&gt;2. Principles of Feedback&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;The second way&lt;/em&gt; of DevOps is about creating fast feedback loops that allow us to build safer systems.
Whether you like it or not, software is complicated.
Even the smallest of changes can have catastrophic consequences.
Without fast feedback, we distance the cause and effect.
Errors can slip in undetected, only to be discovered later when the cost and effort to fix them is higher.&lt;/p&gt;

&lt;h3 id=&quot;21-importance-of-fast-feedback&quot;&gt;2.1 Importance of Fast Feedback&lt;/h3&gt;

&lt;p&gt;Ideally, we’d like to see problems as they occur.
If you’ve written any code in an IDE or a text editor that points out issues as you type them, then you know what I’m talking about.
Ah, the &lt;em&gt;red squiggly line&lt;/em&gt;.
It’s easy to fix problems when they’re discovered shortly after they’ve been created.
Additionally, we get to learn from them.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;It is impossible for a developer to learn anything when someone yells at them for something they broke six months ago—that is why we need to provide feedback to everyone as quickly as possible, in minutes, not months&lt;/p&gt;
  &lt;footer&gt;&lt;strong&gt;Gary Gruver&lt;/strong&gt;&lt;/footer&gt;
&lt;/blockquote&gt;

&lt;p&gt;Unfortunately, we don’t have a &lt;em&gt;red squiggly line&lt;/em&gt; in our editors for future production issues.
Nor do we have them for unwanted or badly designed features.
The next best thing is to reduce the time between when a problem is introduced and when it is detected.&lt;/p&gt;

&lt;p&gt;In environments where quality is &lt;a href=&quot;https://en.wikipedia.org/wiki/Somebody_else%27s_problem&quot;&gt;&lt;em&gt;somebody else’s problem&lt;/em&gt;&lt;/a&gt;, we involuntarily delay feedback.
For instance, if QA is exclusively in charge of the correctness of the work produced by developers or operations is solely responsible for the software in production, quality is moved further away from the source.
Feedback is received by handing over work to the next work center in the value stream.
Unfortunately, handovers create delays.
Work can pile up because, say, QA is busy testing something else or operations doesn’t have time to provision a testing environment.&lt;/p&gt;

&lt;p&gt;Without immediate feedback, we risk passing on defects to downstream work centers.
Consequently, this can create disruptions in the flow of work.
Not only are issues more difficult and time-consuming to fix when they’re detected later in a value stream, but we also run the risk of increasing &lt;em&gt;work-in-progress&lt;/em&gt;.
For example, if QA is available to test your work starting from, say, tomorrow, you’re not going to wait for them to finish.
Instead, you’re going to work on something else.
However, if any issues are found, you’re going to have to multitask between old and new work.
Fast feedback, on the other hand, prevents the start of new work and gets us closer to &lt;a href=&quot;https://dzone.com/articles/pattern-of-the-month-single-piece-flow&quot; title=&quot;Pattern of the Month: Single Piece Flow&quot;&gt;the single-piece flow&lt;/a&gt;.&lt;/p&gt;

&lt;h3 id=&quot;22-push-quality-closer-to-the-source&quot;&gt;2.2 Push Quality Closer To The Source&lt;/h3&gt;

&lt;p&gt;It seems counterintuitive, but adding more inspection steps and approval processes increase the likelihood of failures.
Surely, having more eyes on the problem should produce better results, right?
That might be true if everybody is fully informed of the work at hand.
But as we start to push decision-making further from where the work is performed, the effectiveness of approval processes decreases.&lt;/p&gt;

&lt;p&gt;Getting approvals from people who are distant from the work has several issues.
First of all, they don’t have the most up-to-date information.
Secondly, they might be busy with other work.
Approvals can start to pile up, creating delays.
Under time pressure, decisions can be rubber-stamped.
These quality control measures give you a false sense of security.
To receive faster and more useful feedback, we should instead push quality closer to the source.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2020-04-01-3-ways-of-devops/pile-of-documents.jpg&quot; alt=&quot;Image of a pile of documents&quot; /&gt;
  &lt;figcaption&gt;Approvals pile up and create delays. The flow of work is disturbed. &lt;a href=&quot;https://unsplash.com/photos/tn57JI3CewI&quot;&gt;Image by Sharon McCutcheon&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Quality shouldn’t be exclusively QA’s responsibility.
Everybody should find and fix issues in their area of control.
In technology value streams, fast feedback close to the source can be achieved with, for example, build automation, automated testing, automated security and vulnerability checking, automated deploys, production telemetry, and alerting.
Automation helps us quickly detect problems, recover from them, and learn how to prevent them.&lt;/p&gt;

&lt;p&gt;In addition to end-users, &lt;a href=&quot;https://www.infoq.com/articles/empathy-technical-skill/&quot;&gt;we should have empathy&lt;/a&gt; for our internal customers.
Designing software with testability in mind makes the job of QA more effective.
It shouldn’t be the responsibility of operations to figure out how to configure, deploy, and monitor the software.
And we shouldn’t forget the goals of information security, sales, and marketing.
By thinking about these concerns early on, we create quality closer to the source.&lt;/p&gt;

&lt;h2 id=&quot;3-principles-of-continual-learning&quot;&gt;3. Principles of Continual Learning&lt;/h2&gt;

&lt;p&gt;The third way is about creating a culture of continual learning and experimentation.
Fast feedback enables us to learn from our mistakes.
But that’s only part of the solution.
We want to continually improve, experiment, and create new knowledge in the entire organization.
After all, organizations that can learn quicker than others have a competitive advantage.&lt;/p&gt;

&lt;h3 id=&quot;31-high-trust-culture&quot;&gt;3.1. High-trust Culture&lt;/h3&gt;

&lt;p&gt;In low trust work environments, incidents are often followed by the &lt;em&gt;name, shame, blame&lt;/em&gt; pattern.
This, however, obstructs individuals and the entire organization from learning.
Getting punished for mistakes incentivizes you to stay in your comfort zone; that happy little place where you’re less likely to cause problems.
You’re discouraged from experimenting, trying out new things, and asking &lt;em&gt;“what-if”&lt;/em&gt; questions.
Instead of taking responsibility, it’s more convenient to hide failures under the covers.
People are less likely to speak up and propose novel solutions to existing problems.
Those who try to innovate are met with resistance.&lt;/p&gt;

&lt;p&gt;When small failure signals are continually withheld, they accumulate, until a major catastrophe happens.
The immediate response from management is to add extra processes and approvals to avoid a future disaster.
This results in lower throughput and longer lead times but doesn’t solve the underlying problem.&lt;/p&gt;

&lt;p&gt;Ron Westrum, &lt;a href=&quot;https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1765804/&quot;&gt;in his 2004 paper titled “A Typology of Organisational Cultures”&lt;/a&gt;, describes this as having a pathological organization culture.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;When things go wrong, pathological climates encourage finding a scapegoat […] Pathological environments will discourage taking responsibility, and can be expected to conceal their problems.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Westrum defines three dominant types of organization culture—pathological, bureaucratic, and generative.
On the opposite side to pathological, we have &lt;em&gt;generative organizations&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Generative organisations require empowerment for maximum performance. Individuals’ minds are harnessed to fulfill the organisation’s goals through a culture of conscious inquiry. They are encouraged to speak up, think outside the box, and to act as fully conscious participants in a great cooperative enterprise.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href=&quot;https://www.researchgate.net/publication/263198947_2014_State_of_DevOps_Report&quot;&gt;The 2014 State of DevOps Report&lt;/a&gt; goes on to say that in generative environments, it is understood that continuous improvement leads to ever-higher levels of throughput and stability.
Learning is actively promoted.
Everybody is encouraged to run experiments to learn how to improve both processes and the products and services they build.
Instead of blaming humans for errors, they look into ways to redesign the system to prevent another one.
And when failures do happen, they’re treated as learning opportunities.
When faced with incidents, &lt;a href=&quot;https://www.atlassian.com/incident-management/postmortem/blameless&quot; title=&quot;How to run a blameless postmortem&quot;&gt;blameless post-mortems&lt;/a&gt; are held.
Results are shared with the entire organization to transform local discoveries into global improvements.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;By removing blame, you remove fear; by removing fear, you enable honesty; and honesty enables prevention&lt;/p&gt;
  &lt;footer&gt;&lt;strong&gt;Bethany Marci&lt;/strong&gt; &amp;mdash; &lt;a href=&quot;https://vimeo.com/77206751&quot;&gt;Morgue: Helping Better Understand Events by Building a Post Mortem Tool&lt;/a&gt;&lt;/footer&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;32-continuous-improvement&quot;&gt;3.2. Continuous Improvement&lt;/h3&gt;

&lt;p&gt;Teams that are too busy to improve their daily work, and regularly rely on workarounds, increase their technical debt.
Not only will they continue to suffer, but the suffering increases over time.
Processes degrade, productivity plummets, and throughput decreases.&lt;/p&gt;

&lt;blockquote class=&quot;twitter-tweet&quot;&gt;&lt;p lang=&quot;en&quot; dir=&quot;ltr&quot;&gt;Are you too busy to improve &lt;a href=&quot;http://t.co/O9Gmel3ICB&quot;&gt;pic.twitter.com/O9Gmel3ICB&lt;/a&gt;&lt;/p&gt;&amp;mdash; Shayne 👨🏿‍💻 UXD (@shaynecuffy) &lt;a href=&quot;https://twitter.com/shaynecuffy/status/499473730046001152?ref_src=twsrc%5Etfw&quot;&gt;August 13, 2014&lt;/a&gt;&lt;/blockquote&gt;
&lt;script async=&quot;&quot; src=&quot;https://platform.twitter.com/widgets.js&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;

&lt;p&gt;Improvement shouldn’t be viewed as an optional activity, something you do when you have extra time.
It should be continuous, part of the daily routine of every team.
Time should be consciously reserved to pay down technical debt, run experiments, improve workflows, and create new knowledge.
&lt;a href=&quot;https://mikeorzen.com/change-fatigue-psychological-safety-and-the-leadership-void-why-most-ci-initiatives-dont-last/&quot; title=&quot;Change Fatigue, Psychological Safety and the Leadership Void: Why Most CI Initiatives Don’t Last&quot;&gt;In a continuous improvement culture, improving the way we work is more important than doing the work!&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://amzn.to/3bAWtC0&quot;&gt;The DevOps Handbook&lt;/a&gt; lays out three core principles.
In short, they are:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Smooth flow of work from development to operations to customers&lt;/li&gt;
  &lt;li&gt;Amplification of feedback loops so that corrections and improvements can be continuously made&lt;/li&gt;
  &lt;li&gt;Creation of a high-trust culture that encourages experimentation and learning from failure&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This post covered what I found most valuable.
But the book goes into more detail about various practices that go along with the principles.
It is a recommended read for everyone interested in DevOps.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/3-ways-of-devops/&quot;&gt;The Three Ways of DevOps&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on June 14, 2020.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[Pattern Matching for instanceOf in Java 14]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/java-14-instanceOf/" />
  <id>https://blog.indrek.io/articles/java-14-instanceOf</id>
  <updated>2020-03-28 18:56:18 +0300T00:00:00-00:00</updated>
  <published>2020-03-28T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;instanceOf&lt;/code&gt; operator in Java is used to test whether an object is of a specific type.
A common usage pattern is to first check, then cast and finally use the extracted variable.
In this post we’re going to look at the pattern matching capabilities added to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;instanceOf&lt;/code&gt; operator in Java 14 and how it’s going to enhance the programming language.&lt;/p&gt;

&lt;h2 id=&quot;instanceof-before-java-14&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;instanceOf&lt;/code&gt; before Java 14&lt;/h2&gt;

&lt;p&gt;A typical usage for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;instanceOf&lt;/code&gt; is the &lt;em&gt;check-then-cast&lt;/em&gt; pattern.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obj&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;instanceof&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;obj&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;toUpperCase&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;First we check whether &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;obj&lt;/code&gt; is a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;String&lt;/code&gt; and then we cast &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;obj&lt;/code&gt; into a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;String&lt;/code&gt;.
These steps go together so often that one might label this as boilerplate.
Next, we’re going to look at how pattern matching tries to provide a better solution.&lt;/p&gt;

&lt;h2 id=&quot;pattern-matching-in-java-14&quot;&gt;Pattern Matching in Java 14&lt;/h2&gt;

&lt;p&gt;Starting from java 14, we can use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;instanceOf&lt;/code&gt; as follows.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obj&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;instanceof&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;toUpperCase&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Casting is done at the same time as the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;instanceOf&lt;/code&gt; check.
To be technically correct, &lt;a href=&quot;https://openjdk.java.net/jeps/305&quot; title=&quot;JEP 305: Pattern Matching for instanceof&quot;&gt;JEP 305&lt;/a&gt; describes this as a &lt;em&gt;type test pattern&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;A pattern is a combination of (1) a predicate that can be applied to a target, and (2) a set of binding variables that are extracted from the target only if the predicate successfully applies to it.
A &lt;strong&gt;type test pattern&lt;/strong&gt; consists of a predicate that specifies a type, along with a single binding variable.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;instanceOf&lt;/code&gt; operator matches &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;obj&lt;/code&gt; to the type test pattern.
If the test passes, casting is done automatically and variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;s&lt;/code&gt; is of type &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;String&lt;/code&gt; in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; block of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt; statement.
In more complicated conditional expressions, the scope of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;s&lt;/code&gt; grows as well.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obj&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;instanceof&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Pattern matching for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;instanceOf&lt;/code&gt;, &lt;a href=&quot;https://openjdk.java.net/projects/jdk/14/&quot;&gt;along with other features introduced in Java 14&lt;/a&gt;,
make the language nicer to use and show that the decision to &lt;a href=&quot;https://www.infoq.com/news/2017/09/Java6Month/&quot; title=&quot;Java to Move to 6-Monthly Release Cadence&quot;&gt;move to a 6 month release cadence&lt;/a&gt; back in 2017 helps the language to evolve faster.&lt;/p&gt;

&lt;p&gt;Keep in mind, pattern matching for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;instanceOf&lt;/code&gt; in Java 14 is a &lt;a href=&quot;https://openjdk.java.net/jeps/12&quot; title=&quot;JEP 12: Preview Language and VM Features&quot;&gt;preview feature&lt;/a&gt;.
The implementation could change and evolve in upcoming releases.
To unlock preview features, use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;--enable-preview&lt;/code&gt; command line flag for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;javac&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;java&lt;/code&gt;.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/java-14-instanceOf/&quot;&gt;Pattern Matching for instanceOf in Java 14&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on March 28, 2020.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[Helpful NullPointerExceptions in Java 14]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/java-14-helpful-nullpointerexception/" />
  <id>https://blog.indrek.io/articles/java-14-helpful-nullpointerexception</id>
  <updated>2020-02-29 18:56:18 +0300T00:00:00-00:00</updated>
  <published>2020-02-29T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;Being &lt;a href=&quot;https://blog.overops.com/the-top-10-exceptions-types-in-production-java-applications-based-on-1b-events/&quot; title=&quot;The Top 10 Exception Types in Production Java Applications&quot;&gt;the most common exception in Java&lt;/a&gt;, the infamous &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NullPointerException&lt;/code&gt; is probably the first exception a new Java developer experiences.
To offer helpful information to developers and improve the usability of the language, Java 14 &lt;a href=&quot;https://openjdk.java.net/jeps/358&quot; title=&quot;JEP 358: Helpful NullPointerExceptions&quot;&gt;introduces improved &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NullPointerException&lt;/code&gt;&lt;/a&gt; messages which point out precisely the variable that was &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;npes-before-java-14&quot;&gt;NPEs before Java 14&lt;/h2&gt;

&lt;p&gt;Let’s say we have the following classes.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Person&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;nc&quot;&gt;Name&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Name&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;firstName&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lastName&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;A &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NullPointerException&lt;/code&gt; occurs when we try to dereference a variable that points to nothing.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;Person&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;person&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;person&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// Exception in thread &quot;main&quot; java.lang.NullPointerException&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;//   at mypackage.MyClass.main(MyClass.java:7)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Reading the error message, it’s fairly obvious that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;person&lt;/code&gt; is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;.
However, when the code is more complex, the error message is not that helpful anymore.
Imagine we get a reference to a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Person&lt;/code&gt; object and then try to access its fields.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;person&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;getPersonFromDatabase&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;person&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;firstName&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// Exception in thread &quot;main&quot; java.lang.NullPointerException&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;//   at mypackage.MyClass.main(MyClass.java:7)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;From the error message we can infer that either &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;person&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;name&lt;/code&gt; was &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;.
If the issue is reproducible and we have access to the source code we could debug the problem by attaching a debugger or create intermediate local variables.
However, when the error is found from logs from a production server, we don’t have a clear indication which variable was &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;new-and-improved-npe-error-messages&quot;&gt;New and improved NPE error messages&lt;/h2&gt;

&lt;p&gt;Java 14 introduces &lt;a href=&quot;https://openjdk.java.net/jeps/358&quot; title=&quot;JEP 358: Helpful NullPointerExceptions&quot;&gt;Helpful NullPointerExceptions&lt;/a&gt; that improve NPE error messages by describing precisely which variable was &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;.
If we were to run the previous example in Java 14, we would get a different error message.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;person&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;getPersonFromDatabase&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;person&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;firstName&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// Exception in thread &quot;main&quot; java.lang.NullPointerException: Cannot read field &quot;firstName&quot; because &quot;person.name&quot; is null&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;//   at mypackage.MyClass.main(MyClass.java:7)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This time, the error message is more usable and there’s no need to hunt down which variable is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;By pointing out which variable was &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; in the error message greatly improves the usability of the language.
Keep in mind that in Java 14, helpful &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NullPointerException&lt;/code&gt; messages are turned off by default.
You need to start the JVM with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-XX:+ShowCodeDetailsInExceptionMessages&lt;/code&gt; command line flag.
Helpful error messages will be enabled by default in Java 15.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/java-14-helpful-nullpointerexception/&quot;&gt;Helpful NullPointerExceptions in Java 14&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on February 29, 2020.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[Java 14 Records]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/java-14-records/" />
  <id>https://blog.indrek.io/articles/java-14-records</id>
  <updated>2020-02-22 18:56:18 +0300T00:00:00-00:00</updated>
  <published>2020-02-22T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;Java 14 introduces a &lt;a href=&quot;https://openjdk.java.net/jeps/359&quot; title=&quot;JEP 359: Records (Preview)&quot;&gt;new preview feature&lt;/a&gt; to the language—Records.
Its goal is to offer a compact syntax for declaring containers of shallowly immutable data.&lt;/p&gt;

&lt;h2 id=&quot;records-in-action&quot;&gt;Records in Action&lt;/h2&gt;

&lt;p&gt;It’s common to declare classes in Java that hold nothing more than data.
Sometimes they’re referred to as &lt;em&gt;data transfer objects&lt;/em&gt; or &lt;em&gt;value objects&lt;/em&gt; but you can think of them as just a bag of getters and setters.
For example, to represent a point on a &lt;a href=&quot;https://en.wikipedia.org/wiki/Cartesian_coordinate_system&quot; title=&quot;Cartesian coordinate system&quot;&gt;Cartesian plane&lt;/a&gt;, the following class could do the job.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Point&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;Point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// getters and setters&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// toString&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// equals and hashCode&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The bits of information that make the class interesting are the x and y coordinates.
However, in order for the class to behave correctly, a constructor has to be declared, getters and possibly setters have to be provided, and also &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;toString&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;equals&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;hashCode&lt;/code&gt; methods have to be implemented.&lt;/p&gt;

&lt;p&gt;Modern IDEs can generate this code for us.
Users of &lt;a href=&quot;https://projectlombok.org/&quot; title=&quot;Project Lombok&quot;&gt;Lombok&lt;/a&gt; are well aware of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@Data&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@Value&lt;/code&gt; annotations that generate the boilerplate code during build time.
Records, on the other hand, introduce a syntax to declare &lt;em&gt;only&lt;/em&gt; the parts that are important for the reader.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;record&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;Point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;No need to declare a constructor or worry whether &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;equals&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;hashCode&lt;/code&gt; are implemented correctly.
Records need a name and a &lt;em&gt;state description&lt;/em&gt;, that’s it.&lt;/p&gt;

&lt;h2 id=&quot;its-not-only-about-boilerplate&quot;&gt;It’s not only about boilerplate&lt;/h2&gt;

&lt;p&gt;At first glance, records seem to address the “&lt;em&gt;java is too verbose&lt;/em&gt;” issue.
While that might be true to some extent, the description of &lt;a href=&quot;https://openjdk.java.net/jeps/359&quot;&gt;JEP 359: Records&lt;/a&gt; hints that records have a semantic goal, to model data as data.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;IDEs will help write most of the code in a data carrier class, but don’t do anything to help the reader distill the design intent of “I’m a data carrier for x, y, and z” from the dozens of lines of boilerplate. Writing Java code that models simple aggregates should be easier – to write, to read, and to verify as correct.
While it is superficially tempting to treat records as primarily being about boilerplate reduction, we instead choose a more semantic goal: modeling data as data. (If the semantics are right, the boilerplate will take care of itself.) It should be easy, clear, and concise to declare shallowly-immutable, well-behaved nominal data aggregates.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;constructor&quot;&gt;Constructor&lt;/h2&gt;

&lt;p&gt;A constructor for a record is automatically generated.
It accepts the &lt;em&gt;components&lt;/em&gt; of a record in the order they were declared.
Continuing with our Cartesian point example, to create a new &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Point&lt;/code&gt;, the syntax is the same as creating any other object.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;point&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.9&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In cases where we want to validate constructor arguments, we have to explicitly declare the constructor.
It may be declared without a formal parameter list though, since it is assumed to be identical to the &lt;em&gt;state description&lt;/em&gt;.
Parameters that are left unassigned in the constructor body are implicitly initialised.
This means that we don’t need to assign every constructor parameter to a field (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;this.x = x&lt;/code&gt;).&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;record&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;Point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Point&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// to illustrate, let&apos;s imagine that the value 3.5&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// is not allowed for the x coordinate&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;3.5&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;IllegalArgumentException&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;immutability&quot;&gt;Immutability&lt;/h2&gt;

&lt;p&gt;Records are shallowly immutable.
Declared fields are implicitly &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;final&lt;/code&gt; and they can be accessed via accessor methods.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;point&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.9&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;5.2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// prints out 2.9&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The new syntax provides an easy way to create what &lt;a href=&quot;https://en.wikipedia.org/wiki/Domain-driven_design&quot; title=&quot;Domain-driven design&quot;&gt;DDD&lt;/a&gt; practitioners call &lt;a href=&quot;https://www.martinfowler.com/bliki/ValueObject.html&quot; title=&quot;ValueObject&quot;&gt;value objects&lt;/a&gt;
These are immutable objects that model a value that’s only distinguishable by its state.
If you need to edit a record, you need to create a new one.&lt;/p&gt;

&lt;p class=&quot;notice&quot;&gt;📖 You can read more about value objects and DDD form the book that started it all: &lt;a href=&quot;https://amzn.to/320l3Z5&quot; title=&quot;Domain-Driven Design: Tackling Complexity in the Heart of Software&quot;&gt;Domain-Driven Design: Tackling Complexity in the Heart of Software&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;static-methods&quot;&gt;Static methods&lt;/h2&gt;

&lt;p&gt;Records can contain static methods.
For example, we could include a static factory method to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Point&lt;/code&gt; record that creates a new point at the origin.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;record&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;Point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Point&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;origin&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;Point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;instance-methods&quot;&gt;Instance Methods&lt;/h2&gt;

&lt;p&gt;Besides static methods, we can also include instance methods to records.
Let’s say, we would like to know the distance to another point on a Cartesian plane.
The formula for finding the distance between two points is:&lt;/p&gt;

&lt;p&gt;\[ \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2} \]&lt;/p&gt;

&lt;p&gt;Implementing it as an instance method on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Point&lt;/code&gt; record looks as follows.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;record&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;Point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;distanceTo&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Point&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Math&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Math&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;pow&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Math&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;pow&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;limitations&quot;&gt;Limitations&lt;/h2&gt;

&lt;p&gt;Due to the intended purpose of records, there are limitations we have to take into account.
Records cannot extend any other class and cannot declare instance fields that aren’t part of its state description.
This is to make sure the state description of a record alone defines its representation.
Since immutability is at the core of a record, the &lt;em&gt;components&lt;/em&gt; of a record are implicitly final.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Records introduce a new syntax to the Java language, allowing programmers to declare immutable data classes.
While on the outset, the biggest benefit seems to be the reduction of boilerplate code, there’s also a semantic difference.
Records &lt;em&gt;model data as data&lt;/em&gt; and provide a clear sign to the reader that they’re dealing with a data class.&lt;/p&gt;

&lt;p&gt;Keep in mind, records in Java 14 are a &lt;a href=&quot;https://openjdk.java.net/jeps/12&quot; title=&quot;JEP 12: Preview Language and VM Features&quot;&gt;preview feature&lt;/a&gt;.
The implementation could change and evolve in the upcoming releases.
To unlock records, use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;--enable-preview&lt;/code&gt; command line flag for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;javac&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;java&lt;/code&gt;.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/java-14-records/&quot;&gt;Java 14 Records&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on February 22, 2020.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[Running Spring Boot apps as GraalVM native images]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/running-spring-boot-apps-as-graalvm-native-images/" />
  <id>https://blog.indrek.io/articles/running-spring-boot-apps-as-graalvm-native-images</id>
  <updated>2020-01-06 18:56:18 +0300T00:00:00-00:00</updated>
  <published>2020-01-06T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;&lt;a href=&quot;https://www.graalvm.org/&quot; title=&quot;High-performance polyglot VM&quot;&gt;GraalVM&lt;/a&gt; is a high-performance polyglot virtual machine for running applications written in JavaScript, JVM-based languages, LLVM-based languages and &lt;a href=&quot;https://www.graalvm.org/docs/&quot; title=&quot;GraalVM Docs&quot;&gt;others&lt;/a&gt;.
For Java workloads it’s used as a regular JVM &lt;a href=&quot;https://www.youtube.com/watch?v=pR5NDkIZBOA&quot; title=&quot;Twitter&apos;s quest for a wholly Graal runtime&quot;&gt;but with performance advantages&lt;/a&gt;.
An interesting feature that GraalVM brings to the table is its ability to create &lt;em&gt;ahead-of-time&lt;/em&gt; (AOT) compiled native images of JVM applications which promise faster startup times and lower memory footprint.
In this post we’re going to focus on how to create native binaries from Spring applications.&lt;/p&gt;

&lt;h2 id=&quot;graalvm-native-image-101&quot;&gt;GraalVM Native Image 101&lt;/h2&gt;

&lt;p&gt;Java applications are compiled into bytecode using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;javac&lt;/code&gt;.
During application runtime, the JVM loads class files into memory and analyzes the program’s performance for &lt;a href=&quot;https://en.wikipedia.org/wiki/Hot_spot_(computer_programming)&quot;&gt;hot spots&lt;/a&gt;; hence the name “&lt;a href=&quot;https://en.wikipedia.org/wiki/HotSpot&quot;&gt;HotSpot JVM&lt;/a&gt;”.
The &lt;em&gt;just-in-time&lt;/em&gt; (JIT) compiler compiles parts of the application which are executed repeatedly into native machine code.
&lt;a href=&quot;https://aboullaite.me/understanding-jit-compiler-just-in-time-compiler/&quot; title=&quot;Understanding JIT compiler&quot;&gt;JIT compilation, however, requires processor time and memory&lt;/a&gt; which affects the startup time of the application.&lt;/p&gt;

&lt;p&gt;GraalVM native image allows us to &lt;em&gt;ahead-of-time&lt;/em&gt; compile our JVM application into machine code.
It statically analyzes application’s bytecode, finds all classes and methods that are ever reachable and compiles them into a native executable.
The output is a platform specific executable binary.&lt;/p&gt;

&lt;p&gt;For instance, let’s build a native image from the following “Hello World” program.&lt;/p&gt;
&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;HelloWorld&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[]&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;args&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Hello World&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;First, we need to compile the Java code with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;javac&lt;/code&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ javac HelloWorld.java
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;and then use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;native-image&lt;/code&gt; to build an executable binary from the class file.&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ native-image HelloWorld
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;To start the application, simply&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ ./helloworld
Hello World
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;native-image-java-limitations&quot;&gt;Native Image Java Limitations&lt;/h2&gt;

&lt;p&gt;GraalVM native image static analysis requires a closed-world assumption.
It needs to know all the bytecode that’s ever reachable ahead of time during image generation.
Thus, &lt;a href=&quot;https://github.com/oracle/graal/blob/master/substratevm/LIMITATIONS.md&quot; title=&quot;Native Image Java Limitations&quot;&gt;not all Java features are supported&lt;/a&gt; or they require configuration.&lt;/p&gt;

&lt;p&gt;For example, dynamic class loading/unloading is not supported.
Reflection requires configuration.
CGLIB proxies don’t work with native images.
On the other hand, JDK proxies are supported but require configuration.
Additionally, you need to tell native image about all resource accesses.&lt;/p&gt;

&lt;p&gt;Configuration is supplied in a form of a JSON document.
For instance, to configure reflection, you create the following file and use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-H:ReflectionConfigurationFiles&lt;/code&gt; command line flag to specify the file location to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;native-image&lt;/code&gt; command.&lt;/p&gt;

&lt;div class=&quot;language-json highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;java.lang.Object&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;org.apache.naming.factory.ResourceFactory&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;methods&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[{&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;&amp;lt;init&amp;gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;parameterTypes&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:[]}]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;...&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Similar files have to be created to configure dynamic proxies, JNI and resource accesses.
Doing all this by hand is a lot of work though, especially when we’re dealing with a large application.
Fortunately, there’s a &lt;a href=&quot;https://medium.com/graalvm/introducing-the-tracing-agent-simplifying-graalvm-native-image-configuration-c3b56c486271&quot; title=&quot;Introducing the Tracing Agent: Simplifying GraalVM Native Image Configuration&quot;&gt;Java agent that can generate the configuration&lt;/a&gt;.
It observes the behavior of an application running in a JVM and produces configuration files needed for native image generation.&lt;/p&gt;

&lt;p&gt;To get a complete set of configuration files, you would need to exercise all code paths in your application.
A tests suite with 100% coverage would do the trick but in reality, test suites never test all paths.
Therefore, manual modification of these configuration files might be needed as well.&lt;/p&gt;

&lt;h2 id=&quot;spring-and-graalvm-native-image&quot;&gt;Spring and GraalVM Native Image&lt;/h2&gt;

&lt;p&gt;Starting from Spring Framework 5.1, &lt;a href=&quot;https://github.com/spring-projects/spring-framework/issues/21529&quot; title=&quot;Initial GraalVM native images support&quot;&gt;initial support for GraalVM native images was provided&lt;/a&gt;.
&lt;a href=&quot;https://github.com/spring-projects/spring-framework/wiki/GraalVM-native-image-support#support-of-native-images-at-spring-framework-level&quot; title=&quot;Support of native images at Spring Framework level&quot;&gt;The 5.2 development cycle is focusing on improving the integration&lt;/a&gt; and full support without requiring extra configuration or workarounds is &lt;a href=&quot;https://twitter.com/devoxx/status/1128937256180473856&quot;&gt;one of the themes of the upcoming Spring Framework 5.3 release&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote class=&quot;twitter-tweet&quot;&gt;&lt;p lang=&quot;en&quot; dir=&quot;ltr&quot;&gt;&lt;a href=&quot;https://twitter.com/hashtag/Spring?src=hash&amp;amp;ref_src=twsrc%5Etfw&quot;&gt;#Spring&lt;/a&gt; framework 5.3 (Q2 2020) will support &lt;a href=&quot;https://twitter.com/hashtag/GraalVM?src=hash&amp;amp;ref_src=twsrc%5Etfw&quot;&gt;#GraalVM&lt;/a&gt; native images and much more! &lt;a href=&quot;https://twitter.com/hashtag/SpringBoot?src=hash&amp;amp;ref_src=twsrc%5Etfw&quot;&gt;#SpringBoot&lt;/a&gt; &lt;a href=&quot;https://t.co/GqsfknZ6gc&quot;&gt;pic.twitter.com/GqsfknZ6gc&lt;/a&gt;&lt;/p&gt;&amp;mdash; Devoxx (@Devoxx) &lt;a href=&quot;https://twitter.com/Devoxx/status/1128937256180473856?ref_src=twsrc%5Etfw&quot;&gt;May 16, 2019&lt;/a&gt;&lt;/blockquote&gt;
&lt;script async=&quot;&quot; src=&quot;https://platform.twitter.com/widgets.js&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;example-spring-boot-application&quot;&gt;Example Spring Boot Application&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/spring-projects-experimental/spring-graal-native&quot; title=&quot;Graal feature for building native images of Spring applications&quot;&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;spring-graal-native&lt;/code&gt; Github repository&lt;/a&gt; has examples of how to build a native image from a Spring Boot application.
The project implements a &lt;a href=&quot;https://www.graalvm.org/sdk/javadoc/index.html?org/graalvm/nativeimage/hosted/Feature.html&quot;&gt;Graal &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Feature&lt;/code&gt;&lt;/a&gt; which does the heavy lifting when it comes to configuring reflection, proxies etc.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Features allow clients to intercept the native image generation and run custom initialization code at various stages. All code within feature classes is executed during native image generation, and never at run time.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s focus on a hello-world-level Spring Boot example—&lt;a href=&quot;https://github.com/indrekots/spring-graal-native/tree/master/spring-graal-native-samples/springmvc-tomcat&quot;&gt;Spring MVC with Tomcat&lt;/a&gt;.
Keep in mind, as of writing this, the example expects you’re using GraalVM 19.2.1 and you have the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;native-image&lt;/code&gt; plugin installed.&lt;/p&gt;

&lt;p&gt;Before building the example, we need to compile the Spring Graal Feature.
The &lt;a href=&quot;https://github.com/indrekots/spring-graal-native&quot;&gt;root of the repository&lt;/a&gt; has a bash script to do that.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ ./build-feature.sh
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Once that’s finished, let’s move to the &lt;a href=&quot;https://github.com/indrekots/spring-graal-native/tree/master/spring-graal-native-samples/springmvc-tomcat&quot;&gt;Spring MVC example folder&lt;/a&gt; and execute &lt;a href=&quot;https://github.com/indrekots/spring-graal-native/blob/master/spring-graal-native-samples/springmvc-tomcat/compile.sh&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;compile.sh&lt;/code&gt;&lt;/a&gt;.
It builds the Spring app using Maven and then generates a GraalVM native image.
The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;native-image&lt;/code&gt; command is supplied with the location of the Spring Graal Feature and various configuration files.
Be warned that native image generation takes considerably longer than a regular Maven build.
Also, the process likes to use a lot of RAM.
When finished, navigate to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;target&lt;/code&gt; folder and start the app.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ ./springmvc-tomcat
  .   ____          _            __ _ _
 /\\ / ___&apos;_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | &apos;_ | &apos;_| | &apos;_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  &apos;  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::

...

INFO: Started TomcatApplication in 0.054 seconds (JVM running for 0.057)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Notice the fast startup time of 0.054 seconds.
For comparison, when running the app in a JVM, the reported startup time for me was 1.455 seconds.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;GraalVM native image enables us to build ahead-of-time compiled JVM applications that start very fast and use less memory.
That’s definitely useful for short lived processes, especially in the serverless scene where you’re billed by the millisecond.&lt;/p&gt;

&lt;p&gt;Due to classpath scanning and auto-configuration, Spring Boot apps are &lt;a href=&quot;https://stackoverflow.com/q/47270059/2928051&quot;&gt;very CPU hungry during startup&lt;/a&gt;.
When starting multiple Spring Boot apps simultaneously on a shared host, they start to compete for CPU and the startup time increases.
Orchestration tools could even kill the processes &lt;a href=&quot;https://github.com/kubernetes/kubernetes/issues/3312&quot;&gt;because they didn’t start fast enough&lt;/a&gt;.
Fast-starting ahead-of-time compiled Spring Boot apps could be the answer to the problem.&lt;/p&gt;

&lt;p&gt;Containerized Spring Boot applications have something to gain as well.
Since a native binary has everything it needs, there’s no need to bake a JRE into the container anymore. We can build &lt;a href=&quot;https://blog.softwaremill.com/small-fast-docker-images-using-graalvms-native-image-99c0bc92e70b&quot; title=&quot;Small &amp;amp; fast Docker images using GraalVM’s native-image&quot;&gt;smaller Docker images&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Several microservice-focused frameworks have already made use of the native image feature (e.g. &lt;a href=&quot;https://quarkus.io/&quot;&gt;Quarkus&lt;/a&gt;, &lt;a href=&quot;https://micronaut.io/&quot;&gt;Micronaut&lt;/a&gt;, &lt;a href=&quot;https://helidon.io/&quot;&gt;Helidon&lt;/a&gt;).
Although, Spring Boot does not yet fully support native image generation, I think it will be a significant addition to the framework.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/running-spring-boot-apps-as-graalvm-native-images/&quot;&gt;Running Spring Boot apps as GraalVM native images&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on January 06, 2020.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[Misusing Java's Optional type]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/misusing-java-optional/" />
  <id>https://blog.indrek.io/articles/misusing-java-optional</id>
  <updated>2019-10-05 18:56:18 +0300T00:00:00-00:00</updated>
  <published>2019-10-05T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/optionals-in-java-8/&quot; title=&quot;Optionals in Java 8&quot;&gt;Optionals were introduced to Java&lt;/a&gt; in version 8.
Prior to it, when we had no value to return from a method, we could for example return a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; or throw an exception.
Both options have their drawbacks.
If the calling code forgets to check the return value for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;, there’s a high chance for a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NullPointerException&lt;/code&gt; to happen down the line.
Throwing an exception also does not feel right.
The fact that a value is missing isn’t always an exceptional situation.&lt;/p&gt;

&lt;p&gt;Java’s Optional has been &lt;a href=&quot;https://blog.developer.atlassian.com/optional-broken/&quot;&gt;criticised&lt;/a&gt; for its &lt;a href=&quot;https://medium.com/@bgourlie/java-8-s-new-optional-type-is-worthless-448a00fa672d&quot;&gt;flaws&lt;/a&gt; but despite that I personally find them tremendously useful.
Over the years, however, I’ve also seen code where I think the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; type has been misused.
The following is a list of misuses of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; and what you can do to avoid them.&lt;/p&gt;

&lt;h2 id=&quot;1-returning-null-from-an-optional-returning-method&quot;&gt;1. Returning &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; from an Optional-returning method&lt;/h2&gt;

&lt;p&gt;When you see that a method returns an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; of something, this is a clear indication that the method signature is trying to tell you that &lt;a href=&quot;https://blog.codefx.org/techniques/intention-revealing-code-java-8-optional/&quot;&gt;the return value might be missing&lt;/a&gt;.
The good thing about Optionals is that they force you to handle the special case where there might be no value.
Since Optionals are designed so that we don’t have to explicitly deal with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; references anymore, returning a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; from an Optional-returning method will definitely throw somebody off guard.
Most of us don’t expect the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; container itself to be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;.
Returning a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; from an Optional-returning method means that we have to handle two special cases - &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; reference and empty &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;https://amzn.to/31uiEnG&quot; title=&quot;Effective Java 3rd Edition&quot;&gt;Effective Java&lt;/a&gt;, the author &lt;a href=&quot;https://twitter.com/joshbloch&quot;&gt;Joshua Bloch&lt;/a&gt; writes&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;Never return a null value from an Optional-returning method: it defeats the entire purpose of the facility.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href=&quot;https://twitter.com/stuartmarks&quot;&gt;Stuart marks&lt;/a&gt; gave a presentation about Optionals for &lt;a href=&quot;https://virtualjug.com/&quot;&gt;vJUG&lt;/a&gt; where he emphasised to never, ever, use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; for an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; variable or return value.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-08-12-misusing-java-optional/optional-null.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Slide from a &lt;a href=&quot;https://virtualjug.com/&quot;&gt;vJUG&lt;/a&gt; presentation &lt;a href=&quot;https://www.youtube.com/watch?v=4f9j0LtULiM&quot;&gt;&quot;Optional - The Mother of All Bikesheds by Stuart Marks&quot;&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Make sure that the method responsible for returning the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; &lt;em&gt;never&lt;/em&gt; returns &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;.
Make use of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional.empty()&lt;/code&gt; instead.&lt;/p&gt;

&lt;h2 id=&quot;2-checking-whether-an-optional-is-null&quot;&gt;2. Checking whether an Optional is null&lt;/h2&gt;

&lt;p&gt;Checking whether a variable of type &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; is related to the previous misuse.
If we write code that ensures an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; can never be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;, then there’s no need to check for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; references.
It saves us from cluttering our code with unnecessary &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; checks.
If, however, you find yourself in a situation where an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; for some reason is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;, refer back to the previous paragraph.&lt;/p&gt;

&lt;p&gt;Handling two special cases—&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; reference or an empty &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt;—defeats the entire purpose of using Optionals.
To put it differently, adding an extra layer of indirection in the form of an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; container but reaping none of its benefits is worse compared to not using Optionals at all.&lt;/p&gt;

&lt;p&gt;If you use &lt;a href=&quot;https://www.sonarqube.org/&quot;&gt;SonarQube&lt;/a&gt; or have the &lt;a href=&quot;https://www.sonarlint.org/&quot;&gt;SonarLint&lt;/a&gt; plugin for your IDE, checking an Optional variable for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; results in the following bug report.&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;The concept of Optional is that it will be used when &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; could cause errors. In a way, it replaces &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;, and when Optional is in use, there should never be a question of returning or receiving &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; from a call.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To conclude, make sure a variable whose type is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; is &lt;em&gt;never&lt;/em&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;3-using-optional-as-a-method-parameter&quot;&gt;3. Using Optional as a method parameter&lt;/h2&gt;

&lt;p&gt;Java language doesn’t have &lt;a href=&quot;https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments#optional-arguments&quot;&gt;optional method parameters&lt;/a&gt; but one might think that we could implement it using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt;.
Let’s have a look at the following method declaration.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;greet&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Optional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Hello &quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;orElse&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;world&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Seems nice and succinct, right?
Well, the method body is a beautiful one-liner but let’s quickly look at how callers should invoke the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;greet&lt;/code&gt; method.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;greet&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Optional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;of&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;neighbor&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// prints &quot;Hello neighbor&quot;&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;greet&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Optional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;empty&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// prints &quot;Hello world&quot;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Callers must always wrap every argument with an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; or pass an empty &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt;.
A simpler approach would be to use overloaded methods instead.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;greet&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Hello &quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;greet&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;greet&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;world&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Callers can simply pass in the string without having to do any additional wrapping.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;greet&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;neighbor&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// prints &quot;Hello heighbor&quot;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;greet&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// prints &quot;Hello world&quot;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;But let’s say we were not trying to implement optional parameters.
We just have an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; at hand and want to pass it to another method for further processing, would that be okay?&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;Optional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Customer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;customer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;...&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// get a customer object&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;process&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;customer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;There’s nothing stopping you from doing that but perhaps we can do better?
If we think about, what would happen inside the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;process&lt;/code&gt; method?
Most likely it would try to unwrap the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; and do something with the underlying &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Customer&lt;/code&gt;.
If that’s the case, a more elegant solution would be to make use of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ifPresent&lt;/code&gt; method on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; class and pass it a &lt;a href=&quot;https://blog.indrek.io/articles/java-8-lambda-expressions/&quot; title=&quot;Java 8: Lambda expressions&quot;&gt;lambda expression&lt;/a&gt; or a &lt;a href=&quot;https://blog.indrek.io/articles/four-types-of-method-references-in-java-8/&quot; title=&quot;Four types of method references in Java 8&quot;&gt;method reference&lt;/a&gt;.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;Optional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Customer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;customer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;customer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;ifPresent&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;process&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Java Language Architect Brian Goetz had the following to say &lt;a href=&quot;https://stackoverflow.com/a/26328555/2928051&quot;&gt;in an answer to a question about Optionals on Stack Overflow&lt;/a&gt;.&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;You should almost never use it as a field of something or a method parameter.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;4-getting-a-value-from-optional-without-making-sure-its-present&quot;&gt;4. Getting a value from Optional without making sure it’s present&lt;/h2&gt;

&lt;p&gt;Getting the value from the Optional container seems trivial.
Just use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;get()&lt;/code&gt; method.
&lt;a href=&quot;https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Optional.html#get()&quot;&gt;But if we look more closely at the documentation&lt;/a&gt;, we can see that it throws a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NoSuchElementException&lt;/code&gt; when the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; is empty.
By just reading the method name it seemed like a safe operation but it’s not.
Before calling &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;get()&lt;/code&gt;, we &lt;em&gt;must&lt;/em&gt; make sure the Optional has a value inside.&lt;/p&gt;

&lt;p&gt;Brian Goetz wrote the following in a popular &lt;a href=&quot;https://stackoverflow.com/a/26328555/2928051&quot;&gt;Stack Overflow answer&lt;/a&gt;.&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;NEVER call &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional.get&lt;/code&gt; unless you can prove it will never be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;; instead use one of the safe methods like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;orElse&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ifPresent&lt;/code&gt;. In retrospect, we should have called get something like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;getOrElseThrowNoSuchElementException&lt;/code&gt; or something that made it far clearer that this was a highly dangerous method that undermined the whole purpose of Optional in the first place. Lesson learned.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;There were even talks about deprecating &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional::get&lt;/code&gt; in &lt;a href=&quot;http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-April/040484.html&quot;&gt;OpenJDK mailing list&lt;/a&gt; but the idea was not well received.
Java 10 introduced a new overloaded method for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional::orElseThrow&lt;/code&gt; without any parameters.
The behaviour of this method is the same as for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional::get&lt;/code&gt; but the name is more appropriate.&lt;/p&gt;

&lt;p&gt;Therefore, before calling &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;get&lt;/code&gt; you must prove that an Optional has a value with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;isPresent&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;Optional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optional&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;isPresent&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;str&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;On the other hand, this approach is hardly an improvement compared to checking for nulls.
Compare it with the following code.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;str&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;str&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;// do something with str&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The structure is the same.
We first check, then act.
The problem with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional::get&lt;/code&gt; is that it leads us to write the same style of code that we wrote when we explicitly checked for null references.
That invites an obvious question, what’s the benefit of Optionals then?&lt;/p&gt;

&lt;p&gt;Instead of using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional::get&lt;/code&gt;, most of the time we can create a more elegant solution by using alternative methods on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; class (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;map&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;filter&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ifPresent&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;orElse&lt;/code&gt;).
To put it differently, if possible, try to avoid using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;isPresent&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;5-orelsenull&quot;&gt;5. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;orElse(null)&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;orElse&lt;/code&gt; method on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; class can be used to provide a fallback value when the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; is empty.
In some situations you might want to continue working with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; references.
Let’s say that you already have some code or use a library that expects to receive a nullable reference and can deal with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; case.
In these situations we can let the fallback value be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// findUserById returns an Optional&amp;lt;User&amp;gt;&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;User&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;user&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;findUserById&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1L&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;orElse&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Other than that, I would try to avoid &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;orElse(null)&lt;/code&gt;.
Usually there’s a more elegant way to solve the problem.
Imagine that you used &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;orElse(null)&lt;/code&gt; and now have a reference to a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;User&lt;/code&gt; object that might be null.
Whenever you start to call any methods on the user, you would first have to check that the reference is not null.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;User&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;user&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;findUserById&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1L&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;orElse&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;user&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;// do something with the user&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In my humble opinion, using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ifPresent&lt;/code&gt; in this case would be better.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;Optional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;User&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;user&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;findUserById&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1L&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;user&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;ifPresent&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;cm&quot;&gt;/* lambda expression or method reference */&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;6-collections-wrapped-with-an-optional&quot;&gt;6. Collections wrapped with an Optional&lt;/h2&gt;

&lt;p&gt;We’ve learned so far that Optionals can be used to model the absence of a result from a computation.
Let’s say we have a method that returns a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List&lt;/code&gt; of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;User&lt;/code&gt; objects from a database.
Let’s also introduce a limitation that in some situations the database might not contain any users.
One might think that this special case can be modelled with an Optional.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Optional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;List&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;User&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;fetchUsersFromDatabase&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Callers of the method can see from the return type that the value might be missing and can handle the special case.
&lt;em&gt;Pretty nifty, eh?&lt;/em&gt;
No.
Not really.
Don’t do that!&lt;/p&gt;

&lt;p&gt;This is an example of going too far with Optionals.
Absence of values can also be represented with an empty collection.
Introducing Optionals to the mix only complicates things.
What you would end up is a container inside a container, like a &lt;a href=&quot;https://en.wikipedia.org/wiki/Matryoshka_doll&quot;&gt;Matryoshka doll&lt;/a&gt;.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-08-12-misusing-java-optional/russian-doll.jpg&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Container inside another container. Image by &lt;a href=&quot;https://pixabay.com/photos/russian-dolls-babuschka-matruschka-1861410/&quot;&gt;Monika Schröder&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;The book &lt;a href=&quot;https://amzn.to/31uiEnG&quot; title=&quot;Effective Java 3rd Edition&quot;&gt;Effective Java&lt;/a&gt; mentions the following:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;Container types, including collections, maps, streams, arrays, and optionals should not be wrapped in optionals.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;7-optional-as-an-element-in-a-collection&quot;&gt;7. Optional as an element in a collection&lt;/h2&gt;

&lt;p&gt;We just looked at that there’s no real benefit in wrapping a collection type with an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt;.
What about the other way around?
What if we have a collection of Optional types?&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;List&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Optional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Cat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;users&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;...&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// fetch cats&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;When we have a list of cat objects, most likely we’re going to iterate trough them and do something with each element.
But if each element is an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt;, we would first have to unwrap it and process it only when it is present.
A much simpler approach would be to not include Optionals in collection types at all and keep our collections clean of &lt;a href=&quot;https://en.wikipedia.org/wiki/Schr%C3%B6dinger%27s_cat&quot;&gt;Schrödinger’s cats&lt;/a&gt;—cats that are simultaneously both there and not until we check for their presence.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-08-12-misusing-java-optional/cat.jpg&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Schrödinger&apos;s cat. Image by &lt;a href=&quot;https://pixabay.com/photos/physics-schr%C3%B6dinger-s-cat-3864569/&quot;&gt;Gerd Altmann&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;I’m going to reference &lt;a href=&quot;https://amzn.to/31uiEnG&quot; title=&quot;Effective Java 3rd Edition&quot;&gt;Effective Java&lt;/a&gt; for the last time in this post.&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;… it is almost never appropriate to use an optional as a key, value, or element in a collection or array&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;The introduction of Optionals to Java &lt;a href=&quot;https://blog.developer.atlassian.com/optional-broken/&quot;&gt;got some flak from the community&lt;/a&gt;.
&lt;a href=&quot;https://medium.com/@bgourlie/java-8-s-new-optional-type-is-worthless-448a00fa672d&quot;&gt;Some might think that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; is a first-class option type&lt;/a&gt; integrated into the language.
It does not help that &lt;a href=&quot;https://blog.codefx.org/java/dev/design-optional&quot;&gt;during the design phase&lt;/a&gt; there were different opinions about what &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; should and shouldn’t be.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Optional.html&quot;&gt;From JavaSE 11 documentation&lt;/a&gt; we can read that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; is primarily intended for use as a method return type. In addition, Java language architect Brian Goetz wrote the following in a &lt;a href=&quot;https://stackoverflow.com/a/26328555/2928051&quot;&gt;Stack Overflow answer&lt;/a&gt;.&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;Of course, people will do what they want. But we did have a clear intention when adding this feature, and it was not to be a general purpose Maybe type, as much as many people would have liked us to do so. Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent “no result”, and using null for such was overwhelmingly likely to cause errors.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The main takeaway form this post should be that Optionals don’t replace nulls and &lt;a href=&quot;https://www.codeproject.com/Articles/787668/Why-We-Should-Love-null&quot;&gt;don’t provide 100% null safety&lt;/a&gt;.
Going far and beyond, trying to avoid nulls by using Optionals in places where it was not designed to be used could result in some cumbersome looking code.
Your milage may vary though.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/misusing-java-optional/&quot;&gt;Misusing Java's Optional type&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on October 05, 2019.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[How to Invalidate JSON Web Tokens]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/invalidate-jwt/" />
  <id>https://blog.indrek.io/articles/invalidate-jwt</id>
  <updated>2019-07-17 18:56:18 +0300T00:00:00-00:00</updated>
  <published>2019-07-17T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;The most common use case for &lt;a href=&quot;https://jwt.io/introduction/&quot; title=&quot;Introduction to JSON Web Tokens&quot;&gt;JSON Web Tokens&lt;/a&gt; (&lt;strong&gt;JWT&lt;/strong&gt;) is authorization.
Once a user has provided his/her credentials, the server issues a JWT that the user will have to include in each subsequent request.
&lt;a href=&quot;https://www.jbspeakr.cc/purpose-jwt-stateless-authentication/&quot; title=&quot;The Purpose of JWT: Stateless Authentication&quot;&gt;The benefit of JWTs is that they’re stateless&lt;/a&gt;.
We don’t have to query a central database to validate the token.
As long as the signature is correct and the token hasn’t expired, we can trust it and allow the user to access the restricted resource.
This is good when you wish to reduce the load on your database but it makes invalidating an existing non-expired token difficult.
Let’s say a user has logged out, how do we make sure the token cannot be used anymore?&lt;/p&gt;

&lt;h2 id=&quot;storing-tokens-in-a-database&quot;&gt;Storing tokens in a database&lt;/h2&gt;

&lt;p&gt;The most obvious approach would be to store the token in a database.
We can check which tokens are valid and which ones have been revoked.
But this defeats the entire purpose of using JWTs in my opinion.
Essentially, we would be keeping a list of all issued tokens, making them stateful.
There &lt;em&gt;has to be&lt;/em&gt; a central authentication manager that would have to check every incoming request against the list of stored tokens.&lt;/p&gt;

&lt;h2 id=&quot;delete-token-from-the-client&quot;&gt;Delete token from the client&lt;/h2&gt;

&lt;p&gt;When a user logs out, the client app should delete the token from its memory.
This would stop the client from being able to make authenticated requests.
But if the token is still valid and somebody else has access to it, the token could still be used.&lt;/p&gt;

&lt;h2 id=&quot;short-token-lifetime&quot;&gt;Short token lifetime&lt;/h2&gt;

&lt;p&gt;Let the tokens expire quickly.
Depending on the application, it could be several minutes or half an hour.
When the client deletes its token, there’s a short window of time where it can still be used.
Deleting the token from the client and having short token lifetimes would not require major modifications on the server side. But short token lifetimes would mean that the user is constantly being logged out because the token has expired.&lt;/p&gt;

&lt;h2 id=&quot;rotate-tokens&quot;&gt;Rotate tokens&lt;/h2&gt;

&lt;p&gt;It is possible to introduce a concept of refresh tokens.
When the user logs in, we can provide them with a JWT and a refresh token.
The refresh token will be stored in a database.
For authenticated requests, the client can use the JWT but when the token expires (or is about to expire), let the client make a request with the refresh token in exchange for a new JWT.
This way you would only have to hit the database when a user logs in or asks for a new JWT.
When the user logs out, you would need to invalidate the stored refresh token.
Otherwise somebody listening in on the connection could still get new JWTs even though the user had logged out.&lt;/p&gt;

&lt;h2 id=&quot;create-a-jwt-blacklist&quot;&gt;Create a JWT blacklist.&lt;/h2&gt;

&lt;p&gt;Depending on the expiration time, when the client deletes its token, it might still be valid for some time.
If the token lifetime is short, it might not be an issue, but if you still wish that the token is invalidated immediately, you could create a token blacklist.
When the server receives a logout request, take the JWT from the request and store it in an in-memory database.
For each authenticated request you would need to check your in-memory database to see if the token has been invalidated.
To keep the search space small, you could remove tokens from the blacklist which have already expired.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;In its core, JWTs cannot be edited once they have been issued.
If you wish to invalidate them, you have to start keeping some state.
Ask yourself, why are you using JWTs.
If you really need to invalidate them, perhaps using regular stateful authentication is a simpler approach?&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/invalidate-jwt/&quot;&gt;How to Invalidate JSON Web Tokens&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on July 17, 2019.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[Rock-solid Consumer Driven Contract Testing Workflow With Pact]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/pact-workflow/" />
  <id>https://blog.indrek.io/articles/pact-workflow</id>
  <updated>2019-06-27 18:56:18 +0300T00:00:00-00:00</updated>
  <published>2019-06-27T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;In the previous post we had a look at &lt;a href=&quot;https://blog.indrek.io/articles/consumer-driven-contract-testing/&quot; title=&quot;Consumer Driven Contract Testing with Pact&quot;&gt;Consumer driven contract testing with Pact&lt;/a&gt;.
Consumer driven contract testing is a method of verifying that services (e.g. API consumer and an API provider) speak the same language.
By providing examples, API consumers set expectations on providers on how they should behave on specific inputs.
A set of expectations forms a contract that’s produced by consumers and is verified by providers in isolation.
Pact is a contract testing tool that helps us implement these tests.&lt;/p&gt;

&lt;p&gt;To make the most out of Pact, we should put some time into automation.
This post will cover the steps you need to take to create a rock-solid workflow that helps you to reap the benefits of consumer driven contract testing.
It is advised that you know the basics of &lt;a href=&quot;https://blog.indrek.io/articles/consumer-driven-contract-testing/&quot; title=&quot;Consumer Driven Contract Testing with Pact&quot;&gt;consumer driven contract testing with Pact&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;sharing-pacts&quot;&gt;Sharing pacts&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/consumer-driven-contract-testing/&quot; title=&quot;Consumer Driven Contract Testing with Pact&quot;&gt;In an earlier post&lt;/a&gt;, we saw that a consumer of an API is responsible for setting expectations and generating the pact file.
Once that’s done, the provider should have access to it in order to verify its validity.
How can this be done?
Ideally, we should automate it somehow.
Otherwise, it’s very easy to forget to do it.
A change in the contract might never be picked up by a provider, defeating the entire purpose of consumer driven contract testing.&lt;/p&gt;

&lt;p&gt;Pact files can be &lt;a href=&quot;https://docs.pact.io/getting_started/sharing_pacts#alternative-approaches&quot;&gt;shared in multiple ways&lt;/a&gt;.
If our consumer and provider lived in the same VCS repository, pact files could be stored there as well.
Once the consumer CI build has finished, it could commit the generated pact files into the same repository.
A similar strategy could work also when both projects have their dedicated repository.
Once the consumer CI build has generated the pact file, an extra step can be added to the build process that commits the files to the provider’s repository.&lt;/p&gt;

&lt;p&gt;Another approach is to use an &lt;a href=&quot;https://jfrog.com/knowledge-base/what-is-an-artifact-repository/&quot; title=&quot;What is an artifact repository?&quot;&gt;artifact repository&lt;/a&gt;.
In addition to storing the consumer application as a build artifact, the CI build could also publish pacts as build artifacts.
On the provider side, you would need to figure out how to construct the URL that points to the latest pact file in your artifact repository to access it.&lt;/p&gt;

&lt;p&gt;Additionally, a consumer CI build could store the generated pacts on a shared storage that’s accessible to the provider build.
But if you want to take the most out of Pact, the recommended way to share pact files is to use &lt;a href=&quot;https://github.com/pact-foundation/pact_broker&quot;&gt;Pact Broker&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;pact-broker&quot;&gt;Pact Broker&lt;/h2&gt;

&lt;p&gt;The recommended way to share pacts is to use the &lt;a href=&quot;https://github.com/pact-foundation/pact_broker&quot;&gt;Pact Broker&lt;/a&gt;.
After the consumer has successfully generated a pact file, it should publish it to the broker.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-06-10-pact-workflow/publish-pact.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Generated pact file is published to the Pact Broker&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Although, sharing pacts via network file sharing or VCS repositories gets the job done, you are generally only verifying that the head versions of your services play nicely with each other.
To be able to &lt;a href=&quot;https://www.rea-group.com/blog/enter-the-pact-matrix-or-how-to-decouple-the-release-cycles-of-your-microservices/&quot; title=&quot;Enter the Pact Matrix. Or, how to decouple the release cycles of your microservices&quot;&gt;deploy services independently&lt;/a&gt;, we need to also know whether a change to a service is compatible with its collaborators that are in our production environment.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-06-10-pact-workflow/recap.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Verifying whether the head versions of Billing and Customer service play nicely with each other&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;If the latest version of Billing service generates a pact file and the latest version of Customer service verifies it, we know that we can safely deploy these two services to production together.
But if we would like to deploy only the head version of Billing service independently, we may run into the risk of breaking the API between billing and customer services because the latest version of billing has never been verified against the production version of customer service.&lt;/p&gt;

&lt;h2 id=&quot;pact-matrix&quot;&gt;Pact Matrix&lt;/h2&gt;

&lt;p&gt;Here’s where the Pact Broker really starts to shine.
In addition to being a tool to share pact files, it will keep track of your &lt;a href=&quot;https://docs.pact.io/getting_started/versioning_in_the_pact_broker&quot; title=&quot;Versioning in the Pact Broker&quot;&gt;consumer/provider versions and pact verifications&lt;/a&gt; between them in what is called &lt;a href=&quot;https://github.com/pact-foundation/pact_broker/wiki/Overview#the-matrix&quot;&gt;“The Matrix”&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The following is an example state in the Pact Matrix.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt;Customer (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;latest&lt;/code&gt;)&lt;/th&gt;
      &lt;th&gt;Customer (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prod&lt;/code&gt;)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Billing (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;latest&lt;/code&gt;)&lt;/td&gt;
      &lt;td&gt;✅&lt;/td&gt;
      &lt;td&gt;?&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Billing (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prod&lt;/code&gt;)&lt;/td&gt;
      &lt;td&gt;?&lt;/td&gt;
      &lt;td&gt;✅&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Here we can see that the latest versions of Billing and Customer service are compatible with each other.
Additionally, there’s a successful pact verification between the production versions as well.&lt;/p&gt;

&lt;p&gt;In order for new entries to be added to the matrix, every time the Billing service changes, it should publish a new pact to the broker.
Similarly, for every change to the Customer service, its CI build should fetch the latest pact and verify whether it is compatible with the latest changes in Billing.
Once the verification passes, Customer service’s CI build should then fetch the pact published by the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prod&lt;/code&gt; version of Billing service to ensure that the latest changes in the Customer service are &lt;a href=&quot;https://en.wikipedia.org/wiki/Backward_compatibility&quot; title=&quot;Backward compatibility&quot;&gt;&lt;em&gt;backwards compatible&lt;/em&gt;&lt;/a&gt; with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prod&lt;/code&gt; billing service.
This gives you immediate feedback whether you’ve introduced a breaking change.&lt;/p&gt;

&lt;p&gt;The following table illustrates the state where the latest version of Customer service is not compatible with the production version of Billing service.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt;Customer (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;latest&lt;/code&gt;)&lt;/th&gt;
      &lt;th&gt;Customer (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prod&lt;/code&gt;)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Billing (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;latest&lt;/code&gt;)&lt;/td&gt;
      &lt;td&gt;✅&lt;/td&gt;
      &lt;td&gt;?&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Billing (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prod&lt;/code&gt;)&lt;/td&gt;
      &lt;td&gt;❌&lt;/td&gt;
      &lt;td&gt;✅&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Essentially, it would be unwise to go ahead and deploy the latest Customer service to production since it would break the contract between Billing and Customer services.&lt;/p&gt;

&lt;p&gt;Similarly, when we’d like to deploy the latest Billing service to prod, we’re unsure whether we’re introducing a breaking change.
We would need to first check-out the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prod&lt;/code&gt; version of Customer service and verify it against the latest Billing service.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt;Customer (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;latest&lt;/code&gt;)&lt;/th&gt;
      &lt;th&gt;Customer (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prod&lt;/code&gt;)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Billing (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;latest&lt;/code&gt;)&lt;/td&gt;
      &lt;td&gt;✅&lt;/td&gt;
      &lt;td&gt;✅&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Billing (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prod&lt;/code&gt;)&lt;/td&gt;
      &lt;td&gt;❌&lt;/td&gt;
      &lt;td&gt;✅&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;After running the verification, we can see from the Pact Matrix that latest Billing service is compatible with production version of Customer service.
No breaking changes were introduced and we can feel free to deploy our changes in Billing service to production.&lt;/p&gt;

&lt;p&gt;Later we’ll have a look at a workflow that ensures pacts are published and verified continuously.&lt;/p&gt;

&lt;h3 id=&quot;how-does-pact-know-what-is-deployed-to-production&quot;&gt;How does pact know what is deployed to production?&lt;/h3&gt;

&lt;p&gt;In the previous examples the Pact Broker knew what version of Billing and Customer service was deployed to the production environment.
&lt;em&gt;How did it know that?
What integrations have to be put in place for that to happen?&lt;/em&gt;
The answer is quite simple.
Pact Broker comes with a set of command-line tools that you can use to alter its state.
The feature we’re currently interested in is &lt;a href=&quot;https://github.com/pact-foundation/pact_broker/wiki/Using-tags&quot; title=&quot;Using tag&quot;&gt;tagging&lt;/a&gt;.
After a successful deploy to a production environment, we can &lt;em&gt;tag&lt;/em&gt; the service and version with whatever we like.
In the previous example, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prod&lt;/code&gt; was used as the name for the tag.&lt;/p&gt;

&lt;h3 id=&quot;can-i-deploy-to-production&quot;&gt;Can I deploy to production?&lt;/h3&gt;

&lt;p&gt;We have the Pact Matrix that knows what versions of services play nicely with each other.
We’ve also tagged the versions that have been deployed to our production environment.
Therefore we’re able to make the decision whether it is okay to deploy a specific version of a service to production.
Pact Broker comes with a command-line tool called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;can-i-deploy&lt;/code&gt; that can help us automate this check.&lt;/p&gt;

&lt;p&gt;Before deploying the Billing service, we should run the following command to ensure that version &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bfa3b32&lt;/code&gt; of Billing service can be deployed together with other services in the production environment.
Here I’ve used the abbreviated git commit hash as the version number &lt;a href=&quot;https://github.com/pact-foundation/pact_broker/wiki/Pacticipant-version-numbers&quot; title=&quot;Pacticipant version numbers&quot;&gt;but that’s not strictly required and you could use a different versioning scheme&lt;/a&gt;.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ pact-broker can-i-deploy --pacticipant billing --version bfa3b32 --to prod
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;If there’s a successful verification between the production version of Customer service and the Billing service that’s about to be deployed, the command exits successfully and the deploy script can continue with the deployment.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Computer says yes \o/

CONSUMER         | C.VERSION | PROVIDER         | P.VERSION | SUCCESS?
-----------------|-----------|------------------|-----------|---------
billing          | bfa3b32   | customer         | a8261f9   | true     

All verification results are published and successful
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;If for some reason, the verification was unsuccessful, the command exits with a non-zero exit code.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Computer says no ¯\_(ツ)_/¯

CONSUMER         | C.VERSION | PROVIDER         | P.VERSION | SUCCESS?
-----------------|-----------|------------------|-----------|---------
billing          | bfa3b32   | customer         | a8261f9   | false   

One or more verifications have failed
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;dependencies-between-services&quot;&gt;Dependencies between services&lt;/h3&gt;

&lt;p&gt;Since Pact Broker records all consumer and provider pairs, it knows the dependencies between all of the services.
From the provider’s perspective, this is an extremely valuable information.
If a breaking change is made to an API, it is immediately clear which consumers and which endpoints were broken.
This allows the provider team to plan ahead and evolve their API by gradually introducing backwards compatible changes and letting API consumers catch up.
Old API clients can be phased out and replaced with newer ones.
Unused and deprecated endpoints can be safely deleted since no consumer has declared their interest in them.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-02-25-consumer-driven-contract-testing/network_diagram.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;&lt;a href=&quot;https://github.com/pact-foundation/pact_broker#network-diagram&quot;&gt;Example network diagram displayed by Pact Broker&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Dependency information can be used in other clever ways as well.
For example, let’s say, you’ve decided to control communication on the network level with firewall rules.
With some effort, it should be possible to configure network policies based on the information that’s present in Pact Broker.
The same information could also be used to autogenerate architecture diagrams.&lt;/p&gt;

&lt;p&gt;It must be said that it does not come for free.
Trust must exists between the teams that decide to use Pact and consumer driven contract testing.
If some parties are not on board, it might be difficult to reap all of the benefits that Pact provides.&lt;/p&gt;

&lt;h2 id=&quot;continuous-pact-verification-workflow&quot;&gt;Continuous pact verification workflow&lt;/h2&gt;

&lt;p&gt;So far we’ve seen that there are several steps that you must follow in order to take full advantage of Pact.
Therefore it would be wise to set up an automated workflow that makes sure you won’t miss any of them.
The following is a workflow that makes use of all of the Pact features we’ve covered so far.
You might have to modify some steps to meet your team/organisation requirements.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Billing service’s CI build generates a new pact file and runs local tests against it.
If they pass, the pact is published to the broker.&lt;/li&gt;
&lt;/ul&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-06-10-pact-workflow/billing-ci.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Billing service&apos;s CI build&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Using &lt;a href=&quot;https://github.com/pact-foundation/pact_broker/wiki/Webhooks&quot; title=&quot;Webhooks&quot;&gt;webhooks&lt;/a&gt;, Pact Broker is configured to trigger Customer service’s CI build when there’s a change detected in the pact published by Billing service.
If no changes were detected, the new version of the consumer is &lt;em&gt;pre-verfied&lt;/em&gt; to work with the same providers as the previous version did.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Customer service’s CI build is configured to verify the latest consumer pacts.
Once that’s successful, it will also fetch and verify pacts that that were published by its production consumers.
Verification results are published to Pact Broker, incrementally filling the compatibility matrix.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-06-10-pact-workflow/customer-ci.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Customer service&apos;s CI build&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Customer and Billing service deploy scripts are configured with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;can-i-deploy&lt;/code&gt; tool to verify whether it is okay to proceed with the deployment.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;After the deployment has finished successfully, all deployment scripts have to tag the deployed version in the Pact Broker with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prod&lt;/code&gt; tag.
This ensures that services can be deployed independently with the help of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;can-i-deploy&lt;/code&gt;.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Pact is a powerful tool that helps you implement consumer driven contract testing.
In order to make the most out of Pact, it is strongly advised that you start using Pact Broker as well.
Putting in some effort to implement the steps presented in this post and integrating Pact Broker with your CI/CD pipeline will greatly help you in deploying your services independently and avoiding breaking changes.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/pact-workflow/&quot;&gt;Rock-solid Consumer Driven Contract Testing Workflow With Pact&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on June 27, 2019.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[Consumer Driven Contract Testing with Pact]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/consumer-driven-contract-testing/" />
  <id>https://blog.indrek.io/articles/consumer-driven-contract-testing</id>
  <updated>2019-05-29 18:56:18 +0300T00:00:00-00:00</updated>
  <published>2019-05-29T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;In the previous post, we had a look at &lt;a href=&quot;https://blog.indrek.io/articles/challenges-of-testing-microservices/&quot; title=&quot;The Challenges of Testing Microservices&quot;&gt;different ways of testing microservices&lt;/a&gt; and learned that &lt;em&gt;classical&lt;/em&gt; testing methods might not work well in distributed environments.&lt;/p&gt;

&lt;p&gt;To recap, testing services in isolation with mocks is fast and cheap but not reliable.
Once we change the API of a service, we have to make sure we update the tests in all of its clients.
Essentially, service mocks only assume how the real counterpart should behave and the only thing that verifies this assumption is us, humans.
Therefore it’s very easy for mistakes to creep in.&lt;/p&gt;

&lt;p&gt;Spinning up two services to test the integration between them seems like the next logical step.
As we saw in &lt;a href=&quot;https://blog.indrek.io/articles/challenges-of-testing-microservices/&quot; title=&quot;The Challenges of Testing Microservices&quot;&gt;the previous post&lt;/a&gt;, this approach is definitely more reliable compared to testing with mocks but it’s also slower and takes more effort to maintain.
A service can have many clients, increasing the time it takes to verify a single change.
In addition, if we want to deploy our services independently of others, we have to test for backwards compatibility with services already deployed to production.
The same is true if we were to spin up all of our services and performed end-to-end testing.
Lots moving parts can make our tests flaky and we run the risk of becoming a victim of &lt;a href=&quot;https://en.wikibooks.org/wiki/Professionalism/Diane_Vaughan_and_the_normalization_of_deviance&quot; title=&quot;Professionalism/Diane Vaughan and the normalization of deviance&quot;&gt;&lt;em&gt;normalization of deviance&lt;/em&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This post is about a consumer driven contract testing and how it promises to alleviate some of the &lt;a href=&quot;https://blog.indrek.io/articles/challenges-of-testing-microservices/&quot; title=&quot;The Challenges of Testing Microservices&quot;&gt;difficulties in testing microservices&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;consumer-driven-contract-testing&quot;&gt;Consumer Driven Contract Testing&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;Consumer driven contract testing&lt;/em&gt; is a method of verifying that services (e.g. API consumer and an API provider) speak the same language.
By providing examples, API consumers set expectations on providers on how they should behave on specific inputs.
A set of expectations forms a contract that’s produced by consumers and is shared with providers.&lt;/p&gt;

&lt;p&gt;Contract obligations are verified by providers with tests that can be run in isolation, without having to set up integration testing environments.
That lets them evolve independently and get immediate feedback during build time when they’ve broken any of their API consumers.
Contract testing can be used anywhere where you have two services that need to communicate with each other but becomes especially useful in environments with many services (e.g. microservice architecture).&lt;/p&gt;

&lt;h2 id=&quot;pact&quot;&gt;Pact&lt;/h2&gt;

&lt;p&gt;Pact is a &lt;em&gt;consumer driven contract testing&lt;/em&gt; tool originally written by a development team at realestate.com.au.
By enabling services to enter into a contract on how to communicate with each other, Pact plays the role of an authority that ensures both sides honour the agreement.
In Pact terminology, a contract is referred to as a &lt;em&gt;pact&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;What makes it &lt;em&gt;consumer-driven&lt;/em&gt; is the fact that a client of an API has to first describe how the API provider should behave.
In &lt;a href=&quot;https://blog.indrek.io/articles/challenges-of-testing-microservices/&quot; title=&quot;The Challenges of Testing Microservices&quot;&gt;the previous post&lt;/a&gt; we looked at an example scenario where we had a Billing service and a Customer service.
To recap, the Customer service provides an API that the Billing service needs to consume in order to perform billing.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-05-23-cdct/recap.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Billing service asking for customer information from Customer service&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Let’s have a look at how to use consumer driven contract testing in this scenario.&lt;/p&gt;

&lt;h3 id=&quot;setting-expectations-and-generating-a-pact-file&quot;&gt;Setting expectations and generating a pact file&lt;/h3&gt;

&lt;p&gt;Since the Billing service is consuming an API, it should start setting expectations on the Customer service.
Contract expectations are set by examples and to do that, we need to write some code.
Using a &lt;a href=&quot;https://en.wikipedia.org/wiki/Domain-specific_language&quot; title=&quot;Domain-specific language&quot;&gt;DSL&lt;/a&gt; we need to define the interactions that should happen between the two services.
For instance, when the Billing service sends an HTTP GET request to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/customers/12&lt;/code&gt;, the Customer service should respond with HTTP 200 and with the customer data belonging to the given customer.&lt;/p&gt;

&lt;p&gt;Now that the interactions between Billing and Customer service have been defined, we need to exercise Billing service’s code to verify that it actually makes the requests that were defined as part of the contract.
To do that, we need to write what essentially look like regular unit tests that test the code that is responsible for communicating with the Customer service.
But instead of sending requests to a real Customer service (i.e. an integration test), Pact starts up a mock HTTP server that intercepts all traffic and records it.&lt;/p&gt;

&lt;p&gt;If an incoming request is found in the set of interactions we defined previously, the mock server will respond accordingly.
On the other hand, when the Billing service makes a request that is either slightly different or completely missing, the test will fail, indicating that the consumer did something that was not defined in the contract.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-05-23-cdct/create-pact.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;A pact file is generated after Billing service sets expectations and successfully runs tests&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;A collection of these interactions are encoded into a JSON document called a pact file.&lt;/p&gt;

&lt;div class=&quot;language-json highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;consumer&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;billing&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;provider&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;customer&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;interactions&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;description&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;fetch customer&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;request&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;method&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;GET&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;path&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;/customers/12&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;response&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;status&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;headers&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
          &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;Content-Type&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;application/json&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;body&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
          &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;customerId&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
          &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;John Doe&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;pact-verification&quot;&gt;Pact verification&lt;/h3&gt;

&lt;p&gt;When a consumer of an API has defined a contract and ensured that it complies with it, it is time for the provider side of an API to verify it.
The goal of the verification process is to understand whether the provider behaves as described in the contract.
To do that we need to start up the provider and give it a pact file.
Pact framework starts up an HTTP client that reads all the requests from the pact file and plays them against a running instance of the Customer service.
Then it observes how the Customer service behaves and compares the HTTP responses to the ones in the pact file.
If they don’t match, the verification will fail and Customer service is deemed not compatible with Billing service.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-05-23-cdct/verification.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Pact verifies whether Customer service behaves as defined in the contract&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Looking at the bigger picture, Pact allowed us to verify whether Customer and Billing service speak the same language without having to spin up both services and writing classical integration tests.
This greatly improves the autonomy of API providers.
Teams responsible of services don’t have to explicitly track how other services consume them.
If one of these tests break, the provider team is immediately aware which consumers are impacted.
Now they can start a discussion with the consumer team around whether to create a breaking change or come up with a solution that is backwards compatible.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;https://amzn.to/2Ej0ZGq&quot; title=&quot;Building Microservices: Designing Fine-Grained Systems&quot;&gt;Building Microservices&lt;/a&gt;, the author Sam Newman had the following to say about consumer-driven contracts.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;They [CDCs] become the codification of a set of discussions about what a service API should look like, and when they break, they become a trigger point to have conversations about how that API should evolve.&lt;/p&gt;

  &lt;footer&gt;&lt;strong&gt;Sam Newman&lt;/strong&gt; &amp;mdash; &lt;a href=&quot;https://amzn.to/2Ej0ZGq&quot;&gt;Building Microservices&lt;/a&gt;&lt;/footer&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Consumer driven contract testing helps us decouple consumers and providers in space and time.
We don’t have to spin up both services and run integration tests anymore.
We don’t even have to care about their version numbers.
As long as both sides honour the contract, we can be sure that they speak the same language and we haven’t introduced any breaking changes.&lt;/p&gt;

&lt;p&gt;CDCT provides teams more autonomy in how they evolve their API.
When the contract has been breached, teams are immediately aware of it and can start a discussion around how to solve the issues before anything is deployed to production.&lt;/p&gt;

&lt;p&gt;This post covered CDCT on a high level and intentionally left out implementation details.
&lt;a href=&quot;https://blog.indrek.io/articles/pact-workflow/&quot; title=&quot;Rock-solid Consumer Driven Contract Testing Workflow With Pact&quot;&gt;In the next post we’re going to look at how to build a rock-solid consumer driven contract testing workflow with Pact&lt;/a&gt; that helps you remain backwards compatible, automatically find out when contract verification fails and stop you from deploying to production when there’s an incompatibility between consumers and providers.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/consumer-driven-contract-testing/&quot;&gt;Consumer Driven Contract Testing with Pact&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on May 29, 2019.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[The Challenges of Testing Microservices]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/challenges-of-testing-microservices/" />
  <id>https://blog.indrek.io/articles/challenges-of-testing-microservices</id>
  <updated>2019-04-28 18:56:18 +0300T00:00:00-00:00</updated>
  <published>2019-04-28T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;When looking at many of the leading software engineering conferences out there, you’ll immediately see that &lt;em&gt;microservices&lt;/em&gt; are a topic that’s discussed everywhere.
Entire tracks are dedicated for it.
Tools and products are being built to manage them.
There’s definitely &lt;a href=&quot;https://dzone.com/articles/benefits-amp-examples-of-microservices-architectur&quot; title=&quot;Benefits of Microservices Architecture Implementation&quot;&gt;benefits to building your software using microservices&lt;/a&gt;.
But there’s no question that they &lt;a href=&quot;https://dzone.com/articles/challenges-in-implementing-microservices&quot;&gt;introduces a new set of challenges&lt;/a&gt;, one of them being testing.&lt;/p&gt;

&lt;h2 id=&quot;story-time&quot;&gt;Story time&lt;/h2&gt;

&lt;p&gt;To illustrate the difficulties in testing microservices, I’m going to tell you a fictional story.
Meet our heroes, &lt;a href=&quot;https://en.wikipedia.org/wiki/Alice_and_Bob&quot;&gt;Alice and Bob&lt;/a&gt;, who are predominantly known for being the protagonists in many cryptography examples.
In our alternative universe, they got fed up of sending and receiving encrypted messages to each other.
After careful consideration, they became software engineers and with all the hype around microservices, they’ve decided to ride the bandwagon.&lt;/p&gt;

&lt;p&gt;Alice was responsible for creating &lt;em&gt;the Billing service&lt;/em&gt;.
Bob was tasked with building &lt;em&gt;the Customer service&lt;/em&gt;.
Billing service needs to access customer information to bill them.
To do that, it queries the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/customers/{id}&lt;/code&gt; HTTP endpoint.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-04-20-challenges-of-testing-microservices/overview.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Billing services queries Customer service in order to access customer information&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;One evening Bob discovered that the API response payload had a typo.
Instead of returning &lt;a href=&quot;https://kathleenwcurry.wordpress.com/2015/09/08/easily-confused-words-costumer-vs-customer/&quot; title=&quot;Easily Confused Words: Costumer vs. Customer&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;costumerId&lt;/code&gt;, it should’ve been &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;customerId&lt;/code&gt;&lt;/a&gt;.
Being meticulous, Bob decided to immediately fix the humorous error and call it a day.&lt;/p&gt;

&lt;p&gt;The next morning Bob was confronted by Alice.
“You broke the Billing service!” she said.
Suddenly Bob realised, that he never tested the output of customer service with a running instance of the Billing service.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-04-20-challenges-of-testing-microservices/broken.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Billing service didn&apos;t like the change in the API&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h2 id=&quot;testing&quot;&gt;Testing&lt;/h2&gt;

&lt;p&gt;Why didn’t Customer service’s tests catch this error?
Turns out they did.
Bob had created tests that verified the response of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/customers/{id}&lt;/code&gt; endpoint.
They started to fail after the payload was changed but tests were fixed immediately.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-04-20-challenges-of-testing-microservices/failed-test.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Tests started to fail but were immediately fixed&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Essentially, tests verified how the API should be consumed but not how the Billing service consumed it.
These kind of tests are cheap to maintain and fast to run.
If they fail, they pinpoint the underlying cause extremely well.
On the other hand, they’re not trustworthy when it comes to testing integrations.
If the API changes, it’s not immediately clear, whether API clients still continue to work.&lt;/p&gt;

&lt;p&gt;Conversely, the same is true on the Billing service side.
It uses a mock Customer service that responds with dummy data.
The problem with tests that mock dependencies is that they make assumptions on how the real counterpart behaves.
Unfortunately there’s nothing there to actually verify this assumption.
Once the dependency changes, the assumption is not valid anymore.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-04-20-challenges-of-testing-microservices/testing-with-mocks.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Mocks aren&apos;t updated automatically, when the real counterpart is modified&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Having only two services—Customer and Billing—is a fairly trivial example.
Bob should’ve known, that Billing service uses Customer service.
But in a larger system, perhaps with hundreds of services, it might not be immediately clear who the consumers of an API are.&lt;/p&gt;

&lt;h2 id=&quot;integration-testing&quot;&gt;Integration testing&lt;/h2&gt;

&lt;p&gt;Testing Billing and Customer services together seems like an integration problem, right?
Spinning up both services and exercising the communication between them should’ve caught the integration error.
Unfortunately Alice and Bob didn’t have anything like that set up.&lt;/p&gt;

&lt;p&gt;Integration testing was considered but in the end it was decided not to implement them.
It was not clear how well they would scale if the number of services is increased.
Classical integration testing works well in environments with fewer components.
Modern microservice architectures, on the other hand, have many moving parts.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-02-25-consumer-driven-contract-testing/architecture.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Modern architecture has evolved to have more moving parts. Image by &lt;a href=&quot;https://medium.com/@benorama/the-evolution-of-software-architecture-bd6ea674c477&quot;&gt;Benoit Hediard&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Setting up two services in a controlled environment and running the tests was deemed too costly, especially when a single service has to be tested together with multiple collaborators.
Turns out that &lt;em&gt;the Inventory service&lt;/em&gt; also consumes the API that Customer service provides.
The time it takes for a CI build to finish was also taken into account.
Integration tests are definitely slower than testing against mocked dependencies.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-04-20-challenges-of-testing-microservices/integration.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;In addition to verifying the compatibility of Customer and Billing service, Inventory service has to be taken into account as well&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Questions were also raised about independent deployability.
If version X of Billing service and version Y of Customer service were tested together, does it mean they have to be deployed together as well?
Alice and Bob wanted to avoid lock-step releases and wanted to deploy their services independently of others.
Therefore they would have to test for backwards compatibility with all services that are already deployed to production, increasing the cost of integration testing even more.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-04-20-challenges-of-testing-microservices/backwards-compatibility.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Independent release cycle requires to test for backwards compatibility between the collaborators that are already deployed to production&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h2 id=&quot;testing-pyramid&quot;&gt;Testing pyramid&lt;/h2&gt;

&lt;p&gt;Now is probably a good time to look at the testing pyramid.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-02-25-consumer-driven-contract-testing/unit-testing-pyramid.jpg&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;&lt;a href=&quot;https://manifesto.co.uk/unit-testing-best-practices-java/&quot;&gt;Testing pyramid&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;It states that you should have a good balance of tests—unit tests, integration tests, end-to-end tests.
More focus should be put on the base of the pyramid.
Unit tests are the cheapest to create and maintain, they’re the most targeted and fastest to run.
Moving higher towards the top of the pyramid, the slower and more costly the tests become.&lt;/p&gt;

&lt;h2 id=&quot;end-to-end-testing&quot;&gt;End to end Testing&lt;/h2&gt;

&lt;p&gt;Setting up all services and exercising the application through public APIs could have caught the integration issue between Billing and Customer services.
Unfortunately, Alice and Bob referred to the testing pyramid and did not put much focus on these types of tests.&lt;/p&gt;

&lt;p&gt;The same limitations that are present in integration testing are present in end-to-end testing and are probably even more problematic.
Although, a single end-to-end test covers a big chunk of the system and can give us much confidence that the system is in working order, there are some notable disadvantages.&lt;/p&gt;

&lt;p&gt;Setting up the environment where to run end-to-end tests is costly.
Compared to integration testing, &lt;strong&gt;all other collaborators&lt;/strong&gt; would have to be configured and instantiated as well.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-04-20-challenges-of-testing-microservices/collaborators.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;In addition to Billing and Customer service, the system has other services as well&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Compared to other types of tests, these are definitely the slowest.
Developers would have to wait a significant amount of time before they get feedback on the status of their changes.
Although Alice and Bob deal with only a handful of services, in bigger systems it could take hours to eventually find out whether everything is okay.&lt;/p&gt;

&lt;p&gt;End-to-end testing also does not solve the issue of independent deployability.
If Bob wants to deploy the Customer service independently of others, he would have to set up another environment where the latest Billing service is tested with all other collaborators that are currently present in the production environment.
Increasing the number of services in play would make the situation even more complex and costly to operate.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-04-20-challenges-of-testing-microservices/prod-collaborators.png&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Testing for backwards compatibility with collaborators in production&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h2 id=&quot;flaky-tests&quot;&gt;Flaky tests&lt;/h2&gt;

&lt;p&gt;The more moving parts we have in our tests, the more brittle and flaky they are.
There’s a higher chance that they will fail not because of broken functionality but rather because of a network glitch for example.&lt;/p&gt;

&lt;p&gt;In his book, &lt;a href=&quot;https://amzn.to/2Ej0ZGq&quot;&gt;Building Microservices&lt;/a&gt;, &lt;a href=&quot;https://twitter.com/samnewman&quot;&gt;Sam Newman&lt;/a&gt; had the following to say about flaky tests.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Flaky tests are the enemy. When they fail, they don’t tell us much. We re-run our CI builds in the hope that they will pass again later, only to see check-ins pile up, and suddenly we find ourselves with a load of broken functionality.&lt;/p&gt;

  &lt;p&gt;When we detect flaky tests, it is essential that we do our best to remove them. Otherwise, we start to lose faith in a test suite that “always fails like that.” A test suite with flaky tests can become a victim of what &lt;a href=&quot;https://en.wikipedia.org/wiki/Diane_Vaughan&quot;&gt;Diane Vaughan&lt;/a&gt; calls the &lt;em&gt;normalization of deviance&lt;/em&gt;—the idea that over time we can become so accustomed to things being wrong that we start to accept them as being normal and not a problem.&lt;/p&gt;

  &lt;footer&gt;&lt;strong&gt;Sam Newman&lt;/strong&gt; &amp;mdash; &lt;a href=&quot;https://amzn.to/2Ej0ZGq&quot;&gt;Building Microservices&lt;/a&gt;&lt;/footer&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Diane_Vaughan&quot;&gt;Diane Vaughan&lt;/a&gt; is a sociologist and a professor at the Columbia University.
She coined the phrase &lt;a href=&quot;https://en.wikibooks.org/wiki/Professionalism/Diane_Vaughan_and_the_normalization_of_deviance&quot; title=&quot;Diane Vaughan and the normalization of deviance&quot;&gt;“normalization of deviance”&lt;/a&gt; in her book &lt;a href=&quot;https://amzn.to/2Q8AwAi&quot; title=&quot;The Challenger Launch Decision: Risky Technology, Culture, and Deviance at NASA&quot;&gt;The Challenger Launch Decision&lt;/a&gt;, where she analysed the processes inside NASA that eventually lead up to the &lt;a href=&quot;https://en.wikipedia.org/wiki/Space_Shuttle_Challenger_disaster&quot; title=&quot;Space Shuttle Challenger disaster&quot;&gt;Space Shuttle Challenger disaster&lt;/a&gt;. Over time an unsafe practice grew into something that was considered normal since it did not cause an immediate catastrophe. And then BOOM!&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2019-04-20-challenges-of-testing-microservices/challenger.jpg&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;January 28, 1986, Space Shuttle Challenger&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h2 id=&quot;manual-testing&quot;&gt;Manual Testing&lt;/h2&gt;

&lt;p&gt;What about manual testing?
If we only had a single client and a server, it might sound reasonable.
But if we’re dealing with several services, this approach becomes unpractical very quickly.&lt;/p&gt;

&lt;h2 id=&quot;solution&quot;&gt;Solution?&lt;/h2&gt;

&lt;p&gt;Testing services in isolation with stubs is quick and cheap but not trustworthy.
A change in a service requires to update all of its stubs that are used by its collaborators.
Since this is a manual step, it can be forgotten or mistakes can creep in.&lt;/p&gt;

&lt;p&gt;Integration testing sounds like a good solution.
Unfortunately that’s not cheap to maintain and fast to run compared to &lt;em&gt;testing in isolation&lt;/em&gt;.
In addition, to be able to deploy services independently, we would also have to test for backwards compatibility with services already deployed to production.
This can result in long build queues and slow feedback loops.
The same is true for end-to-end testing.&lt;/p&gt;

&lt;p&gt;Luckily, there’s a technique called &lt;a href=&quot;https://blog.indrek.io/articles/consumer-driven-contract-testing/&quot; title=&quot;Consumer Driven Contract Testing with Pact&quot;&gt;Consumer Driven Contract Testing (CDCT)&lt;/a&gt; that can fix it.
It’s like testing services in isolation but it guarantees that your stubs will never get out of date.
Feel free to read about &lt;a href=&quot;https://blog.indrek.io/articles/consumer-driven-contract-testing/&quot; title=&quot;Consumer Driven Contract Testing with Pact&quot;&gt;Consumer Driven Contract testing from the next post&lt;/a&gt;.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/challenges-of-testing-microservices/&quot;&gt;The Challenges of Testing Microservices&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on April 28, 2019.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[Serving React apps from Spring Boot]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/serving-react-apps-from-spring-boot/" />
  <id>https://blog.indrek.io/articles/serving-react-apps-from-spring-boot</id>
  <updated>2019-01-16 18:56:18 +0300T00:00:00-00:00</updated>
  <published>2019-01-16T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;Let’s say you’ve decided to create a web app with &lt;a href=&quot;https://reactjs.org/&quot; title=&quot;A JavaScript library for building user interfaces&quot;&gt;React&lt;/a&gt;.
You also want to build a back end so you’ve picked &lt;a href=&quot;https://github.com/spring-projects/spring-boot&quot;&gt;Spring Boot&lt;/a&gt; to do the job.
There are lots of ways to serve a React app in production.
In this post, we’re going to take a look at how to bundle the React app inside a Spring Boot back end.&lt;/p&gt;

&lt;h2 id=&quot;create-a-spring-boot-app&quot;&gt;Create a Spring Boot app&lt;/h2&gt;

&lt;p&gt;To get started, go to &lt;a href=&quot;https://start.spring.io/&quot; title=&quot;Spring Initializr&quot;&gt;start.spring.io&lt;/a&gt; and generate yourself a new Spring Boot app (or use an existing one if you wish).
Make sure you at least pick the Web dependency.
In this example, I’m using Gradle as my build tool.
You should have the following folder structure (or similar):&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;.
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── example
    │   │           └── demo
    │   │               └── DemoApplication.java
    │   └── resources
    │       ├── application.properties
    │       ├── static
    │       └── templates
    └── test
        └── java
            └── com
                └── example
                    └── demo
                        └── DemoApplicationTests.java
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;serving-static-content-with-spring-boot&quot;&gt;Serving static content with Spring Boot&lt;/h2&gt;

&lt;p&gt;To serve our front end web app from a Spring Boot jar file, we need to first understand how Spring Boot handles &lt;a href=&quot;https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content&quot;&gt;static content&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;By default, Spring Boot serves static content from a directory called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/static&lt;/code&gt; (or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/public&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/resources&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/META-INF/resources&lt;/code&gt;) in the classpath or from the root of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ServletContext&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For example, the following is an example &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;index.html&lt;/code&gt; that we will put into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;src/main/resources/static/&lt;/code&gt; folder.&lt;/p&gt;

&lt;div class=&quot;language-html highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nt&quot;&gt;&amp;lt;html&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;lang=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;en&quot;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;nt&quot;&gt;&amp;lt;head&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;nt&quot;&gt;&amp;lt;meta&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;charset=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;utf-8&quot;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;nt&quot;&gt;&amp;lt;title&amp;gt;&lt;/span&gt;Static content test&lt;span class=&quot;nt&quot;&gt;&amp;lt;/title&amp;gt;&lt;/span&gt;
&lt;span class=&quot;nt&quot;&gt;&amp;lt;/head&amp;gt;&lt;/span&gt;
&lt;span class=&quot;nt&quot;&gt;&amp;lt;body&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;nt&quot;&gt;&amp;lt;h1&amp;gt;&lt;/span&gt;Hello World&lt;span class=&quot;nt&quot;&gt;&amp;lt;/h1&amp;gt;&lt;/span&gt;
&lt;span class=&quot;nt&quot;&gt;&amp;lt;/body&amp;gt;&lt;/span&gt;
&lt;span class=&quot;nt&quot;&gt;&amp;lt;/html&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;When we start our Spring Boot app and point our web browser to it (with default configuration the URL should be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;localhost:8080&lt;/code&gt;), &lt;em&gt;Hello World&lt;/em&gt; should be displayed to us.
Everything in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;src/main/resources/static/&lt;/code&gt; is moved to the correct location in the packaged jar file.
Now that we know how to serve static content, it should be relatively easy to serve the React app in a similar manner.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;But wait! Javascript source files have to be built first, CSS minified etc.
We can’t just put our React source files to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;src/main/resources&lt;/code&gt; and expect everything to work.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;That’s correct.
We have to build the React app before we can move it into the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/static&lt;/code&gt; directory.
Let’s have a look at how to do that.
But first, we need to generate a new React app.&lt;/p&gt;

&lt;h2 id=&quot;create-a-react-app&quot;&gt;Create a React app&lt;/h2&gt;

&lt;p&gt;It’s super easy to get started with React by using &lt;a href=&quot;https://facebook.github.io/create-react-app/&quot; title=&quot;Create React App&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;create-react-app&lt;/code&gt;&lt;/a&gt;.
If you have the necessary tools installed (e.g. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;node&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;npm&lt;/code&gt;), you can just execute this command&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;npx create-react-app enter-app-name-here
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;You’re free to choose where you would like to place the generated web app.
In this example, I’m going to copy it to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;src/main/webapp&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;gradle-build-script&quot;&gt;Gradle build script&lt;/h2&gt;

&lt;p&gt;Before we can put our web app to production, &lt;a href=&quot;https://github.com/facebook/create-react-app#quick-overview&quot; title=&quot;Create React App Quick Overview&quot;&gt;we must create a minified bundle with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;npm run build&lt;/code&gt;&lt;/a&gt;.
To serve the minified bundle with Spring Boot, we have to move it to one of the directories where &lt;a href=&quot;https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content&quot;&gt;Spring Boot serves static content&lt;/a&gt;.
I’m using &lt;a href=&quot;https://gradle.org/&quot; title=&quot;Gradle Build Tool&quot;&gt;Gradle&lt;/a&gt; in this example to build and package the Spring Boot application, but the same can be achieved with other build tools.
The key is to remember that in addition to building the Java code, we must also create the minified bundle of our web app and copy it to the correct directory.&lt;/p&gt;

&lt;p&gt;To integrate a Gradle build with Node, I’m using the &lt;a href=&quot;https://github.com/srs/gradle-node-plugin&quot; title=&quot;Gradle plugin for integrating NodeJS in your build&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gradle-node-plugin&lt;/code&gt;&lt;/a&gt;.
The following are the most interesting parts of my Gradle build script.&lt;/p&gt;

&lt;div class=&quot;language-groovy highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// Read more about how to configure the plugin from&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// https://github.com/srs/gradle-node-plugin/blob/master/docs/node.md&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;node&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;download&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;

  &lt;span class=&quot;c1&quot;&gt;// Set the work directory for unpacking node&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;workDir&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;file&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;${project.buildDir}/nodejs&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;c1&quot;&gt;// Set the work directory for NPM&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;npmWorkDir&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;file&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;${project.buildDir}/npm&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;task&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;appNpmInstall&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;type:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;NpmTask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;description&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;Installs all dependencies from package.json&quot;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;workingDir&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;file&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;${project.projectDir}/src/main/webapp&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;args&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;install&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;task&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;appNpmBuild&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;type:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;NpmTask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;description&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;Builds production version of the webapp&quot;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;workingDir&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;file&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;${project.projectDir}/src/main/webapp&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;args&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;run&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;build&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;task&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;copyWebApp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;type:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Copy&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;&apos;src/main/webapp/build&apos;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;into&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;&apos;build/resources/main/static/.&apos;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;appNpmInstall&lt;/code&gt; is a Gradle task that runs &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;npm install&lt;/code&gt; in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;webapp&lt;/code&gt; directory.
Similar to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;appNpmInstall&lt;/code&gt;, the build script declares the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;appNpmBuild&lt;/code&gt; task that runs &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;npm run build&lt;/code&gt; to create the minified bundle of the web app.
Finally, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;copyWebApp&lt;/code&gt; is a simple &lt;a href=&quot;https://docs.gradle.org/current/dsl/org.gradle.api.tasks.Copy.html&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Copy&lt;/code&gt;&lt;/a&gt; task to copy the minified bundle to the static content directory.
Feel free to test run these tasks in isolation and see how they work.
For example, running &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gradle appNpmInstall&lt;/code&gt; should install all of our web app dependencies and place them in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;src/main/webapp/node_modules/&lt;/code&gt; directory.&lt;/p&gt;

&lt;h2 id=&quot;development-flow&quot;&gt;Development flow&lt;/h2&gt;

&lt;p&gt;During web app development, you should start the web app in development mode.
Therefore, instead of bundling the web app inside the Spring app, let’s serve it separately using the dev server.
Go to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;webapp&lt;/code&gt; directory and run &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;npm start&lt;/code&gt;.
This way, your web app will reload automatically if you make any changes in the source files.
At the same time, you should also start the Spring Boot application.&lt;/p&gt;

&lt;p&gt;To make the development flow with Spring Boot a little more pleasant, you can also &lt;a href=&quot;https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html#using-boot-devtools-restart&quot; title=&quot;Automatic Restart&quot;&gt;configure &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;spring-boot-devtools&lt;/code&gt; and enable automatic restarts&lt;/a&gt;.
When configured, the Spring Boot app restarts whenever files on the classpath change.&lt;/p&gt;

&lt;h2 id=&quot;build-for-production&quot;&gt;Build for production&lt;/h2&gt;

&lt;p&gt;To build our application for production, in addition to compiling and packaging our Java code, we must also create a minified bundle of the web app and place it inside the Jar file to one of the directories where Spring Boot serves static content.
We already have our build script configured with tasks that can install our dependencies, create the minified bundle and copy it to the correct location.
To make the packaging a bit more simpler, we could define some dependencies between the build tasks in our build script.&lt;/p&gt;

&lt;div class=&quot;language-groovy highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;appNpmBuild&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;dependsOn&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;appNpmInstall&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;copyWebApp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;dependsOn&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;appNpmBuild&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;compileJava&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;dependsOn&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;copyWebApp&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This makes sure that whenever Java code is compiled, web app dependencies are also installed, minified bundle is created and the bundle is copied to a static content directory.
When you run &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gradle clean build&lt;/code&gt;, you don’t have explicitly run any web app specific Gradle tasks.
Once the build has finished, you can start the application via command-line.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;java -jar path/to/web-app.jar
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Point your browser to it and you should see the newly created React app running.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;We went through how to create a basic React web app and serve it with Spring Boot.
The key is to configure our Gradle build script so that in addition to building and packaging our Java code, we also build and minify the web app and copy it to the Jar file.
Essentially, the same principles apply if you’re using any other build tool (e.g. &lt;a href=&quot;https://maven.apache.org/&quot;&gt;Maven&lt;/a&gt;) or you want to use something else than React (e.g. &lt;a href=&quot;https://angular.io/&quot;&gt;Angular&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;The example code presented in this post can be found on &lt;a href=&quot;https://github.com/indrekots/static-content-demo&quot;&gt;Github&lt;/a&gt;.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/serving-react-apps-from-spring-boot/&quot;&gt;Serving React apps from Spring Boot&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on January 16, 2019.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[Structuring packages in Java web applications]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/structuring-packages-in-java-web-applications/" />
  <id>https://blog.indrek.io/articles/structuring-packages-in-java-web-applications</id>
  <updated>2019-06-03 18:56:18 +0300T00:00:00-00:00</updated>
  <published>2018-10-28T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;If you’ve ever worked on a typical &lt;a href=&quot;https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html&quot; title=&quot;Spring Web MVC&quot;&gt;Spring web application&lt;/a&gt;, most likely you have seen the following top level packages.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;.
├── controller
├── service
└── repository&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;This clearly indicates that a &lt;a href=&quot;https://en.wikipedia.org/wiki/Multitier_architecture#Three-tier_architecture&quot; title=&quot;Three-tier architecture&quot;&gt;layered architecture is used&lt;/a&gt;.
We have a package for controllers that accept incoming HTTP requests. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;service&lt;/code&gt; package includes classes that deal with application logic and finally, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;repository&lt;/code&gt; contains data access functionality.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2018-05-28-package-structure/groups.jpg&quot; alt=&quot;&quot; /&gt;
  &lt;figcaption&gt;Classes are grouped like cutlery on a tray. &lt;a href=&quot;https://unsplash.com/photos/yw3UaP-5ybM&quot;&gt;Image by Jarosław Ceborski&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Classes are grouped like cutlery on a tray.
Controllers, services and repositories are in separate packages the same way knives, forks and spoons are in their respective containers.
It’s a widely used approach that’s familiar to many software developers.
But have you ever questioned why do we build applications this way?
Why do we treat layers with such importance that they get a package named after them?
Perhaps this is a &lt;a href=&quot;https://en.wikipedia.org/wiki/Cargo_cult_programming&quot; title=&quot;Cargo cult programming&quot;&gt;cargo cult&lt;/a&gt;?
In this post we’re going to explore the ideas around what would happen if layers were not the topmost level of organization in an application architecture.&lt;/p&gt;

&lt;h2 id=&quot;quick-recap-of-packages&quot;&gt;Quick recap of packages&lt;/h2&gt;

&lt;p&gt;In Java, &lt;a href=&quot;https://docs.oracle.com/javase/tutorial/java/package/packages.html&quot; title=&quot;Creating and Using Packages&quot;&gt;packages&lt;/a&gt; can be used for the following&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Organizing classes into logical groups&lt;/li&gt;
  &lt;li&gt;Namespace classes to avoiding naming conflicts&lt;/li&gt;
  &lt;li&gt;Encapsulation&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In my opinion, using packages as a tool to achieve encapsulation is the least used function of the three.
Packages are more than just folders on disk that organize classes the way you might organize your photo collection.
They can be used to define boundaries in code and hide classes from other parts of the system that don’t need to know about them.&lt;/p&gt;

&lt;h2 id=&quot;package-by-layer&quot;&gt;Package by layer&lt;/h2&gt;

&lt;p&gt;The first chapter of &lt;a href=&quot;https://www.amazon.com/gp/product/0321127420/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;amp;tag=indrekio-20&amp;amp;creative=9325&amp;amp;linkCode=as2&amp;amp;creativeASIN=0321127420&amp;amp;linkId=b79299fe25f6244dd297bb0886dbf3fc&quot;&gt;Patterns of Enterprise Application Architecture by Martin Fowler&lt;/a&gt; says that layering is one of the most common techniques that software designers use to break apart a complicated software system.
They make an intricate system easier to reason about.
In Java, we usually see layers implemented using packages.
If you have ever worked on a Java based web application, you have probably seen it yourself.&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2018-05-28-package-structure/package_by_layer.png&quot; alt=&quot;Layered architecture modelled with packages.&quot; /&gt;
  &lt;figcaption&gt;Layered architecture modelled with packages. Types in each layer have to be public.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Designing packages by layer is technical in nature and does not reflect the underlying domain.
Whenever a layer above calls a layer below, we’re crossing package boundaries.
To do that, the callee needs to be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;public&lt;/code&gt;.
For example, if a service class inside the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;service&lt;/code&gt; package wants to call a method in a repository class that’s in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;repository&lt;/code&gt; package, the latter needs to be public.&lt;/p&gt;

&lt;p&gt;What’s bad about having a type declared as public you might ask?
Having it publicly accessible could be beneficial, because there might be other service layer classes that want to operate on the same repository, right?
Before giving an answer, I’d like to take a step back and talk about encapsulation.&lt;/p&gt;

&lt;h3 id=&quot;encapsulation&quot;&gt;Encapsulation&lt;/h3&gt;

&lt;p&gt;When we design a class, we need to consider what parts of it to hide and what to make &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;public&lt;/code&gt;.
Essentially, we’re using &lt;a href=&quot;https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html&quot; title=&quot;Controlling Access to Members of a Class&quot;&gt;access modifiers&lt;/a&gt; to &lt;a href=&quot;https://en.wikipedia.org/wiki/Information_hiding&quot; title=&quot;Information hiding&quot;&gt;hide the inner workings of a class from the outside world&lt;/a&gt;.
We don’t want anybody to freely access the private parts of our class because (a) we want to hide complexity and (b) have the freedom the change implementation details without having the entire world know about it.
Using packages for encapsulation, it is possible to achieve the same goals but on a higher level of abstraction.&lt;/p&gt;

&lt;p&gt;Unless we’re dealing with a demo application, most of the time, accessing a repository can be considered &lt;em&gt;an implementation detail&lt;/em&gt; of a larger feature.
In addition to, say, storing data to a database, you might need to introduce logging, check permissions or start other business specific processes.
For example, whenever a new user is created in your &lt;a href=&quot;https://en.wikipedia.org/wiki/Software_as_a_service&quot; title=&quot;Software as a service&quot;&gt;SaaS&lt;/a&gt; product, you might want to send them a welcome e-mail.
If a hypothetical &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UserRepository&lt;/code&gt; was publicly accessible to all other classes, it’s easy to bypass important domain related checks and processes without even knowing that you might have done something wrong.&lt;/p&gt;

&lt;h3 id=&quot;everything-public&quot;&gt;Everything public&lt;/h3&gt;

&lt;blockquote class=&quot;twitter-tweet&quot; data-lang=&quot;en&quot;&gt;&lt;p lang=&quot;en&quot; dir=&quot;ltr&quot;&gt;When developers write novels.&lt;br /&gt;&lt;br /&gt;Chapter 1 - Characters&lt;br /&gt;Chapter 2 - Locations&lt;br /&gt;Chapter 3 - Vehicles&lt;br /&gt;Chapter 4 - Relationships&lt;br /&gt;Chapter 5 - Plots&lt;br /&gt;Chapter 6 - Conclusions&lt;br /&gt;Appendix A - Twists &lt;a href=&quot;https://t.co/8lcc27WeoA&quot;&gt;https://t.co/8lcc27WeoA&lt;/a&gt;&lt;/p&gt;&amp;mdash; Richard Dalton 🇪🇺 (@richardadalton) &lt;a href=&quot;https://twitter.com/richardadalton/status/936228404084559872?ref_src=twsrc%5Etfw&quot;&gt;November 30, 2017&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Designing packages by layer means that the classes that are used together the most are in different packages.
This leads to &lt;a href=&quot;https://en.wikipedia.org/wiki/Cohesion_(computer_science)&quot; title=&quot;Cohesion&quot;&gt;low cohesion&lt;/a&gt;.
Our classes &lt;em&gt;need&lt;/em&gt; to be public, otherwise the layer above cannot call them.
When you think about it, we’ve hardwired ourselves to always use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;public&lt;/code&gt; access modifier when creating a new class.
It does not help that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;public&lt;/code&gt; is usually the default option when generating a new class via an IDE.
And when something is public, every other class can call it.
Without discipline, it’s easy to introduce architecture violations by declaring a dependency on a class that might just be an &lt;em&gt;implementation detail&lt;/em&gt;.
There’s a higher risk that the system evolves into something that’s difficult to change.
Using a &lt;em&gt;package-by-layer&lt;/em&gt; approach, we intentionally give away the benefits of encapsulation.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;If all types are public, Java packages are about organisation of code rather than encapsulation&lt;/p&gt;

  &lt;footer&gt;&lt;strong&gt;Simon Brown&lt;/strong&gt; &amp;mdash; &lt;a href=&quot;https://youtu.be/kbKxmEeuvc4?t=1928&quot;&gt;Modular monoliths&lt;/a&gt;&lt;/footer&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;package-by-feature&quot;&gt;Package by feature&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;If we stop doing package by layer, how should we structure our code?&lt;/em&gt;
Instead of creating a package for each layer (a horizontal slice), what if the topmost level of organization in code was a feature (a vertical slice)?&lt;/p&gt;

&lt;figure class=&quot;align-center&quot;&gt;
  &lt;img src=&quot;https://blog.indrek.io/images/2018-05-28-package-structure/package_by_feature.png&quot; alt=&quot;Packages representing a domain concept&quot; /&gt;
  &lt;figcaption&gt;Slicing software vertically with domain specific packages. Layered architecture is still present but hidden from the top level view.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Compared to the &lt;em&gt;package-by-layer&lt;/em&gt; approach, classes that are used together the most are now in the same package, allowing us to design more cohesive modules.
There’s no benefit in making all classes public anymore.
As a matter of fact, we gain more from starting to create &lt;a href=&quot;https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html&quot; title=&quot;Controlling Access to Members of a Class&quot;&gt;package-private&lt;/a&gt; classes.
Types that are specific to a feature can be made package-private so they don’t leak outside of their domain.
On the other hand, public classes define the API of the package their part of.&lt;/p&gt;

&lt;p&gt;When slicing software vertically, we have better control over how classes call each other over package boundaries.
For example, a repository class could be made package-private so that nobody from any other package could call it directly.
Access to a repository can be encapsulated and callers can be forced to go through the public API.
Therefore, implementation details of a feature are hidden from the outside world.
Layered architecture could still exist inside a package but &lt;a href=&quot;http://olivergierke.de/2013/01/whoops-where-did-my-architecture-go/&quot; title=&quot;Whoops! Where did my architecture go&quot;&gt;layering in general becomes an implementation detail&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;So what does the architecture of your application scream? When you look at the top level directory structure, and the source files in the highest level package; do they scream: &lt;strong&gt;Health Care System&lt;/strong&gt;, or &lt;strong&gt;Accounting System&lt;/strong&gt;, or &lt;strong&gt;Inventory Management System&lt;/strong&gt;? Or do they scream: &lt;strong&gt;Rails&lt;/strong&gt;, or &lt;strong&gt;Spring/Hibernate&lt;/strong&gt;, or &lt;strong&gt;ASP&lt;/strong&gt;?&lt;/p&gt;

  &lt;footer&gt;&lt;strong&gt;Uncle Bob&lt;/strong&gt; &amp;mdash; &lt;a href=&quot;https://8thlight.com/blog/uncle-bob/2011/09/30/Screaming-Architecture.html&quot;&gt;Screaming Architecture&lt;/a&gt;&lt;/footer&gt;
&lt;/blockquote&gt;

&lt;p&gt;Packages could be designed around &lt;a href=&quot;https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215&quot; title=&quot;Domain-Driven Design: Tackling Complexity in the Heart of Software&quot;&gt;Domain Driven Design&lt;/a&gt; &lt;a href=&quot;https://martinfowler.com/bliki/DDD_Aggregate.html&quot; title=&quot;DDD_Aggregate&quot;&gt;aggregates&lt;/a&gt;.
When it makes sense, vertical slices can become &lt;a href=&quot;https://martinfowler.com/bliki/BoundedContext.html&quot; title=&quot;BoundedContext&quot;&gt;bounded contexts&lt;/a&gt;.
If you see a need, they could be extracted into a separate &lt;a href=&quot;https://maven.apache.org/guides/mini/guide-multiple-modules.html&quot; title=&quot;Guide to Working with Multiple Modules&quot;&gt;Maven module&lt;/a&gt;.
With the advent of &lt;a href=&quot;https://blog.codefx.org/java/java-module-system-tutorial/&quot; title=&quot;Code-First Java Module System Tutorial&quot;&gt;the Java Module System&lt;/a&gt;, it is possible to think about domain boundaries at a higher level of abstraction.
Theoretically it should be relatively painless to extract a vertical slice into a separate application when we have well defined APIs in place between modules.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;https://amzn.to/2W6Jpvu&quot; title=&quot;Release It!: Design and Deploy Production-Ready Software&quot;&gt;Release It!&lt;/a&gt;, the author &lt;a href=&quot;https://www.michaelnygard.com/&quot;&gt;Michael T. Nygard&lt;/a&gt; writes about the benefits of vertical slices.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;What happens if we rotate the barriers [horizontal slices] 90 degrees? We get something like component-based architecture. Instead of worrying about how to isolate the domain layer from the database, we isolate components from each other. Components are only allowed narrow, formal interfaces between each other. If you squint, they look like microservice instances that happen to run in the same process.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Abstraction helps us to reason about big and complex software systems.
In Java web applications, we usually see that the first level of abstraction are layers implemented with packages.
&lt;a href=&quot;https://martinfowler.com/bliki/PresentationDomainDataLayering.html&quot; title=&quot;PresentationDomainDataLayering&quot;&gt;As the application grows, layers become more complex and further modularization might be needed&lt;/a&gt;.
Creating a package for each layer might not be the best approach anymore because we lose the benefits of encapsulation that packages can provide.
&lt;em&gt;Package-by-layer&lt;/em&gt; approach forces us to create classes that are public.
As a result it’s easy to introduce architecture violations because every part of the system can access public classes.&lt;/p&gt;

&lt;p&gt;Instead of decomposing software systems along technical lines, what if we decomposed software into domain specific modules?
Creating packages by feature allows us to hide classes from other parts of the system that don’t need to know about them.
We’re benefitting from encapsulation and can enforce how modules should talk to each other.&lt;/p&gt;

&lt;p&gt;Coming up with module boundaries is a difficult task where one might have to redraw the boundaries multiple times before settling on a solution that feels right.
Layered architecture using packages is usually a simpler starting point and perhaps that’s one of the reasons we see it more.
Packages are also not the perfect tool to design modules.
Hopefully the Java module system can help us here.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Where do I start?&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Stop making every class public&lt;/p&gt;

  &lt;footer&gt;&lt;strong&gt;Simon Brown&lt;/strong&gt; &amp;mdash; &lt;a href=&quot;https://youtu.be/kbKxmEeuvc4?t=3054&quot;&gt;Modular monoliths&lt;/a&gt;&lt;/footer&gt;
&lt;/blockquote&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/structuring-packages-in-java-web-applications/&quot;&gt;Structuring packages in Java web applications&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on October 28, 2018.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[Improvements to Optional in Java 9]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/improvements-to-optional-in-java-9/" />
  <id>https://blog.indrek.io/articles/improvements-to-optional-in-java-9</id>
  <updated>2018-01-18 16:46:57 +0200T00:00:00-00:00</updated>
  <published>2018-01-18T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/optionals-in-java-8/&quot;&gt;Optionals were introduced to Java in version 8&lt;/a&gt;.
If used correctly, they can help you avoid unintentional &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NullPointerException&lt;/code&gt;s.
Essentially, an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; is a container object which may or may not contain a non-null a value.
Combined with &lt;a href=&quot;https://blog.indrek.io/articles/java-8-lambda-expressions/&quot;&gt;lambda expressions&lt;/a&gt;, you can write concise code that avoids explicit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; checks.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;nc&quot;&gt;Optional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Book&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bookOptional&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;findBook&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;The War of the Worlds&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;Book&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;book&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bookOptional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;orElseGet&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;Book:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;defaultBook&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Java 9 introduced a couple of improvements to the &lt;a href=&quot;https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html&quot;&gt;Optional&lt;/a&gt; class.&lt;/p&gt;

&lt;h2 id=&quot;stream-from-optional&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Stream&lt;/code&gt; from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#stream--&quot; title=&quot;Optional javadoc for Java 9&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional::stream&lt;/code&gt;&lt;/a&gt; allows you to transform an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; to a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Stream&lt;/code&gt;.
If a value is present, the returned &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Stream&lt;/code&gt; will contain that value.
Otherwise an empty &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Stream&lt;/code&gt; is returned.
You might be thinking how can that be useful?
We use Streams to manipulate collections of data.
How can a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Stream&lt;/code&gt; that contains at most one element be useful?&lt;/p&gt;

&lt;p&gt;In a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Stream&lt;/code&gt; processing pipeline we can transform &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt;s into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Stream&lt;/code&gt;s and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;flatmap&lt;/code&gt; them into a single &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Stream&lt;/code&gt; containing only the values that are present.
Let’s look at the following example.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;nc&quot;&gt;List&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Book&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;books&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;

&lt;span class=&quot;nc&quot;&gt;List&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Author&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ghostwriters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;books&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;stream&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;Book:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;getGhostWriter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;flatMap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;Optional:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stream&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;collect&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;toList&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Since every book doesn’t have a &lt;a href=&quot;https://en.wikipedia.org/wiki/Ghostwriter&quot;&gt;ghostwriter&lt;/a&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;getGhostWriter()&lt;/code&gt; returns an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Author&lt;/code&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&amp;lt;Author&amp;gt;&lt;/code&gt;).
For each book, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional::stream&lt;/code&gt; creates a new &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Stream&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;flatmap&lt;/code&gt; will ensure that all &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Stream&lt;/code&gt;s are merged together.
Essentially, we’re getting rid of empty &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt;s.&lt;/p&gt;

&lt;p&gt;You could do it in Java 8 with a &lt;a href=&quot;https://blog.indrek.io/articles/java-8-lambda-expressions/&quot;&gt;lambda expression&lt;/a&gt; but &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional::stream&lt;/code&gt; is more succinct.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;nc&quot;&gt;List&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Book&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;books&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;

&lt;span class=&quot;nc&quot;&gt;List&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Author&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ghostwriters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;books&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;stream&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;Book:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;getGhostWriter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;flatMap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;o&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;o&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;Stream:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;of&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;orElseGet&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;Stream:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;empty&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;))&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;collect&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;toList&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;h2 id=&quot;optionalor&quot;&gt;Optional::or&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#or-java.util.function.Supplier-&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional::or&lt;/code&gt;&lt;/a&gt; will either return the current &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; if a value is present.
Otherwise an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; produced by the provided supplier function is returned.
To make things more clear, let’s have a look at the following example.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;n&quot;&gt;findBook&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;or&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;findBookFromWeb&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;If &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;findBook()&lt;/code&gt; does not find anything, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;findBookFromWeb()&lt;/code&gt; gets called.
Since the return value is always an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt;, we can build a lazily loaded chain of method calls.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Optional&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Book&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;findBook&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;findBookFromDatabase&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;or&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;findBookFromLocalLibrary&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;or&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;findBookFromWeb&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Back in &lt;a href=&quot;https://blog.indrek.io/articles/chaining-optionals-in-java-8/&quot;&gt;Java 8 you had to go through some ceremony&lt;/a&gt; to achieve something similar.&lt;/p&gt;

&lt;h2 id=&quot;optionalifpresentorelse&quot;&gt;Optional::ifPresentOrElse&lt;/h2&gt;

&lt;p&gt;The final addition to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt;s in Java 9 is the &lt;a href=&quot;https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#ifPresentOrElse-java.util.function.Consumer-java.lang.Runnable-&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional::ifPresentOrElse&lt;/code&gt;&lt;/a&gt; method.
By accepting a consumer function and a runnable, it can be used to cover the case where the value is present as well as the case where the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; is empty.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;n&quot;&gt;findBook&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;ifPresentOrElse&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;increaseReaderCount&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;warn&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Tried to look for a book which does not exist!&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Three new methods were added to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; class in Java 9. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional::stream&lt;/code&gt; allows you to transform an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; into a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Stream&lt;/code&gt; of one element or an empty &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Stream&lt;/code&gt;. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional::or&lt;/code&gt; returns the current &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; if a value is present, otherwise an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional&lt;/code&gt; produced by the supplier function is returned. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Optional::ifPresentOrElse&lt;/code&gt; can be used to cover the value present as well as the value missing cases.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/improvements-to-optional-in-java-9/&quot;&gt;Improvements to Optional in Java 9&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on January 18, 2018.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[Using environment variables with Spring Boot]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/using-environment-variables-with-spring-boot/" />
  <id>https://blog.indrek.io/articles/using-environment-variables-with-spring-boot</id>
  <updated>2020-02-23 07:17:09 +0200T00:00:00-00:00</updated>
  <published>2017-12-17T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;Spring Boot applications &lt;a href=&quot;https://blog.indrek.io/articles/externalized-configuration-in-spring-boot/&quot; title=&quot;Externalized configuration in Spring Boot&quot;&gt;can be easily configured via property files&lt;/a&gt;.
But sometimes you need more flexibility in terms of how the configuration is provided to the application.
A popular approach next to configuration files is to use environment variables.
This post will cover how you can use OS environment variables to pass configuration values to a Spring Boot application.&lt;/p&gt;

&lt;h2 id=&quot;injecting-environment-variables&quot;&gt;Injecting environment variables&lt;/h2&gt;

&lt;p&gt;You might already be familiar with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@Value&lt;/code&gt; annotation.
It can be used to inject property values to beans.
In addition to looking values from property files, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@Value&lt;/code&gt; annotation also looks for matching values from the environment.
So when you have an environment property called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DB_URL&lt;/code&gt;, you can inject it to a field with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@Value(&quot;${DB_URL}&quot;)&lt;/code&gt;.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;nd&quot;&gt;@Value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;${DB_URL}&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dbUrl&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;h2 id=&quot;setting-applicationproperties-values-from-environment&quot;&gt;Setting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;application.properties&lt;/code&gt; values from environment&lt;/h2&gt;

&lt;p&gt;Similar to the previous approach, it is possible to assign values to properties in your &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;application.properties&lt;/code&gt; file from the environment.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-yaml&quot; data-lang=&quot;yaml&quot;&gt;&lt;span class=&quot;s&quot;&gt;api.key=${API_KEY}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;As with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@Value&lt;/code&gt; annotation, you can provide a default value which will be used if the environment variable is not found.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-yaml&quot; data-lang=&quot;yaml&quot;&gt;&lt;span class=&quot;s&quot;&gt;api.key=${API_KEY:123abc}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;h2 id=&quot;spring_application_json&quot;&gt;SPRING_APPLICATION_JSON&lt;/h2&gt;

&lt;p&gt;At application startup, Spring Boot will look for an environment variable called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SPRING_APPLICATION_JSON&lt;/code&gt;.
It can be used to provide a set of application properties using inline JSON.
For example, you can set &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ec2.public.url&lt;/code&gt; property as follows.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-bash&quot; data-lang=&quot;bash&quot;&gt;&lt;span class=&quot;nv&quot;&gt;SPRING_APPLICATION_JSON&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;&apos;{&quot;ec2&quot;:{&quot;public&quot;:{&quot;url&quot;:&quot;http://mydomain.com&quot;}}}&apos;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;To get a more thorough overview of all the ways Spring Boot allows you to configure applications, you should definitely look at &lt;a href=&quot;https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html&quot;&gt;the official docs&lt;/a&gt;.
You can find an example Sprint Boot application from &lt;a href=&quot;https://github.com/indrekots/spring-boot-envvariables&quot;&gt;Github&lt;/a&gt; that demonstrates the approaches covered in this post.&lt;/p&gt;

&lt;p class=&quot;notice&quot;&gt;📖 &lt;strong&gt;Book Recommendation!&lt;/strong&gt; If you’d like to learn more about Spring Boot, check out &lt;a href=&quot;https://amzn.to/2HMNznJ&quot; title=&quot;Learning Spring Boot 2.0 - Second Edition: Simplify the development of lightning fast applications based on microservices and reactive programming&quot;&gt;Learning Spring Boot 2.0&lt;/a&gt; by Greg L. Turnquist.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/using-environment-variables-with-spring-boot/&quot;&gt;Using environment variables with Spring Boot&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on December 17, 2017.&lt;/p&gt;</content>
</entry>


<entry>
  <title type="html"><![CDATA[How to write a good commit message]]></title>
  <link rel="alternate" type="text/html" href="https://blog.indrek.io/articles/how-to-write-a-good-commit-message/" />
  <id>https://blog.indrek.io/articles/how-to-write-a-good-commit-message</id>
  <updated>2019-06-08 20:47:17 +0300T00:00:00-00:00</updated>
  <published>2017-09-17T00:00:00+00:00</published>
  
  <author>
    <name></name>
    <uri>https://blog.indrek.io</uri>
    
  </author>
  <content type="html">&lt;p&gt;A &lt;a href=&quot;https://en.wikipedia.org/wiki/Version_control&quot; title=&quot;Version Control&quot;&gt;version control system&lt;/a&gt; is an essential collaboration tool used in software engineering.
I think for most developers, it is a tool for sharing work in a co-operative manner.
For the most part, this is correct.
Multiple developers can work on the same codebase without overwriting each other’s work.
But VCSs also play an important role—something that cannot be understated—in tracking the history of changes in a codebase.
But a history is only good if it’s well documented.
This leads me to the topic of this post—commit messages and how to write a good one.&lt;/p&gt;

&lt;p&gt;This post centered around &lt;a href=&quot;https://git-scm.com/&quot; title=&quot;Git&quot;&gt;Git&lt;/a&gt;, but the basic concepts apply to other VCSs as well.&lt;/p&gt;

&lt;h2 id=&quot;bad-commit-messages&quot;&gt;Bad commit messages&lt;/h2&gt;

&lt;p&gt;To understand what’s a good commit message, let’s start with a few examples of bad ones.
I dug through some old git repositories and found some gems that I have written.
I’m sure you’ve seen similar messages.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;started working on feature X&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;some testing stuff&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;little fix&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TICKET-66&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;very big commit but a short commit message&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All of them would receive a high ranking in &lt;a href=&quot;http://www.codelord.net/2015/03/16/bad-commit-messages-hall-of-shame/&quot; title=&quot;Bad Commit Messages Hall of Shame&quot;&gt;the commit messages hall of shame&lt;/a&gt;.
In general, they’re vague and don’t say anything about why the particular change was introduced.
Looking at them now, they’re almost as good as having no commit messages at all.
To understand what’s wrong, let’s turn our attention to what to look for in a good commit message.&lt;/p&gt;

&lt;h2 id=&quot;understanding-good-commit-messages&quot;&gt;Understanding good commit messages&lt;/h2&gt;

&lt;p&gt;To understand how to write a good commit message, let’s put ourselves in the place of a maintainer or
a future developer of the project. After all, we should write commit messages not for our pleasure but
for others to read.&lt;/p&gt;

&lt;p&gt;Imagine yourself as a developer who is tasked to maintain a relatively large codebase.
You need to hunt down a bug and while doing that, you come across a line of code that looks interesting to say the least.
You start to wonder why the original author implemented it like that. Maybe there was a very specific and rational reason.
Or maybe—just maybe—this is the source of that dreaded bug that you’ve been trying to catch for hours.&lt;/p&gt;

&lt;p&gt;Being a good &lt;a href=&quot;https://en.wikipedia.org/wiki/Software_archaeology&quot; title=&quot;Software Archeology&quot;&gt;software archeologist&lt;/a&gt;, you whip out your handy Swiss Army knife—Git—like MacGyver and proceed to unravel the mystery.
Using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;git blame&lt;/code&gt; you try to understand who was the author of the line of code in question
and what was the original intent. After some time spent on &lt;a href=&quot;https://git-scm.com/docs/git-blame&quot; title=&quot;Git blame documentation&quot;&gt;reading how &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;git blame&lt;/code&gt; works&lt;/a&gt; you read the commit message
of the revision the line of code was part of.&lt;/p&gt;

&lt;p&gt;If this were a &lt;em&gt;choose your own adventure&lt;/em&gt; book, you would be presented with the following options:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;The commit message is vague. You look at other changes in the same commit in hopes of understanding
what the original author tried to achieve but they’re all over the place. It seems that the original author
bundled many logical changes into one commit.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;The commit message is vague. Luckily the commit is fairly small with only 2 files being changed in total.
Although the message is not useful, other changes in the commit help you deduce the original intent of the
author.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;The commit message is well structured and describes clearly the intent of the author. The message
includes why the change was introduced and also explains the peculiarities of the line of code that prompted you to take this journey.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you’re like me, you’d choose the third option. The main takeaway is that commit messages should be
written for other developers—or for the future you—so they could understand why you introduced these changes.&lt;/p&gt;

&lt;p&gt;Unfortunately, often times we find ourselves faced with the first option.
This becomes even more aggravating when we’re under a tight deadline while trying to fix an obscure bug in production.
Jez Humble and David Farley, the authors of &lt;a href=&quot;https://amzn.to/2MvKfSP&quot; title=&quot;Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation&quot;&gt;Continuous Delivery&lt;/a&gt;, had the following to say about commit messages.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;There is no prize for writing the shortest commit message. A Couple of medium-to-long sentences with an overview of what you were doing will often save you many times the effort later on.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Writing code is a team effort.
Even your hobby project has at least two developers working on it—you and the future you.
Software projects can last years and see many developers joining and leaving.
A lot of times it is impossible for a new developer to go and ask a previous developer what was on his/her mind when a piece of code was written.
Fortunately, good commit messages can help here.
They’re like a trail of breadcrumbs you leave behind for others who might stumble on the same twisted path you once took, hopefully leading them out of the dark forest.&lt;/p&gt;

&lt;h2 id=&quot;what-makes-up-a-good-commit-message&quot;&gt;What makes up a good commit message?&lt;/h2&gt;

&lt;p&gt;Hopefully by now I have convinced you of the importance of good commit messages.
Without further ado, let’s move on and look at what a commit message should contain.&lt;/p&gt;

&lt;p&gt;Overall, a commit message should explain what was changed and why.
There’s no need for a detailed description on how a patch was implemented.
That’s what source code is for.
But what if the code is not clear enough?
Then I think you might have bigger problems.
Read &lt;a href=&quot;https://amzn.to/2WDA1UF&quot;&gt;Clean Code&lt;/a&gt; by Robert C. Martin.&lt;/p&gt;

&lt;p&gt;It’s also good to compare the current implementation to how things were before the change.
This usually gives enough context so the reader can understand why the change was necessary.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://who-t.blogspot.com.ee/2009/12/on-commit-messages.html&quot; title=&quot;On commit messages&quot;&gt;Peter Hutterer writes&lt;/a&gt; that a good commit message should answer three questions about a patch:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Why is it necessary?&lt;/strong&gt; It may fix a bug, it may add a feature, it may improve performance, reliabilty, stability, or just be a change for the sake of correctness.
&lt;em&gt;My boss told me to do it&lt;/em&gt; is not a good reason.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;How does it address the issue?&lt;/strong&gt; For short obvious patches this part can be omitted, but it should be a high level description of what the approach was.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;What effects does the patch have?&lt;/strong&gt; (In addition to the obvious ones, this may include benchmarks, side effects, etc.)&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Put yourself in the position of a future developer or maintainer and try to think of what they should know about your patch.
In addition, try to avoid large commits.
Checking in a day’s worth of work at the end of the day is usually not a good practice.
If you don’t know what to write, your commit might be too large.
&lt;a href=&quot;https://www.freshconsulting.com/atomic-commits/&quot;&gt;Try to keep your commits atomic&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Don’t be too verbose.
Writing a good commit summary is difficult.
Keeping it short and meaningful can be a challenge.
It’s like naming a variable or a method.
You don’t want it to be too long, but you want to convey a meaning that’s easy to understand.&lt;/p&gt;

&lt;h2 id=&quot;commit-message-formatting&quot;&gt;Commit message formatting&lt;/h2&gt;

&lt;p&gt;An equally important aspect of commit messages is formatting.
To make your commits easy to read, there’s a few things to keep in mind.
First of all, &lt;a href=&quot;https://git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project&quot;&gt;the very first line of the commit message is the subject line&lt;/a&gt;.
Use it to briefly describe the changeset.
The subject line should be followed with a blank line and starting from the third line, you can add a more detailed description of the patch.&lt;/p&gt;

&lt;p&gt;&lt;strike&gt;Don&apos;t use &lt;code&gt;git commit -m &quot;my commit message&quot;&lt;/code&gt; to write commit messages.
It won&apos;t allow you to write a more detailed description on the third line.&lt;/strike&gt;
Apparently, I was wrong as was pointed out by &lt;a href=&quot;https://twitter.com/homeworkprod/status/1038797032826306560&quot;&gt;@homeworkprod&lt;/a&gt;.
According to &lt;a href=&quot;https://git-scm.com/docs/git-commit#git-commit---messageltmsggt&quot;&gt;Git docs&lt;/a&gt;, if multiple &lt;code&gt;-m&lt;/code&gt; options are given, their values are concatenated as separate paragraphs.
You can also &lt;a href=&quot;https://stackoverflow.com/a/2596835/2928051&quot;&gt;Configure Git to open a text editor&lt;/a&gt; to write a commit message.&lt;/p&gt;

&lt;p&gt;Git tooling expects that the first line of a commit message is the title.
Therefore, the first letter should be capitalized and it should not end with a period.
You would not want to have a lower case heading that ends with a period, would you?&lt;/p&gt;

&lt;p&gt;For example, when running &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;git log --oneline&lt;/code&gt;, Git prints out only the commit hash and the first line of the commit message, giving you a quick overview of the commit history.
The following is an example of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;git log --oneline&lt;/code&gt; when applied on the &lt;a href=&quot;https://github.com/spring-projects/spring-framework&quot; title=&quot;Spring Framework&quot;&gt;Spring Framework&lt;/a&gt; project.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-bash&quot; data-lang=&quot;bash&quot;&gt;9aa369f402 Data class construction supports field default/marker parameters
18f42f9667 Fix typo
47a7475898 Resolve remaining nullability warnings
ac5e2599f7 Consistent overriding &lt;span class=&quot;k&quot;&gt;for &lt;/span&gt;all variants of init/destroy method inheritance
b94302b5bd Enforce non-null value from getBean and at injection points
10dcaa9bf6 Update introduction to Spring Web MVC&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;But if you’re interested in a more detailed view of the history, you could run &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;git log&lt;/code&gt; and the output will include the full commit message.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-bash&quot; data-lang=&quot;bash&quot;&gt;commit da8d50f91fed1470c69baa0cbaeeffc4b31a0e8b
Author: Sam Brannen &amp;lt;sam@sambrannen.com&amp;gt;
Date:   Thu Aug 3 23:19:57 2017 +0300

    Revise SpringExtension based on recent changes &lt;span class=&quot;k&quot;&gt;in &lt;/span&gt;JUnit Jupiter

    This commit revises the implementation of the SpringExtension to use
    the getRequired&lt;span class=&quot;k&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; methods &lt;span class=&quot;k&quot;&gt;in &lt;/span&gt;the ExtensionContext which are now built
    into JUnit Jupiter thanks to inspiration from the initial &lt;span class=&quot;s2&quot;&gt;&quot;convenience&quot;&lt;/span&gt;
    methods implemented here.

commit fabc9c28d7e115431e25da81a0dca47787a683aa
Author: Juergen Hoeller &amp;lt;jhoeller@pivotal.io&amp;gt;
Date:   Thu Aug 3 14:21:00 2017 +0200

    Align new FileSystemUtils NIO implementation with original behavior

    Issue: SPR-15845
    Issue: SPR-15846&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;&lt;a href=&quot;https://git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project&quot;&gt;Multiple&lt;/a&gt; &lt;a href=&quot;https://medium.com/@preslavrachev/what-s-with-the-50-72-rule-8a906f61f09c&quot; title=&quot;What’s with the 50/72 rule?&quot;&gt;resources&lt;/a&gt; advise to follow the 50/72 rule.
It says that your title line should be 50 characters or less and you should wrap lines in the message body around the 72 character mark.
Although, I don’t think this is a hard requirement, it has its merits.
A short title forces you to give a brief overview.
Limiting the line length in your body &lt;a href=&quot;https://baymard.com/blog/line-length-readability&quot; title=&quot;Readability: the Optimal Line Length&quot;&gt;greatly improves readability of text&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://chris.beams.io/posts/git-commit/#imperative&quot;&gt;Use imperative style for commit summary&lt;/a&gt;.
Instead of writing &lt;em&gt;Adding/added support for markdown&lt;/em&gt;, use &lt;em&gt;Add support for markdown&lt;/em&gt;.
Git’s generated commits use this convention too.&lt;/p&gt;

&lt;p&gt;Think of the subject line not as what you did, but what this commit will do if it is applied to my history.
For example, this commit will &lt;em&gt;add support for markdown&lt;/em&gt;.
When reviewing a pull request or merging branches, you can have a look at the summary of the commits and read them as follows: if I accept commit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bc43a2d&lt;/code&gt;, then this will &lt;em&gt;remove unused variables in controller&lt;/em&gt;.
The same is true if you’re cherry picking commits.
This would not work if the commit summary was written as something that has happened in the past.&lt;/p&gt;

&lt;h2 id=&quot;other-benefits&quot;&gt;Other benefits&lt;/h2&gt;

&lt;p&gt;In addition to leaving behind a trail of intent, well written commit messages have other benefits as well.
If you do &lt;a href=&quot;https://en.wikipedia.org/wiki/Code_review&quot;&gt;code reviews&lt;/a&gt;, an informative commit message can be of great help to the reviewer.
Instead of trying to understand the committers intentions by reading the changes in source code and possibly asking further questions, dedicating a bit of your time to write a good commit message can save the reviewer’s time.&lt;/p&gt;

&lt;p&gt;When a team has a consistent commit message style, the commit log could be used as a source for release notes.
Without much effort you’d have a quick way to generate release notes for your upcoming release.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;I like how Peter Hutterer put in a &lt;a href=&quot;https://who-t.blogspot.com.ee/2009/12/on-commit-messages.html&quot;&gt;blog post&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;A commit message shows whether a developer is a good collaborator.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A commit message should make it easy to understand why a change was introduced in the first place.
There’s no need to describe how the change was implemented.
Leave that for the source code.&lt;/p&gt;

&lt;p&gt;Treat the first line in your commit message as the title.
After that, leave a blank line and write a more thorough description starting from the third line.&lt;/p&gt;

&lt;p&gt;As developers, we agree that source code should follow a similar style.
Consistency is better than having &lt;a href=&quot;https://chris.beams.io/posts/git-commit/&quot;&gt;each participant use their own style&lt;/a&gt;.
This should apply to the commit log as well.
Project’s commit history is a valuable artifact, so let’s treat it as we treat our code.&lt;/p&gt;

&lt;p&gt;If you’re interested in Git, how to use it and its internals, then I suggest you to read &lt;a href=&quot;https://amzn.to/2Wo5een&quot;&gt;Pro Git&lt;/a&gt;.
And finally, keep in mind to &lt;a href=&quot;https://www.troyhunt.com/10-commandments-of-good-source-control/&quot; title=&quot;The 10 commandments of good source control management&quot;&gt;write every commit message like the next person who reads it is an axe-wielding maniac who knows where you live&lt;/a&gt;.&lt;/p&gt;

  &lt;p&gt;&lt;a href=&quot;https://blog.indrek.io/articles/how-to-write-a-good-commit-message/&quot;&gt;How to write a good commit message&lt;/a&gt; was originally published by  at &lt;a href=&quot;https://blog.indrek.io&quot;&gt;That Which Inspires Awe&lt;/a&gt; on September 17, 2017.&lt;/p&gt;</content>
</entry>

</feed>