<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>code &amp;mdash; StealthyCoder</title>
    <link>https://stealthycoder.writeas.com/tag:code</link>
    <description>Making code ninjas out of everyone</description>
    <pubDate>Sat, 13 Jun 2026 13:35:24 +0000</pubDate>
    <item>
      <title>PHP is bad.</title>
      <link>https://stealthycoder.writeas.com/php-is-bad?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[I just skimmed/read this article. It states that PHP is just as good as Rust/C/Java. That the opinion that it is bad is just 10 years out of date. !--more--&#xA;&#xA;5 years&#xA;&#xA;I would say even 5 years ago it was really bad. It was not secure and frameworks were lacking professionalism. To be honest I would say PHP is still bad today.&#xA;&#xA;Criticisms&#xA;&#xA;The criticisms to bad structure, SQL injections and general security related things are all batted away with one statement: use frameworks. Just use a framework and magically all things are fixed. That is a lie. The fundamental nature of PHP will make it be bad, no matter how many cool awesome things you build on top of it. &#xA;&#xA;Also frameworks themselves are also not foolproof and still will suffer from security flaws. Aside from this there are some other problems. Just search for all the CVE&#39;s of your favourite framework. They still occur across the board. &#xA;&#xA;Concurrency / parallelism&#xA;&#xA;The main problem with PHP is that it is not async in any way. It does not support threads, multiprocess or other constructs to make it concurrent or scalable in that sense. It just does not utilize the CPU efficiently. This also is combated in the original article by stating just throw more servers at it. Also the database is the bottleneck in all architectures, just scale that first then you can scale the application too. &#xA;&#xA;This is just nonsense. The database is hardly ever the real bottleneck. I made many applications, enterprise and non-enterprise, and I did not once run into the issue the database could not cope with the amount that was requested. Inefficient queries, sure, lots of request to the webserver, sure, but not that the database was struggling and the application was doing just fine. &#xA;&#xA;The fact you should not have to throw more servers at it is what is important. I worked on a simple Java application using Spring Boot and HATEOAS. This application is used by 100s of concurrent users. I only need to run one instance of this application to handle all of that. It is not even one giant instance with lots of resources, it has 2vCPU and 4Gb memory. That is all that is needed to support complex workflows for 100s of concurrent users. The database is a modest t3.small instance. &#xA;&#xA;Code itself&#xA;&#xA;Of course PHP has typehinting these days and namespacing and all good things, but it still suffers from the same problem outlined in this article subtracted with the addendum of this article. The core is trying to get better but it still is weak. I think the author of the article is referring to this ten year opinion. &#xA;&#xA;The tools you get are still slightly different from normal tools. So the things that get built with them are all slightly wonky. &#xA;&#xA;Deployments&#xA;&#xA;To deploy PHP is horrible. Same goes for Python, because it is not a compiled language. So to make artifacts and deploy consistent code is actually quite difficult. Putting them in a container does not help as you always need a webserver to serve the PHP code. Same for Python  where you need something like Gunicorn or similar to wrap around the code. Unless you wrote a server yourself. &#xA;&#xA;It also just is not fun to write PHP.&#xA;&#xA;#code #devops]]&gt;</description>
      <content:encoded><![CDATA[<p>I just skimmed/read <a href="https://getparthenon.com/blog/php-isnt-that-like-really-bad/" rel="nofollow">this</a> article. It states that PHP is just as good as Rust/C/Java. That the opinion that it is bad is just 10 years out of date. </p>

<h1 id="5-years" id="5-years">5 years</h1>

<p>I would say even 5 years ago it was really bad. It was not secure and frameworks were lacking professionalism. To be honest I would say PHP is still bad today.</p>

<h1 id="criticisms" id="criticisms">Criticisms</h1>

<p>The criticisms to bad structure, SQL injections and general security related things are all batted away with one statement: use frameworks. Just use a framework and magically all things are fixed. That is a lie. The fundamental nature of PHP will make it be bad, no matter how many cool awesome things you build on top of it.</p>

<p>Also frameworks themselves are also not foolproof and still will suffer from security flaws. Aside from this there are some other problems. Just search for all the CVE&#39;s of your favourite framework. They still occur across the board.</p>

<h2 id="concurrency-parallelism" id="concurrency-parallelism">Concurrency / parallelism</h2>

<p>The main problem with PHP is that it is not async in any way. It does not support threads, multiprocess or other constructs to make it concurrent or scalable in that sense. It just does not utilize the CPU efficiently. This also is combated in the original article by stating just throw more servers at it. Also the database is the bottleneck in all architectures, just scale that first then you can scale the application too.</p>

<p>This is just nonsense. The database is hardly ever the real bottleneck. I made many applications, enterprise and non-enterprise, and I did not once run into the issue the database could not cope with the amount that was requested. Inefficient queries, sure, lots of request to the webserver, sure, but not that the database was struggling and the application was doing just fine.</p>

<p>The fact you should not have to throw more servers at it is what is important. I worked on a simple Java application using Spring Boot and HATEOAS. This application is used by 100s of concurrent users. I only need to run one instance of this application to handle all of that. It is not even one giant instance with lots of resources, it has 2vCPU and 4Gb memory. That is all that is needed to support complex workflows for 100s of concurrent users. The database is a modest t3.small instance.</p>

<h2 id="code-itself" id="code-itself">Code itself</h2>

<p>Of course PHP has typehinting these days and namespacing and all good things, but it still suffers from the same problem outlined in <a href="https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/" rel="nofollow">this</a> article subtracted with the addendum of <a href="http://maettig.com/2020-09-16-revisiting-a-fractal-of-bad-design" rel="nofollow">this</a> article. The core is trying to get better but it still is weak. I think the author of the article is referring to this ten year opinion.</p>

<p>The tools you get are still slightly different from normal tools. So the things that get built with them are all slightly wonky.</p>

<h1 id="deployments" id="deployments">Deployments</h1>

<p>To deploy PHP is horrible. Same goes for Python, because it is not a compiled language. So to make artifacts and deploy consistent code is actually quite difficult. Putting them in a container does not help as you always need a webserver to serve the PHP code. Same for Python  where you need something like Gunicorn or similar to wrap around the code. Unless you wrote a server yourself.</p>

<p>It also just is not fun to write PHP.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:devops" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">devops</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/php-is-bad</guid>
      <pubDate>Mon, 05 Jul 2021 09:33:22 +0000</pubDate>
    </item>
    <item>
      <title>Flow like water diverted</title>
      <link>https://stealthycoder.writeas.com/flow-like-water-diverted?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[I have gotten some experience using the Flow constructs in a real scenario and learned some lessons. Therefore I wanted to make some code changes to my original design. !--more--&#xA;&#xA;Integer Subscription&#xA;&#xA;In the subscription we will use a internal ExecutorService to handle the input.&#xA;&#xA;import publishers.IntegerPublisher;&#xA;import java.util.Iterator;&#xA;import java.util.concurrent.ExecutorService;&#xA;import java.util.concurrent.Executors;&#xA;import java.util.concurrent.Flow;&#xA;import java.util.concurrent.TimeUnit;&#xA;import java.util.stream.Stream;&#xA;&#xA;public class IntegerSubscription implements Flow.Subscription  {&#xA;&#xA;    private IntegerPublisher integerPublisher;&#xA;    private IteratorInteger integerStream;&#xA;    private final AtomicBoolean isCanceled = new AtomicBoolean();&#xA;    private final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());&#xA;&#xA;    public IntegerSubscription(IntegerPublisher integerPublisher) {&#xA;        this.integerPublisher = integerPublisher;&#xA;        this.integerStream = Stream.iterate(2, i -  i + 1).iterator();&#xA;    }&#xA;&#xA;    @Override&#xA;    public void request(long l) {&#xA;        if ( l &lt; 0) {&#xA;            integerPublisher.publish(new IllegalArgumentException(&#34;Have to request a positive number of elements&#34;));&#xA;        }&#xA;        executorService.submit(this.handleRequests(l));&#xA;        &#xA;    }&#xA;&#xA;    private Runnable handleRequests(long l) {&#xA;        return () -  {&#xA;            for (long i = 0; i &lt; l; i++) {&#xA;                if (isCanceled.get()) {&#xA;                    break;&#xA;                }&#xA;                integerPublisher.publish(integerStream.next());&#xA;            }&#xA;        };&#xA;    }&#xA;&#xA;    @Override&#xA;    public void cancel() {&#xA;        isCanceled.set(true);&#xA;        executorService.shutdown();&#xA;        try {&#xA;            executorService.awaitTermination(5L, TimeUnit.SECONDS);&#xA;        } catch (InterruptedException e) {&#xA;            e.printStackTrace();&#xA;        }&#xA;    }&#xA;}&#xA;&#xA;Publisher&#xA;&#xA;In the publisher take out the executorService parts. One of the major problems was actually that the publisher itself was on the executorService somewhere and so it would never shutdown. Also I did not call the onComplete and therefore the executorService would not shutdown correctly either.&#xA;&#xA;import CyclicRingBuffer;&#xA;import subscriptions.IntegerSubscription;&#xA;&#xA;import java.util.Objects;&#xA;import java.util.concurrent.;&#xA;&#xA;public class IntegerPublisherImpl implements IntegerPublisher  {&#xA;&#xA;    private final IntegerSubscription subscription;&#xA;    private final CyclicRingBufferFlow.Subscriber&lt;? super Integer  subscribers;&#xA;&#xA;    public IntegerPublisherImpl() {&#xA;        this.subscription = new IntegerSubscription(this);&#xA;        subscribers = new CyclicRingBuffer();&#xA;    }&#xA;&#xA;    @Override&#xA;    public void subscribe(Flow.Subscriber? super Integer subscriber) {&#xA;        subscribers.push(subscriber);&#xA;        subscriber.onSubscribe(this.subscription);&#xA;    }&#xA;&#xA;    private void shutdown(boolean cancel) {&#xA;        if (cancel) {&#xA;            this.subscription.cancel();&#xA;        } &#xA;        for (Flow.Subscriber? super Integer subscriber : subscribers) {&#xA;           subscriber.onComplete();&#xA;        }&#xA;&#xA;        executorService.shutdown();&#xA;&#xA;    }&#xA;&#xA;    public void publish(int i) {&#xA;        Flow.Subscriber? super Integer subscriber = subscribers.poll();&#xA;        if (Objects.nonNull(subscriber)) {&#xA;            subscriber.onNext(i);&#xA;        }&#xA;    }&#xA;&#xA;    public void publish(IllegalArgumentException e) {&#xA;        Flow.Subscriber? super Integer subscriber = subscribers.poll();&#xA;        if (Objects.nonNull(subscriber)) {&#xA;            subscriber.onError(e);&#xA;        }&#xA;    }&#xA;&#xA;    public void sendShutdown(boolean cancel) {&#xA;        this.shutdown(cancel);&#xA;    }&#xA;}&#xA;&#xA;I learned that having everything on the ForkJoinPool with work stealing ethics causes a lot, but a lot, context switching and threads. So in my case the CPU just flared 100% on thread switching whilst not much was going on. &#xA;&#xA;Subscriber&#xA;&#xA;The subscriber will ask for Long.MAXVALUE so it is essentially unbounded. Which is also in the documentation, so I should have just read that more carefully and think about it.&#xA;&#xA;import util.StatisticsUtil;&#xA;import java.util.UUID;&#xA;import java.util.concurrent.Flow;&#xA;import java.util.logging.Level;&#xA;import java.util.logging.Logger;&#xA;&#xA;import static util.PrimeUtil.demand;&#xA;import static util.PrimeUtil.primes;&#xA;&#xA;public class PrimeFinder implements Flow.SubscriberInteger {&#xA;&#xA;    private final String name;&#xA;    private static Logger LOGGER;&#xA;&#xA;    public PrimeFinder() {&#xA;        this.name = String.format(&#34;%s-%s&#34;, this.getClass().getName(), UUID.randomUUID());&#xA;        LOGGER = Logger.getLogger(this.name);&#xA;    }&#xA;&#xA;    @Override&#xA;    public void onSubscribe(Flow.Subscription subscription) {&#xA;        StatisticsUtil.stats.putIfAbsent(this.name, 0);&#xA;        subscription.request(Long.MAXVALUE);&#xA;    }&#xA;&#xA;    @Override&#xA;    public void onNext(Integer integer) {&#xA;        LOGGER.log(Level.FINE, String.format(&#34;I&#39;m %s working on %d&#34;, name, integer));&#xA;&#xA;        if (primes.parallelStream().noneMatch(p -  integer % p == 0)) {&#xA;            if(demand.getAndDecrement()   0) {&#xA;                primes.add(integer);&#xA;                LOGGER.log(Level.INFO, String.format(&#34;%d found by me: %s&#34;, integer, name));&#xA;                int newCount = StatisticsUtil.stats.get(this.name) + 1;&#xA;                StatisticsUtil.stats.put(this.name, newCount);&#xA;            }&#xA;        }&#xA;    }&#xA;&#xA;    @Override&#xA;    public void onError(Throwable throwable) {&#xA;        LOGGER.log(Level.SEVERE, throwable.getMessage());&#xA;    }&#xA;&#xA;    @Override&#xA;    public void onComplete() {&#xA;        LOGGER.log(Level.INFO, name + &#34; is done&#34;);&#xA;    }&#xA;}&#xA;&#xA;Main&#xA;&#xA;In the main not a lot gets changed. Number of totalSubscribers gets doubled and sending a true to sendShutdown to make sure the executorServices in question are shutdown and waited for until done. &#xA;&#xA;import publishers.IntegerPublisherImpl;&#xA;import subscribers.PrimeFinder;&#xA;import util.PrimeUtil;&#xA;import util.StatisticsUtil;&#xA;&#xA;import java.util.ArrayList;&#xA;import java.util.List;&#xA;import java.util.concurrent.Flow;&#xA;import java.util.concurrent.TimeUnit;&#xA;import java.util.logging.Level;&#xA;import java.util.logging.Logger;&#xA;&#xA;public class Main {&#xA;    final static int totalSubscribers = Runtime.getRuntime().availableProcessors()  2;&#xA;    private static final Logger LOGGER = Logger.getAnonymousLogger();&#xA;&#xA;    public static void main(String[] args) throws InterruptedException {&#xA;        IntegerPublisherImpl integerPublisher = new IntegerPublisherImpl();&#xA;        ListFlow.Subscriber&lt;Integer  subscribers = new ArrayList();&#xA;&#xA;        for (int i = 0; i &lt; totalSubscribers; i++) {&#xA;            subscribers.add(new PrimeFinder());&#xA;        }&#xA;        subscribers.forEach(integerPublisher::subscribe);&#xA;&#xA;        while (PrimeUtil.demand.get()   0 ) {&#xA;            TimeUnit.MILLISECONDS.sleep(100);&#xA;        }&#xA;        integerPublisher.sendShutdown(true);&#xA;        StatisticsUtil.stats.forEach((name, count) -  LOGGER.log(Level.INFO, String.format(&#34;%s found %d&#34;, name, count)));&#xA;        LOGGER.log(Level.INFO, PrimeUtil.primes.toString());&#xA;    }&#xA;}&#xA;&#xA;This should flow way nicer and smoother. It should also provide a more even distribution amongst the subscribers. I have 8 subscribers and put in 1000 primes and it did it in close to 1 second. Which I find a nice result. It did not put a strain on my CPU as all other applications happily chugged along.  &#xA;&#xA;Final thoughts&#xA;&#xA;I think about extending this into an example that has an error queue and so the publisher can also publish errors and log them. The nice thing is that in this case the publishing will still happen regardless of errors. The previous one would drop the subscriber as it would not request a new one, and therefore it had to wait a whole cycle until it was next to process a request and then it would request a new one. Let&#39;s say all errors happen in a row and all subscribers have to handle errors. Could happen, it is not unfathomable to know multiple errors happen in a row. Then the chain would die due to starvation of no new requests being made. &#xA;&#xA;#code #java]]&gt;</description>
      <content:encoded><![CDATA[<p>I have gotten some experience using the Flow constructs in a real scenario and learned some lessons. Therefore I wanted to make some code changes to my <a href="https://stealthycoder.writeas.com/flow-like-water" rel="nofollow">original design</a>. </p>

<h1 id="integer-subscription" id="integer-subscription">Integer Subscription</h1>

<p>In the subscription we will use a internal ExecutorService to handle the input.</p>

<pre><code class="language-Java">import publishers.IntegerPublisher;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Flow;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

public class IntegerSubscription implements Flow.Subscription  {

    private IntegerPublisher integerPublisher;
    private Iterator&lt;Integer&gt; integerStream;
    private final AtomicBoolean isCanceled = new AtomicBoolean();
    private final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    public IntegerSubscription(IntegerPublisher integerPublisher) {
        this.integerPublisher = integerPublisher;
        this.integerStream = Stream.iterate(2, i -&gt; i + 1).iterator();
    }

    @Override
    public void request(long l) {
        if ( l &lt; 0) {
            integerPublisher.publish(new IllegalArgumentException(&#34;Have to request a positive number of elements&#34;));
        }
        executorService.submit(this.handleRequests(l));
        
    }

    private Runnable handleRequests(long l) {
        return () -&gt; {
            for (long i = 0; i &lt; l; i++) {
                if (isCanceled.get()) {
                    break;
                }
                integerPublisher.publish(integerStream.next());
            }
        };
    }

    @Override
    public void cancel() {
        isCanceled.set(true);
        executorService.shutdown();
        try {
            executorService.awaitTermination(5L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code></pre>

<h1 id="publisher" id="publisher">Publisher</h1>

<p>In the publisher take out the executorService parts. One of the major problems was actually that the publisher itself was on the executorService somewhere and so it would never shutdown. Also I did not call the <code>onComplete</code> and therefore the <code>executorService</code> would not shutdown correctly either.</p>

<pre><code class="language-Java">import CyclicRingBuffer;
import subscriptions.IntegerSubscription;

import java.util.Objects;
import java.util.concurrent.*;

public class IntegerPublisherImpl implements IntegerPublisher  {

    private final IntegerSubscription subscription;
    private final CyclicRingBuffer&lt;Flow.Subscriber&lt;? super Integer&gt;&gt; subscribers;

    public IntegerPublisherImpl() {
        this.subscription = new IntegerSubscription(this);
        subscribers = new CyclicRingBuffer&lt;&gt;();
    }

    @Override
    public void subscribe(Flow.Subscriber&lt;? super Integer&gt; subscriber) {
        subscribers.push(subscriber);
        subscriber.onSubscribe(this.subscription);
    }

    private void shutdown(boolean cancel) {
        if (cancel) {
            this.subscription.cancel();
        } 
        for (Flow.Subscriber&lt;? super Integer&gt; subscriber : subscribers) {
           subscriber.onComplete();
        }

        executorService.shutdown();

    }

    public void publish(int i) {
        Flow.Subscriber&lt;? super Integer&gt; subscriber = subscribers.poll();
        if (Objects.nonNull(subscriber)) {
            subscriber.onNext(i);
        }
    }

    public void publish(IllegalArgumentException e) {
        Flow.Subscriber&lt;? super Integer&gt; subscriber = subscribers.poll();
        if (Objects.nonNull(subscriber)) {
            subscriber.onError(e);
        }
    }

    public void sendShutdown(boolean cancel) {
        this.shutdown(cancel);
    }
}
</code></pre>

<p>I learned that having everything on the ForkJoinPool with work stealing ethics causes a lot, but <strong>a lot</strong>, context switching and threads. So in my case the CPU just flared 100% on thread switching whilst not much was going on.</p>

<h1 id="subscriber" id="subscriber">Subscriber</h1>

<p>The subscriber will ask for <code>Long.MAX_VALUE</code> so it is essentially unbounded. Which is also in the documentation, so I should have just read that more carefully and think about it.</p>

<pre><code class="language-Java">import util.StatisticsUtil;
import java.util.UUID;
import java.util.concurrent.Flow;
import java.util.logging.Level;
import java.util.logging.Logger;

import static util.PrimeUtil.demand;
import static util.PrimeUtil.primes;

public class PrimeFinder implements Flow.Subscriber&lt;Integer&gt; {

    private final String name;
    private static Logger LOGGER;

    public PrimeFinder() {
        this.name = String.format(&#34;%s-%s&#34;, this.getClass().getName(), UUID.randomUUID());
        LOGGER = Logger.getLogger(this.name);
    }

    @Override
    public void onSubscribe(Flow.Subscription subscription) {
        StatisticsUtil.stats.putIfAbsent(this.name, 0);
        subscription.request(Long.MAX_VALUE);
    }

    @Override
    public void onNext(Integer integer) {
        LOGGER.log(Level.FINE, String.format(&#34;I&#39;m %s working on %d&#34;, name, integer));

        if (primes.parallelStream().noneMatch(p -&gt; integer % p == 0)) {
            if(demand.getAndDecrement() &gt; 0) {
                primes.add(integer);
                LOGGER.log(Level.INFO, String.format(&#34;%d found by me: %s&#34;, integer, name));
                int newCount = StatisticsUtil.stats.get(this.name) + 1;
                StatisticsUtil.stats.put(this.name, newCount);
            }
        }
    }

    @Override
    public void onError(Throwable throwable) {
        LOGGER.log(Level.SEVERE, throwable.getMessage());
    }

    @Override
    public void onComplete() {
        LOGGER.log(Level.INFO, name + &#34; is done&#34;);
    }
}
</code></pre>

<h1 id="main" id="main">Main</h1>

<p>In the main not a lot gets changed. Number of <code>totalSubscribers</code> gets doubled and sending a <code>true</code> to <code>sendShutdown</code> to make sure the <code>executorServices</code> in question are shutdown and waited for until done.</p>

<pre><code class="language-Java">import publishers.IntegerPublisherImpl;
import subscribers.PrimeFinder;
import util.PrimeUtil;
import util.StatisticsUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Flow;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Main {
    final static int totalSubscribers = Runtime.getRuntime().availableProcessors() * 2;
    private static final Logger LOGGER = Logger.getAnonymousLogger();

    public static void main(String[] args) throws InterruptedException {
        IntegerPublisherImpl integerPublisher = new IntegerPublisherImpl();
        List&lt;Flow.Subscriber&lt;Integer&gt;&gt; subscribers = new ArrayList&lt;&gt;();

        for (int i = 0; i &lt; totalSubscribers; i++) {
            subscribers.add(new PrimeFinder());
        }
        subscribers.forEach(integerPublisher::subscribe);

        while (PrimeUtil.demand.get() &gt; 0 ) {
            TimeUnit.MILLISECONDS.sleep(100);
        }
        integerPublisher.sendShutdown(true);
        StatisticsUtil.stats.forEach((name, count) -&gt; LOGGER.log(Level.INFO, String.format(&#34;%s found %d&#34;, name, count)));
        LOGGER.log(Level.INFO, PrimeUtil.primes.toString());
    }
}
</code></pre>

<p>This should flow way nicer and smoother. It should also provide a more even distribution amongst the subscribers. I have 8 subscribers and put in 1000 primes and it did it in close to 1 second. Which I find a nice result. It did not put a strain on my CPU as all other applications happily chugged along.</p>

<h1 id="final-thoughts" id="final-thoughts">Final thoughts</h1>

<p>I think about extending this into an example that has an error queue and so the publisher can also publish errors and log them. The nice thing is that in this case the publishing will still happen regardless of errors. The previous one would drop the subscriber as it would not request a new one, and therefore it had to wait a whole cycle until it was next to process a request and then it would request a new one. Let&#39;s say all errors happen in a row and all subscribers have to handle errors. Could happen, it is not unfathomable to know multiple errors happen in a row. Then the chain would die due to starvation of no new requests being made.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/flow-like-water-diverted</guid>
      <pubDate>Wed, 20 Jan 2021 10:43:15 +0000</pubDate>
    </item>
    <item>
      <title>Spring WebFlux Hidden thoughts</title>
      <link>https://stealthycoder.writeas.com/spring-webflux-hidden-thoughts?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[So I recently started using Spring WebFlux and Project Reactor as stated in this post. One more thing I came across as I was debugging why a certain job was not running was that if you do not catch all exceptions and do not have a doOnError statement it will just keep that thought hidden from you and all to itself.  !--more--&#xA;&#xA;Then I sprinkled some log() statements around and it surfaced that the data import/export I was doing had some unfortunate data that Long.parseLong() did not agree with and threw a NumberFormatException. That however was nowhere in my code to catch and so it failed silently. &#xA;&#xA;This meant I could see the job starting and for all intents and purposes see it do nothing afterwards. &#xA;&#xA;Lesson learned, always have a doOnError on each of your flows. &#xA;&#xA;#code #devops #java]]&gt;</description>
      <content:encoded><![CDATA[<p>So I recently started using Spring WebFlux and Project Reactor as stated in <a href="https://stealthycoder.writeas.com/webflux-is-not-for-the-faint-of-heart" rel="nofollow">this</a> post. One more thing I came across as I was debugging why a certain job was not running was that if you do not catch all exceptions and do not have a <code>doOnError</code> statement it will just keep that thought hidden from you and all to itself.  </p>

<p>Then I sprinkled some <code>log()</code> statements around and it surfaced that the data import/export I was doing had some unfortunate data that <code>Long.parseLong()</code> did not agree with and threw a <code>NumberFormatException</code>. That however was nowhere in my code to catch and so it failed silently.</p>

<p>This meant I could see the job starting and for all intents and purposes see it do nothing afterwards.</p>

<p>Lesson learned, always have a <code>doOnError</code> on each of your flows.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:devops" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">devops</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/spring-webflux-hidden-thoughts</guid>
      <pubDate>Tue, 19 Jan 2021 22:35:10 +0000</pubDate>
    </item>
    <item>
      <title>WebFlux is not for the faint of heart</title>
      <link>https://stealthycoder.writeas.com/webflux-is-not-for-the-faint-of-heart?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[I started a project recently using Spring WebFlux which is based upon Project Reactor. I chose this one because it was new and I thought for the client it would suit the best as a lot of data was involved. !--more--&#xA;&#xA;Reactive Programming&#xA;&#xA;The concept this framework is based on is reactive programming. This means you effectively set up conveyor belts on which data will sit and be passed around a factory as part of a chain of operations that will make the raw material into the end product you want. &#xA;&#xA;You get the record from the database, pass it along to the service to transform it into a DTO and then pass it to the controller that transforms it into a HTTPResponse for example. &#xA;&#xA;All of this is non blocking I/O. From the database to the response to the user. This means the CPU is always doing something to progress one process or another. I quite liked this feature. The problem is building these conveyor belts.&#xA;&#xA;Data flow&#xA;&#xA;The flow is sometimes difficult to visualise. It does not help that you can only start flows buy so called subscribing. Then sometimes you want to do two things with the data at two different places but you cannot easily do that. In normal non reactive programming you would for example create a variable that holds some data and send that data to two functions. You could do that asynchronous with CompletableFuture or just regular old synchronous. &#xA;&#xA;I had a hard time grasping every thing and sometimes when things did not work it was because of the flow being wrong or incorrect. Especially when handling errors and stopping the flow. I learned you should handle errors and then send along nulls for example as the next one will not get the null. Optionals might also work but provides more work checking it later in the flow, downstream. &#xA;&#xA;Keep it small&#xA;&#xA;If you keep the functions themselves as small as possible and named correctly you can at least read the flow in a understandable way. It is also important to make it simple at the top and more and more complex the deeper you go. This means if you understand abstractly what needs to happen and then it does not happen you go one layer deeper. Usually the lowest level is fine, i.e. getting the data from some resource. The top level is usually also fine, i.e. sending the response to the user. &#xA;&#xA;It is that middle bit where you do the transformations and business logic where it seems to often go awry. &#xA;&#xA;Adding new functionality to an existing flow is simple and complex at the same time. You have to make sure you give back the same output as before or make sure the input of the next step gets adjusted. It makes it quite finicky to correctly in one try insert new steps. &#xA;&#xA;I would recommend it to at least try out. It might not suit your style, but it does give some great concepts in structuring your application and data flows.&#xA;&#xA;#devlife #code #java]]&gt;</description>
      <content:encoded><![CDATA[<p>I started a project recently using <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux" rel="nofollow">Spring WebFlux</a> which is based upon <a href="https://projectreactor.io/" rel="nofollow">Project Reactor</a>. I chose this one because it was new and I thought for the client it would suit the best as a lot of data was involved. </p>

<h1 id="reactive-programming" id="reactive-programming">Reactive Programming</h1>

<p>The concept this framework is based on is reactive programming. This means you effectively set up conveyor belts on which data will sit and be passed around a factory as part of a chain of operations that will make the raw material into the end product you want.</p>

<p>You get the record from the database, pass it along to the service to transform it into a <code>DTO</code> and then pass it to the controller that transforms it into a <code>HTTPResponse</code> for example.</p>

<p>All of this is non blocking I/O. From the database to the response to the user. This means the CPU is always doing something to progress one process or another. I quite liked this feature. The problem is building these conveyor belts.</p>

<h1 id="data-flow" id="data-flow">Data flow</h1>

<p>The flow is sometimes difficult to visualise. It does not help that you can only start flows buy so called subscribing. Then sometimes you want to do two things with the data at two different places but you cannot easily do that. In normal non reactive programming you would for example create a variable that holds some data and send that data to two functions. You could do that asynchronous with <code>CompletableFuture</code> or just regular old synchronous.</p>

<p>I had a hard time grasping every thing and sometimes when things did not work it was because of the flow being wrong or incorrect. Especially when handling errors and stopping the flow. I learned you should handle errors and then send along <code>null</code>s for example as the next one will not get the <code>null</code>. <code>Optional</code>s might also work but provides more work checking it later in the flow, downstream.</p>

<h1 id="keep-it-small" id="keep-it-small">Keep it small</h1>

<p>If you keep the functions themselves as small as possible and named correctly you can at least read the flow in a understandable way. It is also important to make it simple at the top and more and more complex the deeper you go. This means if you understand abstractly what needs to happen and then it does not happen you go one layer deeper. Usually the lowest level is fine, i.e. getting the data from some resource. The top level is usually also fine, i.e. sending the response to the user.</p>

<p>It is that middle bit where you do the transformations and business logic where it seems to often go awry.</p>

<p>Adding new functionality to an existing flow is simple and complex at the same time. You have to make sure you give back the same output as before or make sure the input of the next step gets adjusted. It makes it quite finicky to correctly in one try insert new steps.</p>

<p>I would recommend it to at least try out. It might not suit your style, but it does give some great concepts in structuring your application and data flows.</p>

<p><a href="https://stealthycoder.writeas.com/tag:devlife" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">devlife</span></a> <a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/webflux-is-not-for-the-faint-of-heart</guid>
      <pubDate>Thu, 14 Jan 2021 09:48:01 +0000</pubDate>
    </item>
    <item>
      <title>Advent of Code 2020 - My foray into Scala</title>
      <link>https://stealthycoder.writeas.com/advent-of-code-2020-my-foray-into-scala?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This year I tried to do the advent of code again, and I got to day 13 this time. Not because I got stuck, it is mainly due to time management issues. !--more--&#xA;&#xA;The code I wrote is on this repo here. I chose the name because I liked the autogenerated one GitHub gave me. Also I am not showing this repo because I want you to view some epic god-like tier code that happens to be Scala, no. It is just to show you what you can do with Scala and how it seems to fit these kind of problems really really well.&#xA;&#xA;Perfect fit&#xA;&#xA;When I started the problems are really simplistic, like doing some mathematical operations on a list of numbers or processing matrices. Some of the earlier ones can be solved naively and in a brute-force kind of way. Later on that won&#39;t work anymore as the inputs will be too big to compute or hold in memory on most devices. &#xA;&#xA;For these kind of problems where a lot happens on lists of things, that is usually the input, Scala just offers a variety of tools to operate on these lists. For instance the .sliding() or .grouped() operations. What they essentially do is go over a list and per whatever size and step size you choose give you back the elements. For instance the list [1,2,3,4,5] with sliding(3,1) operating on it will give back:&#xA;[1,2,3],[2,3,4],[3,4,5]&#xA;&#xA;This operation is very useful in these situations as most often you have to compare the neighbouring elements. So you sort a list, do a sliding operation and then some functional mapping and you get the answer.&#xA;&#xA;Nice structures&#xA;&#xA;The structures arising out of Scala code is one I really like. There exist a couple of concepts and I will only talk about the ones I used. The first is a object. It is similar to a Singleton class idea in normal Java. It holds static methods and variables. This is not to say you cannot have a variable in there outside of methods but it is not usual. &#xA;&#xA;Then exists the normal class like everywhere else. However you can combine this class with an object to create a hybrid. You can therefore apply logic in a nice way and keep everything separated. Then exists the case class concept where you have a very minimal class with just property accessors. You can have these properties be immutable (default) or mutable (use the var keyword in front of it). They can be likened to the new Record concept in Java that also exists in other languages. The case class can have one or more methods, but preferably not. &#xA;&#xA;Then there also exists the concept of a case object. This is super minimal one that does not even take in parameters and holds anything. So why would you use this? Well for example in enumeration it is really helpful or when passing messages. When you want to easily pass around an object that conveys what needs to be done. I used this to represent the cardinal directions. Then I could easily pass around these and use them to implement some logic. &#xA;&#xA;Concurrent programming&#xA;&#xA;This is by far the easiest to do in Scala than compared to Java. You just wrap it in a Future and have an implicit executor. What does it look like? Like this:&#xA;&#xA;def lineofsight(layout: Array[Array[Seat]]): Unit = {&#xA;    var futures : List[Future[Unit]] = List.empty&#xA;&#xA;    futures +:= Future { north(layout) }&#xA;    futures +:= Future { northeast(layout) }&#xA;    futures +:= Future { east(layout) }&#xA;    futures +:= Future { southeast(layout) }&#xA;    futures +:= Future { south(layout) }&#xA;    futures +:= Future { southwest(layout) }&#xA;    futures +:= Future { west(layout) }&#xA;    futures +:= Future { northwest(layout) }&#xA;&#xA;    ConcurrencyUtil.awaitAll(futures)&#xA;&#xA;  }&#xA;&#xA;This is taken from day 11. That is it. Now all those functions will be concurrent. &#xA;&#xA;I hope I will find a project soon where I can use this language to its full potential. &#xA;&#xA;#code #scala]]&gt;</description>
      <content:encoded><![CDATA[<p>This year I tried to do the <a href="https://adventofcode.com/" rel="nofollow">advent of code</a> again, and I got to day 13 this time. Not because I got stuck, it is mainly due to time management issues. </p>

<p>The code I wrote is on this <a href="https://github.com/StealthyCoder/crispy-computing-machine" rel="nofollow">repo</a> here. I chose the name because I liked the autogenerated one GitHub gave me. Also I am not showing this repo because I want you to view some epic god-like tier code that happens to be <a href="https://www.scala-lang.org/" rel="nofollow">Scala</a>, no. It is just to show you what you can do with Scala and how it seems to fit these kind of problems really really well.</p>

<h1 id="perfect-fit" id="perfect-fit">Perfect fit</h1>

<p>When I started the problems are really simplistic, like doing some mathematical operations on a list of numbers or processing matrices. Some of the earlier ones can be solved naively and in a brute-force kind of way. Later on that won&#39;t work anymore as the inputs will be too big to compute or hold in memory on most devices.</p>

<p>For these kind of problems where a lot happens on lists of things, that is usually the input, Scala just offers a variety of tools to operate on these lists. For instance the <code>.sliding()</code> or <code>.grouped()</code> operations. What they essentially do is go over a list and per whatever size and step size you choose give you back the elements. For instance the list <code>[1,2,3,4,5]</code> with <code>sliding(3,1)</code> operating on it will give back:
<code>[1,2,3]</code>,<code>[2,3,4]</code>,<code>[3,4,5]</code></p>

<p>This operation is very useful in these situations as most often you have to compare the neighbouring elements. So you sort a list, do a sliding operation and then some functional mapping and you get the answer.</p>

<h1 id="nice-structures" id="nice-structures">Nice structures</h1>

<p>The structures arising out of Scala code is one I really like. There exist a couple of concepts and I will only talk about the ones I used. The first is a <code>object</code>. It is similar to a <code>Singleton</code> class idea in normal Java. It holds static methods and variables. This is not to say you cannot have a variable in there outside of methods but it is not usual.</p>

<p>Then exists the normal class like everywhere else. However you can combine this class with an object to create a hybrid. You can therefore apply logic in a nice way and keep everything separated. Then exists the <code>case class</code> concept where you have a very minimal class with just property accessors. You can have these properties be immutable (default) or mutable (use the <code>var</code> keyword in front of it). They can be likened to the new <code>Record</code> concept in Java that also exists in other languages. The <code>case class</code> can have one or more methods, but preferably not.</p>

<p>Then there also exists the concept of a <code>case object</code>. This is super minimal one that does not even take in parameters and holds anything. So why would you use this? Well for example in enumeration it is really helpful or when passing messages. When you want to easily pass around an object that conveys what needs to be done. I used this to represent the cardinal directions. Then I could easily pass around these and use them to implement some logic.</p>

<h1 id="concurrent-programming" id="concurrent-programming">Concurrent programming</h1>

<p>This is by far the easiest to do in Scala than compared to Java. You just wrap it in a Future and have an implicit executor. What does it look like? Like this:</p>

<pre><code class="language-scala">def line_of_sight(layout: Array[Array[Seat]]): Unit = {
    var futures : List[Future[Unit]] = List.empty

    futures +:= Future { north(layout) }
    futures +:= Future { north_east(layout) }
    futures +:= Future { east(layout) }
    futures +:= Future { south_east(layout) }
    futures +:= Future { south(layout) }
    futures +:= Future { south_west(layout) }
    futures +:= Future { west(layout) }
    futures +:= Future { north_west(layout) }

    ConcurrencyUtil.awaitAll(futures)

  }
</code></pre>

<p>This is taken from day 11. That is it. Now all those functions will be concurrent.</p>

<p>I hope I will find a project soon where I can use this language to its full potential.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:scala" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">scala</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/advent-of-code-2020-my-foray-into-scala</guid>
      <pubDate>Wed, 30 Dec 2020 15:00:45 +0000</pubDate>
    </item>
    <item>
      <title>Powerful Concept: Let others do the work</title>
      <link>https://stealthycoder.writeas.com/powerful-concept-let-others-do-the-work?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[So this will hopefully convey the message on how to model your code in order to have things done in a nicer way. !--more--&#xA;&#xA;Let&#39;s say you are building an object, you have the materials ready to build it and at some step you have to ask another party for some information. Based on that information you will either add a piece or not to your build. &#xA;&#xA;This means you have to also know the domain knowledge of what that third party knows and also how to attach it to your build. For every one of these kind of steps. &#xA;&#xA;Would it not be nicer to just hand off the build sign an agreement that party is responsible the time it is in their care and have them give it back with or without modifications depending on the same information you had before. &#xA;&#xA;Of course it would be nice to understand what is going on at the party in order to maintain it yourself, but let us just say that it is free forever to have the party maintain your build.&#xA;&#xA;Now in code&#xA;&#xA;Now in code we can do the same, even in Java where everything is passed by value. Just make sure to wrap it in something, a POJO for example or basically anything that is a class instance.&#xA;&#xA;First the normal way of doing things:&#xA;var l = new ArrayListString();&#xA;&#xA;if (l.isEmpty()) {  &#xA;   l.add(&#34;s&#34;);&#xA;}&#xA;if (l.contains(&#34;s&#34;)) {&#xA;     l.removeAll(&#34;s&#34;);&#xA;     l.add(&#34;x&#34;);&#xA;}&#xA;&#xA;Is this a contrived example of course it is. &#xA;&#xA;So we ask first if it is empty then add something. Then otherwise we remove and add elements if it does contain something. What if we did something like the following:&#xA;var l = new ArrayListString();&#xA;&#xA;ConsumerList&lt;String  ifEmptyAddS = (l) -  { var b = l.isEmpty() &amp;&amp; l.add(&#34;s&#34;); };&#xA;ConsumerList&lt;String  removeAllSAddX = (l) -  { l.removeAll(l.stream().filter(s -  s.equalsIgnoreCase(&#34;s&#34;)).collect(Collectors.toList())); l.add(&#34;x&#34;);};&#xA;&#xA;ifEmptyAddS.andThen(removeAllSAddX).accept(l);&#xA;&#xA;Now we just hand over the whole list over to the party and have them operate on it. The flow is very easily managed and if the naming is chosen a bit nicely you can read it out and just see what is going on. Like for example, why is removeAllSAddX doing it in such a complicated way? You can change that if needed, but it works and it might be better for future proofing the process according to them.&#xA;&#xA;It also makes it so you are responsible for making sure the right persons in the right order get your build but they are all responsible for what they do to it. That is a nice separation of concerns. &#xA;&#xA;#devlife #code #java]]&gt;</description>
      <content:encoded><![CDATA[<p>So this will hopefully convey the message on how to model your code in order to have things done in a nicer way. </p>

<p>Let&#39;s say you are building an object, you have the materials ready to build it and at some step you have to ask another party for some information. Based on that information you will either add a piece or not to your build.</p>

<p>This means you have to also know the domain knowledge of what that third party knows and also how to attach it to your build. For every one of these kind of steps.</p>

<p>Would it not be nicer to just hand off the build sign an agreement that party is responsible the time it is in their care and have them give it back with or without modifications depending on the same information you had before.</p>

<p>Of course it would be nice to understand what is going on at the party in order to maintain it yourself, but let us just say that it is free forever to have the party maintain your build.</p>

<h1 id="now-in-code" id="now-in-code">Now in code</h1>

<p>Now in code we can do the same, even in Java where everything is passed by value. Just make sure to wrap it in something, a POJO for example or basically anything that is a class instance.</p>

<p>First the normal way of doing things:</p>

<pre><code class="language-Java">var l = new ArrayList&lt;String&gt;();

if (l.isEmpty()) {  
   l.add(&#34;s&#34;);
}
if (l.contains(&#34;s&#34;)) {
     l.removeAll(&#34;s&#34;);
     l.add(&#34;x&#34;);
}

</code></pre>

<p>Is this a contrived example of course it is.</p>

<p>So we ask first if it is empty then add something. Then otherwise we remove and add elements if it does contain something. What if we did something like the following:</p>

<pre><code class="language-Java">var l = new ArrayList&lt;String&gt;();

Consumer&lt;List&lt;String&gt;&gt; ifEmptyAddS = (l) -&gt; { var b = l.isEmpty() &amp;&amp; l.add(&#34;s&#34;); };
Consumer&lt;List&lt;String&gt;&gt; removeAllSAddX = (l) -&gt; { l.removeAll(l.stream().filter(s -&gt; s.equalsIgnoreCase(&#34;s&#34;)).collect(Collectors.toList())); l.add(&#34;x&#34;);};

ifEmptyAddS.andThen(removeAllSAddX).accept(l);
</code></pre>

<p>Now we just hand over the whole list over to the party and have them operate on it. The flow is very easily managed and if the naming is chosen a bit nicely you can read it out and just see what is going on. Like for example, why is <code>removeAllSAddX</code> doing it in such a complicated way? You can change that if needed, but it works and it might be better for future proofing the process according to them.</p>

<p>It also makes it so you are responsible for making sure the right persons in the right order get your build but they are all responsible for what they do to it. That is a nice separation of concerns.</p>

<p><a href="https://stealthycoder.writeas.com/tag:devlife" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">devlife</span></a> <a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/powerful-concept-let-others-do-the-work</guid>
      <pubDate>Thu, 10 Dec 2020 22:26:43 +0000</pubDate>
    </item>
    <item>
      <title>Powerful concept: FunctionMap</title>
      <link>https://stealthycoder.writeas.com/powerful-concept-functionmap?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This idea comes from JavaScript when there were no classes yet as there are now in ES6. You would write something like this: !--more--&#xA;&#xA;var greetings = {&#xA; hello: function() { console.info(&#34;Hello&#34;); }&#xA;};&#xA;greetings.hello();&#xA;greetings&#34;hello&#34;;&#xA;This is how functions could be shipped around. So the idea is simple, especially the second one. I started to wonder if we can have a Map of String -  Function in other languages like Java, Python, PHP and more?&#xA;&#xA;Java&#xA;&#xA;We sure can. I was working on a JSON-RPC project where you don&#39;t send entity bodies but you send what method to invoke and with what arguments. In the backend we made it so internally a consistent object was shipped around (RPCServiceResult) and we had Enum for the methods that were allowed. So I set up an EnumMap of Enum -  Function. This made it so the entrypoint of each service was the same. See if the method key exists, if so execute the corresponding function with the given input otherwise throw a MethodNotFound error. This meant we could extend the Enum and EnumMap and the Function mapping but never had to change how the services called each other. &#xA;&#xA;Python&#xA;&#xA;In Python I was working on a silly hacking simulation game in the Console. I wanted to have a list of commands and execute the corresponding function that was that command in game terms. At this point I just came from PHP and there it is completely normal to execute the string itself. I will come back to this in a bit. This is more difficult to do in Python and so I came up with a dict where command name was the key and function references were the values. This made it super simple to maintain. &#xA;&#xA;PHP&#xA;&#xA;So in PHP this is normal:&#xA;function a(){ echo &#34;A&#34;; };&#xA;$a = &#34;a&#34;;&#xA;$a();&#xA;However it is really difficult to maintain and see what is going on, let alone insecure to do this if the input to $a is user input. The following makes more sense and is easier to maintain.&#xA;&#xA;function a() { echo &#34;A&#34;; };&#xA;$commands = [&#34;a&#34; =  function() { calluserfunc(&#34;a&#34;); }];&#xA;if ( arraykeyexists(&#34;a&#34;, $commands) ) { $commands&#34;a&#34;; }&#xA;&#xA;Granted this is a contrived example but I hope it gets the point across. &#xA;&#xA;Scala&#xA;&#xA;I was working on the Advent of Code 2020 and one of the puzzles had a lot of validation rules. Immediately the structure came to mind of having a Map of Functions, for each field to validate the corresponding function. This worked like a charm and it is very easy to see what each rule does. &#xA;&#xA;Java&#xA;&#xA;Another example was that in a particular flow there was a need to either create a User of type A or type B and then continue the flow. It was first like the following:&#xA;if ( type == &#34;UserA&#34; ) {&#xA;    return new UserA();&#xA;} else {&#xA;    return new UserB();&#xA;}&#xA;Now never mind the bug of always returning type B, I suggested the following:&#xA;MapString, Supplier&lt;User  userSupplier = new HashMap(){{ put(&#34;UserA&#34;, UserA::new); put(&#34;UserB&#34;, UserB::new); }};&#xA;Now you could replace it with one entrypoint:&#xA;return userSupplier.getOrDefault(type, UserB::new).get();&#xA;You still have the bug, but it became a feature. So we leave it in.&#xA;The colleague immediately said, this happens in way more places in the code and I can change all of them. &#xA;&#xA;The nice thing again is, we can extend the map to support more types but it does not change the logic of calling the service.&#xA;&#xA;Conclusion&#xA;&#xA;I hope this concept proves useful to you, I find it quite powerful and easy to construct and it gives lots of nice patterns. &#xA;&#xA;#code #javascript #java #python]]&gt;</description>
      <content:encoded><![CDATA[<p>This idea comes from JavaScript when there were no classes yet as there are now in ES6. You would write something like this: </p>

<pre><code class="language-javascript">var greetings = {
 hello: function() { console.info(&#34;Hello&#34;); }
};
greetings.hello();
greetings[&#34;hello&#34;]();
</code></pre>

<p>This is how functions could be shipped around. So the idea is simple, especially the second one. I started to wonder if we can have a <code>Map</code> of <code>String -&gt; Function</code> in other languages like Java, Python, PHP and more?</p>

<h1 id="java" id="java">Java</h1>

<p>We sure can. I was working on a JSON-RPC project where you don&#39;t send entity bodies but you send what method to invoke and with what arguments. In the backend we made it so internally a consistent object was shipped around (<code>RPCServiceResult</code>) and we had <code>Enum</code> for the methods that were allowed. So I set up an <code>EnumMap</code> of <code>Enum -&gt; Function</code>. This made it so the entrypoint of each service was the same. See if the method key exists, if so execute the corresponding function with the given input otherwise throw a <code>MethodNotFound</code> error. This meant we could extend the Enum and EnumMap and the Function mapping but never had to change how the services called each other.</p>

<h1 id="python" id="python">Python</h1>

<p>In Python I was working on a silly hacking simulation game in the Console. I wanted to have a list of commands and execute the corresponding function that was that command in game terms. At this point I just came from PHP and there it is completely normal to execute the string itself. I will come back to this in a bit. This is more difficult to do in Python and so I came up with a dict where command name was the key and function references were the values. This made it super simple to maintain.</p>

<h1 id="php" id="php">PHP</h1>

<p>So in PHP this is normal:</p>

<pre><code class="language-php">function a(){ echo &#34;A&#34;; };
$a = &#34;a&#34;;
$a();
</code></pre>

<p>However it is really difficult to maintain and see what is going on, let alone insecure to do this if the input to <code>$a</code> is user input. The following makes more sense and is easier to maintain.</p>

<pre><code class="language-php">function a() { echo &#34;A&#34;; };
$commands = [&#34;a&#34; =&gt; function() { call_user_func(&#34;a&#34;); }];
if ( array_key_exists(&#34;a&#34;, $commands) ) { $commands[&#34;a&#34;](); }
</code></pre>

<p>Granted this is a contrived example but I hope it gets the point across.</p>

<h1 id="scala" id="scala">Scala</h1>

<p>I was working on the Advent of Code 2020 and one of the puzzles had a lot of validation rules. Immediately the structure came to mind of having a Map of Functions, for each field to validate the corresponding function. This worked like a charm and it is very easy to see what each rule does.</p>

<h1 id="java-1" id="java-1">Java</h1>

<p>Another example was that in a particular flow there was a need to either create a User of type A or type B and then continue the flow. It was first like the following:</p>

<pre><code class="language-java">if ( type == &#34;UserA&#34; ) {
    return new UserA();
} else {
    return new UserB();
}
</code></pre>

<p>Now never mind the bug of always returning type B, I suggested the following:</p>

<pre><code class="language-java">Map&lt;String, Supplier&lt;User&gt;&gt; userSupplier = new HashMap&lt;&gt;(){{ put(&#34;UserA&#34;, UserA::new); put(&#34;UserB&#34;, UserB::new); }};
</code></pre>

<p>Now you could replace it with one entrypoint:</p>

<pre><code class="language-java">return userSupplier.getOrDefault(type, UserB::new).get();
</code></pre>

<p>You still have the bug, but it became a feature. So we leave it in.
The colleague immediately said, this happens in way more places in the code and I can change all of them.</p>

<p>The nice thing again is, we can extend the map to support more types but it does not change the logic of calling the service.</p>

<h1 id="conclusion" id="conclusion">Conclusion</h1>

<p>I hope this concept proves useful to you, I find it quite powerful and easy to construct and it gives lots of nice patterns.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:javascript" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">javascript</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a> <a href="https://stealthycoder.writeas.com/tag:python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">python</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/powerful-concept-functionmap</guid>
      <pubDate>Mon, 07 Dec 2020 23:10:38 +0000</pubDate>
    </item>
    <item>
      <title>Fragility of progress</title>
      <link>https://stealthycoder.writeas.com/fragility-of-progress?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This article concerns Web Components, Mozilla, Google and something GitHub created called Catalyst touching on ideas and that sometimes pride can get in the way of good things. !--more--&#xA;&#xA;Catalyst is something released by GitHub that is their vanilla JavaScript library of good patterns to make web components more easily. They themselves use it to make the UI of GitHub. This got me thinking on Web Components again and recently I took the journey to whatever happened to the rel=import in HTML link tag. &#xA;&#xA;Web Components&#xA;&#xA;This idea started a while back already, maybe around six years ago or so. The idea that you would be able to create custom elements (tags) in HTML with their own scoped CSS and JavaScript in so called Shadow DOM so you could better create reusable components and complex UIs with modern paradigms. Also making HTML carry more of the load and since it should be responsible for structure this is a good move to make.&#xA;&#xA;This all sounds great, we currently have a bunch of them; Shadow DOM, Custom Elements and templates and slots. I won&#39;t go into too much detail concerning these but one thing is missing from this and Google thought of it.&#xA;&#xA;Imports&#xA;&#xA;Being able to import HTML files into your current web page that holds all those custom elements code would be amazing. Google thought of this, and implemented it. It even made a framework around it, Polymer. It moved too fast though. Other vendors, at the time Microsoft and Mozilla did not want to implement it. Seemingly it was because Microsoft could not implement it for Internet Explorer and Edge was quite a long ways away. Mozilla just did not want to because it found that imports were already solved by ES modules that you could import. You can read about that here. Note that Google abandoned it in version 73 that is from 2019-03-12. So not that long ago. &#xA;&#xA;Modules&#xA;&#xA;These days you can make so called modules and they can relatively import each other. The caveat is that is done with JavaScript only. It is true that part of making it work with custom elements is JavaScript but the main part are the template and slot tags that make them work. So this would mean you can currently put the code in modules and still have to have the HTML strewn about. &#xA;&#xA;Broken ideas&#xA;&#xA;So currently we have a broken idea, that will never be implemented because Mozilla is too egotistical. The idea is a good idea, even though it came from your competitor does not make the idea any less viable. I am with Mozilla, I do not like Google on the whole either and I am very happy Mozilla stays in the browser war fight. I use Firefox to type this article currently, and it is my preferred browser by far for a long time already. Still this idea looked so cool and still looks like such a boon to Web development on the whole. The source of an idea does not affect the idea. It does affect how it will be received, conveyed and communicated though. &#xA;&#xA;New Framework&#xA;&#xA;I also followed this CommitStrip comic, I have a cool idea for a framework though. &#xA;&#xA;First let me say this problem can be fixed server side for sure. Just like HTML templates exist there for MVC frameworks you can include and load and do things there that will substitute the need for the rel=import, however that implies you need an application server again to support this. I think it is stronger to have the browser be able to do this. Therefore, I propose the following.&#xA;&#xA;Have an entrypoint in a normal script tag that sets some data. Or load it in an index.mjs, just one entrypoint. The entrypoint will use a single method of the framework feeding a config object that will download the html files and inject them into the page. Setting up all the Custom Elements for you, bringing the rel=import back into the browser. &#xA;&#xA;In all seriousness, I wish Mozilla and Google would reconcile and implement this. &#xA;&#xA;#devlife #code]]&gt;</description>
      <content:encoded><![CDATA[<p>This article concerns Web Components, Mozilla, Google and something GitHub created called Catalyst touching on ideas and that sometimes pride can get in the way of good things. </p>

<p><a href="https://github.github.io/catalyst/guide/introduction/" rel="nofollow">Catalyst</a> is something released by GitHub that is their vanilla JavaScript library of good patterns to make web components more easily. They themselves use it to make the UI of GitHub. This got me thinking on Web Components again and recently I took the journey to whatever happened to the <code>rel=import</code> in HTML <code>&lt;link&gt;</code> tag.</p>

<h1 id="web-components" id="web-components">Web Components</h1>

<p>This idea started a while back already, maybe around six years ago or so. The idea that you would be able to create custom elements (tags) in HTML with their own scoped CSS and JavaScript in so called Shadow DOM so you could better create reusable components and complex UIs with modern paradigms. Also making HTML carry more of the load and since it should be responsible for structure this is a good move to make.</p>

<p>This all sounds great, we currently have a bunch of them; <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM" rel="nofollow">Shadow DOM</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements" rel="nofollow">Custom Elements</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots" rel="nofollow">templates and slots</a>. I won&#39;t go into too much detail concerning these but one thing is missing from this and Google thought of it.</p>

<h1 id="imports" id="imports">Imports</h1>

<p>Being able to import HTML files into your current web page that holds all those custom elements code would be amazing. Google thought of this, and implemented it. It even made a framework around it, <a href="https://www.polymer-project.org/" rel="nofollow">Polymer</a>. It moved too fast though. Other vendors, at the time Microsoft and Mozilla did not want to implement it. Seemingly it was because Microsoft could not implement it for Internet Explorer and Edge was quite a long ways away. Mozilla just did not want to because it found that imports were already solved by ES modules that you could import. You can read about that <a href="https://hacks.mozilla.org/2015/06/the-state-of-web-components/" rel="nofollow">here</a>. Note that Google abandoned it in version 73 that is from 2019-03-12. So not that long ago.</p>

<h1 id="modules" id="modules">Modules</h1>

<p>These days you can make so called modules and they can relatively import each other. The caveat is that is done with JavaScript only. It is true that part of making it work with custom elements is JavaScript but the main part are the <code>&lt;template&gt;</code> and <code>&lt;slot&gt;</code> tags that make them work. So this would mean you can currently put the code in modules and still have to have the HTML strewn about.</p>

<h1 id="broken-ideas" id="broken-ideas">Broken ideas</h1>

<p>So currently we have a broken idea, that will never be implemented because Mozilla is too egotistical. The idea is a good idea, even though it came from your competitor does not make the idea any less viable. I am with Mozilla, I do not like Google on the whole either and I am very happy Mozilla stays in the browser war fight. I use Firefox to type this article currently, and it is my preferred browser by far for a long time already. Still this idea looked so cool and still looks like such a boon to Web development on the whole. The source of an idea does not affect the idea. It does affect how it will be received, conveyed and communicated though.</p>

<h1 id="new-framework" id="new-framework">New Framework</h1>

<p>I also followed this <a href="https://www.commitstrip.com/en/2020/01/08/unintentional-framework/" rel="nofollow">CommitStrip comic</a>, I have a cool idea for a framework though.</p>

<p>First let me say this problem can be fixed server side for sure. Just like HTML templates exist there for MVC frameworks you can include and load and do things there that will substitute the need for the <code>rel=import</code>, however that implies you need an application server again to support this. I think it is stronger to have the browser be able to do this. Therefore, I propose the following.</p>

<p>Have an entrypoint in a normal <code>&lt;script&gt;</code> tag that sets some data. Or load it in an <code>index.mjs</code>, just one entrypoint. The entrypoint will use a single method of the framework feeding a config object that will download the <code>html</code> files and inject them into the page. Setting up all the Custom Elements for you, bringing the <code>rel=import</code> back into the browser.</p>

<p>In all seriousness, I wish Mozilla and Google would reconcile and implement this.</p>

<p><a href="https://stealthycoder.writeas.com/tag:devlife" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">devlife</span></a> <a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/fragility-of-progress</guid>
      <pubDate>Thu, 03 Dec 2020 21:26:15 +0000</pubDate>
    </item>
    <item>
      <title>Quirky, weird and fun pattern for Java</title>
      <link>https://stealthycoder.writeas.com/quirky-weird-and-fun-pattern-for-java?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[To be honest I have no idea what you can do with the following pattern and if it is good at all. It just a thought I had and it felt like there was something there, so I decided to write it down. Hopefully you can use the following pattern for something. !--more--&#xA;&#xA;import java.util.function.Supplier;&#xA;import java.util.UUID;&#xA;&#xA;public class Quirky {&#xA;  private SupplierUUID id;&#xA;  private SupplierString name;&#xA;&#xA;  public SupplierUUID getId() {&#xA;    return this.id;&#xA;  }&#xA;&#xA;  public SupplierString getName() {&#xA;    return this.name;&#xA;  }&#xA;&#xA;  public void setId(UUID id) {&#xA;    this.id = () -  { return id; };&#xA;  }&#xA;&#xA;  public void setId(SupplierUUID id) {&#xA;    this.id = id;&#xA;  }&#xA;&#xA;  public void setName(String name) {&#xA;    this.name = () -  { return name; };&#xA;  }&#xA;&#xA;  public void setName(SupplierString name) {&#xA;    this.name = name;&#xA;  }&#xA;&#xA;}&#xA;&#xA;The idea was to turn the properties into Suppliers and therefore you would get to do some functional style flows. I am not sure yet how it will fit in with other patterns. For example to set the id you would do :&#xA;Quirky q = new Quirky();&#xA;q.setId(UUID.randomUUID());&#xA;&#xA;Then to retrieve the id you would do :&#xA;&#xA;q.getId().get();&#xA;&#xA;There is the fact you have to do double gets that feel weird. If you wanted to make a random Quirky you could do the following:&#xA;&#xA;Quirky q = new Quirky();&#xA;q.setId(() -  { return UUID.randomUUID();});&#xA;Then every following call to getId().get() will return a new UUID. &#xA;&#xA;One thing I did want to implement were the double setters . One will wrap a value into a simple supplier but you could also augment that. &#xA;&#xA;public void setName(String name) {&#xA;    this.name = () -  { return name.toUpperCase(); };&#xA;  }&#xA;Now the normal method will always return all caps. There can also be logging and other side effects. &#xA;&#xA;Hopefully you will read this and think of something somewhere to use it. Also I have the feeling somewhere functional programmers woke up and are going to bombard me with Monads, Functors and similar corrigenda.  &#xA;&#xA;#code #java]]&gt;</description>
      <content:encoded><![CDATA[<p>To be honest I have no idea what you can do with the following pattern and if it is good at all. It just a thought I had and it felt like there was something there, so I decided to write it down. Hopefully you can use the following pattern for something. </p>

<pre><code class="language-Java">import java.util.function.Supplier;
import java.util.UUID;


public class Quirky {
  private Supplier&lt;UUID&gt; id;
  private Supplier&lt;String&gt; name;


  public Supplier&lt;UUID&gt; getId() {
    return this.id;
  }

  public Supplier&lt;String&gt; getName() {
    return this.name;
  }

  public void setId(UUID id) {
    this.id = () -&gt; { return id; };
  }

  public void setId(Supplier&lt;UUID&gt; id) {
    this.id = id;
  }

  public void setName(String name) {
    this.name = () -&gt; { return name; };
  }

  public void setName(Supplier&lt;String&gt; name) {
    this.name = name;
  }

}

</code></pre>

<p>The idea was to turn the properties into <code>Supplier</code>s and therefore you would get to do some functional style flows. I am not sure yet how it will fit in with other patterns. For example to set the id you would do :</p>

<pre><code class="language-Java">Quirky q = new Quirky();
q.setId(UUID.randomUUID());
</code></pre>

<p>Then to retrieve the id you would do :</p>

<pre><code class="language-Java">q.getId().get();
</code></pre>

<p>There is the fact you have to do double <strong>get</strong>s that feel weird. If you wanted to make a random Quirky you could do the following:</p>

<pre><code class="language-Java">Quirky q = new Quirky();
q.setId(() -&gt; { return UUID.randomUUID();});
</code></pre>

<p>Then every following call to <code>getId().get()</code> will return a new UUID.</p>

<p>One thing I did want to implement were the double <em>setters</em> . One will wrap a value into a simple supplier but you could also augment that.</p>

<pre><code class="language-Java">public void setName(String name) {
    this.name = () -&gt; { return name.toUpperCase(); };
  }
</code></pre>

<p>Now the normal method will always return all caps. There can also be logging and other side effects.</p>

<p>Hopefully you will read this and think of something somewhere to use it. Also I have the feeling somewhere functional programmers woke up and are going to bombard me with Monads, Functors and similar corrigenda.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/quirky-weird-and-fun-pattern-for-java</guid>
      <pubDate>Tue, 06 Oct 2020 22:01:43 +0000</pubDate>
    </item>
    <item>
      <title>Truths in Java</title>
      <link>https://stealthycoder.writeas.com/truths-in-java?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This post is about why you want immutable objects and how to achieve that in various ways. I specify the language as Java this time because I want to showcase the Quarkus framework. This pattern can be used in any language and framework combination using the tools available in that language of course. !--more--&#xA;&#xA;Oracles&#xA;&#xA;Why do objects need to be immutable and what does it even mean? Well to be immutable mean you are not allowed to change a property of the object but you are allowed to assign a whole new reference to the variable for example. Like with String in Java, and with strings in most other languages. You cannot change a part of the String in the middle but you are allowed to assign a new String to a variable declared. &#xA;&#xA;String s = &#34;StealthyCoder&#34;;&#xA;s = &#34;Coding Ninjas&#34;; &#xA;What you want is the fact that s, in this case, will hold a truth and that truth will not easily be changed halfway true except very explicitly. &#xA;&#xA;In this case you want s to be a so called oracle. It needs to be able to tell you what the source of truth is at this specific moment in time. &#xA;&#xA;DTOs&#xA;&#xA;In the REST API world, there is a pattern that consists of DTOs, Entities, Services and Controllers. In which a Controller is responsible for making sure a route has a method associated with it. The Entities are responsible for modeling the Database tables. The Services are responsible for handling Entities and making business logic decisions. The DTOs are responsible for being the truthful state of the world. &#xA;&#xA;This leads to stating that DTOs, and also to an extent Entities, should be immutable as it was just stated that oracles are there to provide truths. In the REST API we will be making, the fact is that whatever the frontend will be sending as an input should be immutable once it is in the backend as we do not want any code to be able to accidentally change something. Also the generation of a response should be once only. &#xA;&#xA;The following project outline and code will provide some examples on how to achieve this using the Quarkus framework.&#xA;&#xA;Outline&#xA;&#xA;├── build.gradle&#xA;├── docker-compose.yml&#xA;├── Dockerfile&#xA;├── gradle.properties&#xA;├── settings.gradle&#xA;└── src&#xA;    └── main&#xA;        ├── java&#xA;        │   └── com&#xA;        │       └── stealthycoder&#xA;        │           └── dto&#xA;        │               ├── models&#xA;        │               │   ├── dto&#xA;        │               │   │   ├── GiftRequestDTO.java&#xA;        │               │   │   └── GiftResponseDTO.java&#xA;        │               │   └── entity&#xA;        │               │       └── Gift.java&#xA;        │               ├── routes&#xA;        │               │   └── gifts&#xA;        │               │       └── GiftResource.java&#xA;        │               └── services&#xA;        │                   └── SantaClausService.java&#xA;        └── resources&#xA;            └── application.properties&#xA;&#xA;build.gradle&#xA;&#xA;The contents of the build.gradle file are as follows:&#xA;plugins {&#xA;    id &#39;java&#39;&#xA;    id &#39;io.quarkus&#39; version &#34;${quarkusVersion}&#34;&#xA;}&#xA;&#xA;repositories {&#xA;     mavenCentral()&#xA;}&#xA;&#xA;test {&#xA;  useJUnitPlatform()&#xA;}&#xA;&#xA;dependencies {&#xA;    implementation &#39;io.quarkus:quarkus-resteasy-jackson&#39;&#xA;    implementation &#39;io.quarkus:quarkus-hibernate-orm&#39;&#xA;    implementation &#39;io.quarkus:quarkus-jdbc-postgresql&#39;&#xA;    implementation enforcedPlatform(&#34;io.quarkus:quarkus-bom:${quarkusVersion}&#34;)&#xA;&#xA;    testImplementation &#39;io.quarkus:quarkus-junit5&#39;&#xA;    testImplementation &#39;io.rest-assured:rest-assured&#39;&#xA;}&#xA;group &#39;com.stealthycoder&#39;&#xA;version &#39;0.0.1-SNAPSHOT&#39;&#xA;&#xA;sourceCompatibility = 14&#xA;This just sets up the necessary dependencies for our project and the extensions for Quarkus in order to handle JSON serialization (quarkus-resteasy-jackson) and connect to Postgres (quarkus-jdbc-postgresql) for example. &#xA;&#xA;docker-compose.yml&#xA;&#xA;The contents of the docker-compose.yml file are as follows:&#xA;version: &#39;3.6&#39;&#xA;&#xA;networks:&#xA;  quarkus:&#xA;    name: quarkus&#xA;&#xA;services:&#xA;  api:&#xA;    containername: api.dto.local&#xA;    build:&#xA;      context: .&#xA;      dockerfile: &#39;Dockerfile&#39;&#xA;    environment:&#xA;      PGHOST: database&#xA;      PGUSER: dto&#xA;      PGPASS: dto&#xA;      PGDATABASE: dto&#xA;    ports:&#xA;      &#34;8080:8080&#34;&#xA;    networks:&#xA;      quarkus&#xA;  database:&#xA;    image: postgres:13-alpine&#xA;    containername: db.dto.local&#xA;    environment:&#xA;      POSTGRESPASSWORD: dto&#xA;      POSTGRESUSER: dto&#xA;      POSTGRESDB: dto&#xA;    stdinopen: true&#xA;    tty: true&#xA;    networks:&#xA;      quarkus&#xA;This sets us up so we have a running container and database we can use locally for our development purposes. I chose to build the image for the API because I was reluctant this time to install Gradle on the docker image or indeed use a ready made Gradle image to run the tooling in there. &#xA;&#xA;Dockerfile&#xA;&#xA;The contents of the Dockerfile are as follows:&#xA;FROM adoptopenjdk/openjdk14:alpine-slim&#xA;&#xA;COPY build/com.stealthycoder.dto-0.0.1-SNAPSHOT-runner.jar /srv/http/quarkus.jar&#xA;COPY build/lib /srv/http/lib&#xA;&#xA;CMD [&#34;/opt/java/openjdk/bin/java&#34;, &#34;-jar&#34;, &#34;/srv/http/quarkus.jar&#34; ]&#xA;Very straightforward, copy a jar into a named other jar and copy the lib folder as well as it needs that to be able to load the dependencies and start it. &#xA;The name of the jar depends on the group name and the structure of the package and of a setting in the settings.gradle file.&#xA;&#xA;gradle.properties&#xA;&#xA;The contents of the gradle.properties file is as follows:&#xA;quarkusVersion=1.8.1.Final&#xA;&#xA;settings.gradle&#xA;&#xA;The contents of the settings.gradle file are as follows:&#xA;&#xA;pluginManagement {&#xA;    repositories {&#xA;        mavenLocal()&#xA;        mavenCentral()&#xA;        gradlePluginPortal()&#xA;    }&#xA;}&#xA;rootProject.name = &#39;com.stealthycoder.dto&#39;&#xA;&#xA;That rootProject.name will mostly determine the naming together with the version of build.gradle. &#xA;&#xA;application.properties&#xA;&#xA;The contents of the application.properties file are as follows:&#xA;quarkus.datasource.db-kind = pg&#xA;quarkus.datasource.jdbc.url = jdbc:postgresql://${PGHOST:localhost}/${PGDATABASE:database}&#xA;quarkus.datasource.username=${PGUSER:user}&#xA;quarkus.datasource.password=${PGPASS:password}&#xA;quarkus.hibernate-orm.database.generation=${HIBERNATEGENERATION:drop-and-create}&#xA;quarkus.http.access-log.enabled=true&#xA;quarkus.http.access-log.pattern=&#34;%h &#34;%r&#34; %s&#34;&#xA;quarkus.resteasy.gzip.enabled=true&#xA;quarkus.resteasy.gzip.max-input=10M&#xA;This will set the connection to the database based on Environment variables with some defaults. The HIBERNATEGENERATION should only be set to drop-and-create the very first time you run the application as it will otherwise consistently delete your previous data. &#xA;&#xA;GiftResource.java&#xA;&#xA;The contents of the GiftResource.java are as follows:&#xA;package com.stealthycoder.dto.routes.gifts;&#xA;&#xA;import com.stealthycoder.dto.models.dto.GiftRequestDTO;&#xA;import com.stealthycoder.dto.models.dto.GiftResponseDTO;&#xA;import com.stealthycoder.dto.services.SantaClausService;&#xA;&#xA;import javax.inject.Inject;&#xA;import javax.ws.rs.Consumes;&#xA;import javax.ws.rs.GET;&#xA;import javax.ws.rs.PATCH;&#xA;import javax.ws.rs.POST;&#xA;import javax.ws.rs.Path;&#xA;import javax.ws.rs.PathParam;&#xA;import javax.ws.rs.Produces;&#xA;import javax.ws.rs.core.MediaType;&#xA;import javax.ws.rs.core.Response;&#xA;import java.util.Objects;&#xA;import java.util.UUID;&#xA;&#xA;@Path(&#34;/gift&#34;)&#xA;public final class GiftResource {&#xA;&#xA;    @Inject&#xA;    SantaClausService service;&#xA;&#xA;    @GET&#xA;    @Produces(MediaType.APPLICATIONJSON)&#xA;    @Path(&#34;{id}&#34;)&#xA;    public Response get(@PathParam(&#34;id&#34;) UUID uuid) {&#xA;        GiftResponseDTO gift = service.getGift(uuid);&#xA;        if (Objects.isNull(gift)) {&#xA;            return Response.status(Response.Status.NOTFOUND).build();&#xA;        }&#xA;        return Response.ok(gift).build();&#xA;    }&#xA;&#xA;    @POST&#xA;    @Produces(MediaType.APPLICATIONJSON)&#xA;    @Consumes(MediaType.APPLICATIONJSON)&#xA;    public Response add(GiftRequestDTO giftRequestDTO) {&#xA;        return Response.ok(service.createGift(giftRequestDTO)).build();&#xA;    }&#xA;&#xA;    @PATCH&#xA;    @Produces(MediaType.APPLICATIONJSON)&#xA;    @Consumes(MediaType.APPLICATIONJSON)&#xA;    @Path(&#34;{id}&#34;)&#xA;    public Response update(@PathParam(&#34;id&#34;) UUID uuid, GiftRequestDTO giftRequestDTO) {&#xA;        GiftResponseDTO responseDTO = service.updateGift(uuid, giftRequestDTO);&#xA;        if (Objects.isNull(responseDTO)) {&#xA;            return Response.status(Response.Status.NOTFOUND).build();&#xA;        }&#xA;        return Response.ok(responseDTO).build();&#xA;    }&#xA;&#xA;}&#xA;This file will create routes for GET, POST and PATCH on the path /gift. From this we can also determine that the service SantaClausService returns DTOs and also accepts DTOs. The Produces and Consumes annotations help with making sure the serialization will work alright. So in this case the fact is the method will get an instance of the GiftRequestDTO class to be able to use for further processing.&#xA;&#xA;GiftRequestDTO.java&#xA;&#xA;The contents of the GiftRequestDTO.java file are as follows:&#xA;package com.stealthycoder.dto.models.dto;&#xA;&#xA;import com.fasterxml.jackson.annotation.JsonAutoDetect;&#xA;&#xA;@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)&#xA;public final class GiftRequestDTO {&#xA;    private String name;&#xA;    private String wrapper;&#xA;    private boolean expensive;&#xA;    private boolean fragile;&#xA;&#xA;    public String getName(){&#xA;        return name;&#xA;    }&#xA;&#xA;    public String getWrapper() {&#xA;        return wrapper;&#xA;    }&#xA;&#xA;    public boolean isExpensive() {&#xA;        return expensive;&#xA;    }&#xA;&#xA;    public boolean isFragile() {&#xA;        return fragile;&#xA;    }&#xA;}&#xA;The important bits to note are the fields are all private. Another is that there are only so called getters . The thing that ties it all together is to tell Jackson to allow to use reflection on all fields so it can set even private fields to values. This is what will make the DTO immutable for further processing. Of course there are ways around this as it was just stated that even Jackson can do mutations to private fields. Also the class is marked as final meaning you cannot extend it in some way and therefore cast it and still make changes. &#xA;&#xA;GiftResponseDTO.java &#xA;&#xA;The contents of the GiftResponseDTO.java are as follows:&#xA;package com.stealthycoder.dto.models.dto;&#xA;&#xA;import com.fasterxml.jackson.annotation.JsonAutoDetect;&#xA;&#xA;import java.util.UUID;&#xA;&#xA;@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.PROTECTEDANDPUBLIC)&#xA;public final class GiftResponseDTO {&#xA;    protected UUID id;&#xA;    protected String name;&#xA;    protected String wrapper;&#xA;    protected boolean expensive;&#xA;    protected boolean fragile;&#xA;&#xA;    public final static class Builder {&#xA;        private String name;&#xA;        private String wrapper;&#xA;        private boolean expensive;&#xA;        private boolean fragile;&#xA;        private UUID id;&#xA;&#xA;        public Builder withName(String name) {&#xA;            this.name = name;&#xA;            return this;&#xA;        }&#xA;&#xA;        public Builder withWrapper(String wrapper) {&#xA;            this.wrapper = wrapper;&#xA;            return this;&#xA;        }&#xA;&#xA;        public Builder isExpensive(boolean expensive) {&#xA;            this.expensive = expensive;&#xA;            return this;&#xA;        }&#xA;&#xA;        public Builder isFragile(boolean fragile) {&#xA;            this.fragile = fragile;&#xA;            return this;&#xA;        }&#xA;&#xA;        public Builder withId(UUID id) {&#xA;            this.id = id;&#xA;            return this;&#xA;        }&#xA;&#xA;        public GiftResponseDTO build() {&#xA;            GiftResponseDTO responseDTO = new GiftResponseDTO();&#xA;            responseDTO.name = this.name;&#xA;            responseDTO.wrapper = this.wrapper;&#xA;            responseDTO.expensive = this.expensive;&#xA;            responseDTO.fragile = this.fragile;&#xA;            responseDTO.id = this.id;&#xA;            return responseDTO;&#xA;        }&#xA;    }&#xA;}&#xA;Here there is a bit more going on. First off Jackson is instructed to allow protected fields as well. This time there are no getters or so called setters_. There is a Builder class in there though. This is the so named Builder pattern. The gist is to have a static Builder class that you instantiate and all methods except build() will return the instance itself. This causes a Fluent API to emerge where you can in a declarative way set the properties that you need and then even pass around the Builder instance if you wanted to produce carbon copies but separate instances each time by subsequently calling the build() method. The reason for the protected one is because then the Builder can instantiate a new instance of the class GiftResponseDTO and then be allowed to set the properties. &#xA;&#xA;Gift.java&#xA;&#xA;The contents of the Gift.java file are as follows:&#xA;package com.stealthycoder.dto.models.entity;&#xA;&#xA;import org.hibernate.annotations.Type;&#xA;&#xA;import javax.persistence.Entity;&#xA;import javax.persistence.GeneratedValue;&#xA;import javax.persistence.Id;&#xA;import java.util.Objects;&#xA;import java.util.UUID;&#xA;&#xA;@Entity&#xA;public class Gift {&#xA;    private UUID id;&#xA;    private String name;&#xA;    private String wrappingPaper;&#xA;    private Boolean expensive;&#xA;    private Boolean fragile;&#xA;&#xA;    @Id&#xA;    @GeneratedValue&#xA;    @Type(type = &#34;uuid-char&#34;)&#xA;    public UUID getId() {&#xA;        return id;&#xA;    }&#xA;&#xA;    public void setId(UUID id) {&#xA;        this.id = id;&#xA;    }&#xA;&#xA;    public String getName() {&#xA;        return name;&#xA;    }&#xA;&#xA;    public void setName(String name) {&#xA;        if (Objects.isNull(this.name) &amp;&amp; Objects.nonNull(name)) {&#xA;            this.name = name;&#xA;        }&#xA;    }&#xA;&#xA;    public String getWrappingPaper() {&#xA;        return wrappingPaper;&#xA;    }&#xA;&#xA;    public void setWrappingPaper(String wrappingPaper) {&#xA;        if (Objects.isNull(this.wrappingPaper) &amp;&amp; Objects.nonNull(wrappingPaper)) {&#xA;            this.wrappingPaper = wrappingPaper;&#xA;        }&#xA;    }&#xA;&#xA;    public boolean isExpensive() {&#xA;        return expensive;&#xA;    }&#xA;&#xA;    public void setExpensive(Boolean expensive) {&#xA;        if (Objects.isNull(this.expensive) &amp;&amp; Objects.nonNull(expensive)) {&#xA;            this.expensive = expensive;&#xA;        }&#xA;    }&#xA;&#xA;    public boolean isFragile() {&#xA;        return fragile;&#xA;    }&#xA;&#xA;    public void setFragile(Boolean fragile) {&#xA;        if (Objects.isNull(this.fragile) &amp;&amp; Objects.nonNull(fragile)) {&#xA;            this.fragile = fragile;&#xA;        }&#xA;    }&#xA;}&#xA;So this class has the Entity annotation to mark it as an entity for the Hibernate framework to do it&#39;s magic. There is a novel approach here by having a sort of immutability by allowing the properties to be only set once. This is because the Entity should reflect the database values and it should be explicit when you want to do updates, not just willy-nilly throughout the services. This is the reason for the usage of the Boolean boxing instead of using boolean. A primitive like boolean will automatically become false in the checking for isNull. &#xA;&#xA;SantaClausService.java&#xA;&#xA;The contents of the SantaClausService.java are as follows:&#xA;package com.stealthycoder.dto.services;&#xA;&#xA;import com.stealthycoder.dto.models.dto.GiftRequestDTO;&#xA;import com.stealthycoder.dto.models.dto.GiftResponseDTO;&#xA;import com.stealthycoder.dto.models.entity.Gift;&#xA;&#xA;import javax.enterprise.context.ApplicationScoped;&#xA;import javax.inject.Inject;&#xA;import javax.persistence.EntityManager;&#xA;import javax.persistence.PersistenceContext;&#xA;import javax.transaction.Transactional;&#xA;import java.util.Objects;&#xA;import java.util.UUID;&#xA;&#xA;@ApplicationScoped&#xA;public final class SantaClausService {&#xA;&#xA;    @PersistenceContext&#xA;    EntityManager em;&#xA;&#xA;    @Transactional&#xA;    public GiftResponseDTO createGift(GiftRequestDTO newGift){&#xA;        Gift gift = fromDTO(newGift);&#xA;        em.persist(gift);&#xA;        return toDTO(gift);&#xA;    }&#xA;&#xA;    @Transactional&#xA;    public GiftResponseDTO updateGift(UUID uuid, GiftRequestDTO updatedGiftDto) {&#xA;        Gift originalGift = em.find(Gift.class, uuid);&#xA;        if (Objects.isNull(originalGift)) {&#xA;            return null;&#xA;        }&#xA;&#xA;        Gift updatedGift = fromDTO(updatedGiftDto);&#xA;        updatedGift.setId(uuid);&#xA;        updatedGift.setWrappingPaper(originalGift.getWrappingPaper());&#xA;        updatedGift.setFragile(originalGift.isFragile());&#xA;        updatedGift.setExpensive(originalGift.isExpensive());&#xA;        updatedGift.setName(originalGift.getName());&#xA;&#xA;        updatedGift = em.merge(updatedGift);&#xA;        em.flush();&#xA;&#xA;        return toDTO(updatedGift);&#xA;    }&#xA;&#xA;    public GiftResponseDTO getGift(UUID uuid) {&#xA;        return toDTO(em.find(Gift.class, uuid));&#xA;    }&#xA;&#xA;    private GiftResponseDTO toDTO(Gift gift) {&#xA;        if (Objects.isNull(gift)) {&#xA;            return null;&#xA;        }&#xA;        return new GiftResponseDTO.Builder()&#xA;                .withName(gift.getName())&#xA;                .withWrapper(gift.getWrappingPaper())&#xA;                .isExpensive(gift.isExpensive())&#xA;                .isFragile(gift.isFragile())&#xA;                .withId(gift.getId())&#xA;                .build();&#xA;    }&#xA;&#xA;    private Gift fromDTO(GiftRequestDTO requestDTO) {&#xA;        Gift gift = new Gift();&#xA;        gift.setName(requestDTO.getName());&#xA;        gift.setExpensive(requestDTO.isExpensive());&#xA;        gift.setFragile(requestDTO.isFragile());&#xA;        gift.setWrappingPaper(requestDTO.getWrapper());&#xA;        return gift;&#xA;    }&#xA;}&#xA;So here is the meat of the whole application basically. There are two helper methods that either take in an Entity and transmogrify it into a DTO or the other way around. Here is where we use the Builder to build the DTO. There is only one place now in the application where GiftResponseDTO classes can be instantiated and therefore after this service nobody can change it. The Gift that comes back from the helper method fromDTO might have properties that still can be set. Namely they can be still null. &#xA;&#xA;The create and get methods are quite self explanatory. The update one might require some more explanation. So we get a DTO and we turn it into a Gift entity. Then we get the one that is currently in the database. That will set the Persistence Context to that object. Then we update the Gift from the DTO to set the properties that were not set yet (i.e. are still null), meaning the properties that were set override the ones in the database. Then the em.merge happens which will give back the representation in the database of the newly updated Gift with the correct properties. Then the em.flush call will make sure this is actually persisted/synchronised with the database. &#xA;&#xA;The Transactional annotations make sure the methods will be transactional and that means if something fails at all, it will not be persisted and rolled back. &#xA;&#xA;Getting started&#xA;&#xA;After you copied all the content and setup the project exactly as is and have Gradle installed, run the following command in the root of the project: gradle quarkusBuild . Then run docker-compose up . Next use your favourite API exploration tool to POST something to http://localhost:8080/gift and see what happens. &#xA;&#xA;Conclusion&#xA;&#xA;I hope that the patterns above can be useful for you when you want to have immutability in Java and in general. I think this pattern is quite powerful as it also makes you think about what you are doing and what you want to change and where and why. This makes it transparent who generates the instances, who mutates them and what is being changed. Also I quite like the novel approach of only allowing to set the properties once. &#xA;&#xA;Also I really like Quarkus. It gives you enough control but still allows for very fast development. It has some cool patterns like Event driven design out of the box as well as Reactive programming. Check out their guides. &#xA;&#xA;#code #java]]&gt;</description>
      <content:encoded><![CDATA[<p>This post is about why you want immutable objects and how to achieve that in various ways. I specify the language as Java this time because I want to showcase the <a href="https://quarkus.io/" rel="nofollow">Quarkus framework</a>. This pattern can be used in any language and framework combination using the tools available in that language of course. </p>

<h1 id="oracles" id="oracles">Oracles</h1>

<p>Why do objects need to be immutable and what does it even mean? Well to be immutable mean you are not allowed to change a property of the object but you are allowed to assign a whole new reference to the variable for example. Like with <code>String</code> in Java, and with strings in most other languages. You cannot change a part of the String in the middle but you are allowed to assign a new <code>String</code> to a variable declared.</p>

<pre><code class="language-Java">String s = &#34;StealthyCoder&#34;;
s = &#34;Coding Ninjas&#34;; 
</code></pre>

<p>What you want is the fact that <code>s</code>, in this case, will hold a truth and that truth will not easily be changed halfway true except very explicitly.</p>

<p>In this case you want <code>s</code> to be a so called oracle. It needs to be able to tell you what the source of truth is at this specific moment in time.</p>

<h1 id="dtos" id="dtos">DTOs</h1>

<p>In the REST API world, there is a pattern that consists of <strong>DTOs</strong>, <strong>Entities</strong>, <strong>Services</strong> and <strong>Controllers</strong>. In which a <strong>Controller</strong> is responsible for making sure a route has a method associated with it. The <strong>Entities</strong> are responsible for modeling the Database tables. The <strong>Services</strong> are responsible for handling <strong>Entities</strong> and making business logic decisions. The <strong>DTOs</strong> are responsible for being the truthful state of the world.</p>

<p>This leads to stating that <strong>DTOs</strong>, and also to an extent <strong>Entities</strong>, should be immutable as it was just stated that oracles are there to provide truths. In the REST API we will be making, the fact is that whatever the frontend will be sending as an input should be immutable once it is in the backend as we do not want any code to be able to accidentally change something. Also the generation of a response should be once only.</p>

<p>The following project outline and code will provide some examples on how to achieve this using the Quarkus framework.</p>

<h1 id="outline" id="outline">Outline</h1>

<pre><code>├── build.gradle
├── docker-compose.yml
├── Dockerfile
├── gradle.properties
├── settings.gradle
└── src
    └── main
        ├── java
        │   └── com
        │       └── stealthycoder
        │           └── dto
        │               ├── models
        │               │   ├── dto
        │               │   │   ├── GiftRequestDTO.java
        │               │   │   └── GiftResponseDTO.java
        │               │   └── entity
        │               │       └── Gift.java
        │               ├── routes
        │               │   └── gifts
        │               │       └── GiftResource.java
        │               └── services
        │                   └── SantaClausService.java
        └── resources
            └── application.properties
</code></pre>

<h2 id="build-gradle" id="build-gradle">build.gradle</h2>

<p>The contents of the <code>build.gradle</code> file are as follows:</p>

<pre><code class="language-gradle">plugins {
    id &#39;java&#39;
    id &#39;io.quarkus&#39; version &#34;${quarkusVersion}&#34;
}

repositories {
     mavenCentral()
}

test {
  useJUnitPlatform()
}

dependencies {
    implementation &#39;io.quarkus:quarkus-resteasy-jackson&#39;
    implementation &#39;io.quarkus:quarkus-hibernate-orm&#39;
    implementation &#39;io.quarkus:quarkus-jdbc-postgresql&#39;
    implementation enforcedPlatform(&#34;io.quarkus:quarkus-bom:${quarkusVersion}&#34;)

    testImplementation &#39;io.quarkus:quarkus-junit5&#39;
    testImplementation &#39;io.rest-assured:rest-assured&#39;
}
group &#39;com.stealthycoder&#39;
version &#39;0.0.1-SNAPSHOT&#39;

sourceCompatibility = 14
</code></pre>

<p>This just sets up the necessary dependencies for our project and the extensions for Quarkus in order to handle JSON serialization (<em>quarkus-resteasy-jackson</em>) and connect to Postgres (<em>quarkus-jdbc-postgresql</em>) for example.</p>

<h2 id="docker-compose-yml" id="docker-compose-yml">docker-compose.yml</h2>

<p>The contents of the <code>docker-compose.yml</code> file are as follows:</p>

<pre><code class="language-yaml">version: &#39;3.6&#39;

networks:
  quarkus:
    name: quarkus

services:
  api:
    container_name: api.dto.local
    build:
      context: .
      dockerfile: &#39;Dockerfile&#39;
    environment:
      PG_HOST: database
      PG_USER: dto
      PG_PASS: dto
      PG_DATABASE: dto
    ports:
      - &#34;8080:8080&#34;
    networks:
      - quarkus
  database:
    image: postgres:13-alpine
    container_name: db.dto.local
    environment:
      POSTGRES_PASSWORD: dto
      POSTGRES_USER: dto
      POSTGRES_DB: dto
    stdin_open: true
    tty: true
    networks:
      - quarkus
</code></pre>

<p>This sets us up so we have a running container and database we can use locally for our development purposes. I chose to build the image for the API because I was reluctant this time to install Gradle on the docker image or indeed use a ready made Gradle image to run the tooling in there.</p>

<h2 id="dockerfile" id="dockerfile">Dockerfile</h2>

<p>The contents of the <code>Dockerfile</code> are as follows:</p>

<pre><code class="language-dockerfile">FROM adoptopenjdk/openjdk14:alpine-slim

COPY build/com.stealthycoder.dto-0.0.1-SNAPSHOT-runner.jar /srv/http/quarkus.jar
COPY build/lib /srv/http/lib

CMD [&#34;/opt/java/openjdk/bin/java&#34;, &#34;-jar&#34;, &#34;/srv/http/quarkus.jar&#34; ]
</code></pre>

<p>Very straightforward, copy a jar into a named other jar and copy the <code>lib</code> folder as well as it needs that to be able to load the dependencies and start it.
The name of the jar depends on the group name and the structure of the package and of a setting in the <code>settings.gradle</code> file.</p>

<h2 id="gradle-properties" id="gradle-properties">gradle.properties</h2>

<p>The contents of the <code>gradle.properties</code> file is as follows:</p>

<pre><code class="language-ini">quarkusVersion=1.8.1.Final
</code></pre>

<h2 id="settings-gradle" id="settings-gradle">settings.gradle</h2>

<p>The contents of the <code>settings.gradle</code> file are as follows:</p>

<pre><code class="language-gradle">pluginManagement {
    repositories {
        mavenLocal()
        mavenCentral()
        gradlePluginPortal()
    }
}
rootProject.name = &#39;com.stealthycoder.dto&#39;
</code></pre>

<p>That <em>rootProject.name</em> will mostly determine the naming together with the version of <code>build.gradle</code>.</p>

<h2 id="application-properties" id="application-properties">application.properties</h2>

<p>The contents of the <code>application.properties</code> file are as follows:</p>

<pre><code class="language-ini">quarkus.datasource.db-kind = pg
quarkus.datasource.jdbc.url = jdbc:postgresql://${PG_HOST:localhost}/${PG_DATABASE:database}
quarkus.datasource.username=${PG_USER:user}
quarkus.datasource.password=${PG_PASS:password}
quarkus.hibernate-orm.database.generation=${HIBERNATE_GENERATION:drop-and-create}
quarkus.http.access-log.enabled=true
quarkus.http.access-log.pattern=&#34;%h &#34;%r&#34; %s&#34;
quarkus.resteasy.gzip.enabled=true
quarkus.resteasy.gzip.max-input=10M
</code></pre>

<p>This will set the connection to the database based on <em>Environment</em> variables with some defaults. The <code>HIBERNATE_GENERATION</code> should only be set to <strong>drop-and-create</strong> the very first time you run the application as it will otherwise consistently delete your previous data.</p>

<h2 id="giftresource-java" id="giftresource-java">GiftResource.java</h2>

<p>The contents of the <code>GiftResource.java</code> are as follows:</p>

<pre><code class="language-Java">package com.stealthycoder.dto.routes.gifts;

import com.stealthycoder.dto.models.dto.GiftRequestDTO;
import com.stealthycoder.dto.models.dto.GiftResponseDTO;
import com.stealthycoder.dto.services.SantaClausService;

import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PATCH;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Objects;
import java.util.UUID;

@Path(&#34;/gift&#34;)
public final class GiftResource {

    @Inject
    SantaClausService service;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path(&#34;{id}&#34;)
    public Response get(@PathParam(&#34;id&#34;) UUID uuid) {
        GiftResponseDTO gift = service.getGift(uuid);
        if (Objects.isNull(gift)) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
        return Response.ok(gift).build();
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response add(GiftRequestDTO giftRequestDTO) {
        return Response.ok(service.createGift(giftRequestDTO)).build();
    }

    @PATCH
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Path(&#34;{id}&#34;)
    public Response update(@PathParam(&#34;id&#34;) UUID uuid, GiftRequestDTO giftRequestDTO) {
        GiftResponseDTO responseDTO = service.updateGift(uuid, giftRequestDTO);
        if (Objects.isNull(responseDTO)) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
        return Response.ok(responseDTO).build();
    }

}
</code></pre>

<p>This file will create routes for <em>GET</em>, <em>POST</em> and <em>PATCH</em> on the path <code>/gift</code>. From this we can also determine that the service <code>SantaClausService</code> returns <strong>DTOs</strong> and also accepts <strong>DTOs</strong>. The <code>Produces</code> and <code>Consumes</code> annotations help with making sure the serialization will work alright. So in this case the fact is the method will get an instance of the <code>GiftRequestDTO</code> class to be able to use for further processing.</p>

<h2 id="giftrequestdto-java" id="giftrequestdto-java">GiftRequestDTO.java</h2>

<p>The contents of the <code>GiftRequestDTO.java</code> file are as follows:</p>

<pre><code class="language-Java">package com.stealthycoder.dto.models.dto;

import com.fasterxml.jackson.annotation.JsonAutoDetect;

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public final class GiftRequestDTO {
    private String name;
    private String wrapper;
    private boolean expensive;
    private boolean fragile;

    public String getName(){
        return name;
    }

    public String getWrapper() {
        return wrapper;
    }

    public boolean isExpensive() {
        return expensive;
    }

    public boolean isFragile() {
        return fragile;
    }
}
</code></pre>

<p>The important bits to note are the fields are all <strong><code>private</code></strong>. Another is that there are only so called <em><strong>getters</strong></em> . The thing that ties it all together is to tell Jackson to <em>allow</em> to use reflection on all fields so it can set even private fields to values. This is what will make the DTO immutable for further processing. Of course there are ways around this as it was just stated that even Jackson can do mutations to private fields. Also the class is marked as <code>final</code> meaning you cannot extend it in some way and therefore cast it and still make changes.</p>

<h2 id="giftresponsedto-java" id="giftresponsedto-java">GiftResponseDTO.java</h2>

<p>The contents of the <code>GiftResponseDTO.java</code> are as follows:</p>

<pre><code class="language-Java">package com.stealthycoder.dto.models.dto;

import com.fasterxml.jackson.annotation.JsonAutoDetect;

import java.util.UUID;

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC)
public final class GiftResponseDTO {
    protected UUID id;
    protected String name;
    protected String wrapper;
    protected boolean expensive;
    protected boolean fragile;

    public final static class Builder {
        private String name;
        private String wrapper;
        private boolean expensive;
        private boolean fragile;
        private UUID id;

        public Builder withName(String name) {
            this.name = name;
            return this;
        }

        public Builder withWrapper(String wrapper) {
            this.wrapper = wrapper;
            return this;
        }

        public Builder isExpensive(boolean expensive) {
            this.expensive = expensive;
            return this;
        }

        public Builder isFragile(boolean fragile) {
            this.fragile = fragile;
            return this;
        }

        public Builder withId(UUID id) {
            this.id = id;
            return this;
        }

        public GiftResponseDTO build() {
            GiftResponseDTO responseDTO = new GiftResponseDTO();
            responseDTO.name = this.name;
            responseDTO.wrapper = this.wrapper;
            responseDTO.expensive = this.expensive;
            responseDTO.fragile = this.fragile;
            responseDTO.id = this.id;
            return responseDTO;
        }
    }
}
</code></pre>

<p>Here there is a bit more going on. First off Jackson is instructed to allow protected fields as well. This time there are no <em><strong>getters</strong></em> or so called <em><strong>setters</strong></em>. There is a Builder class in there though. This is the so named Builder pattern. The gist is to have a static Builder class that you instantiate and all methods except <code>build()</code> will return the instance itself. This causes a Fluent API to emerge where you can in a declarative way set the properties that you need and then even pass around the Builder instance if you wanted to produce carbon copies but separate instances each time by subsequently calling the <code>build()</code> method. The reason for the protected one is because then the Builder can instantiate a new instance of the class <code>GiftResponseDTO</code> and then be allowed to set the properties.</p>

<h2 id="gift-java" id="gift-java">Gift.java</h2>

<p>The contents of the <code>Gift.java</code> file are as follows:</p>

<pre><code class="language-Java">package com.stealthycoder.dto.models.entity;

import org.hibernate.annotations.Type;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Objects;
import java.util.UUID;

@Entity
public class Gift {
    private UUID id;
    private String name;
    private String wrappingPaper;
    private Boolean expensive;
    private Boolean fragile;


    @Id
    @GeneratedValue
    @Type(type = &#34;uuid-char&#34;)
    public UUID getId() {
        return id;
    }

    public void setId(UUID id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if (Objects.isNull(this.name) &amp;&amp; Objects.nonNull(name)) {
            this.name = name;
        }
    }

    public String getWrappingPaper() {
        return wrappingPaper;
    }

    public void setWrappingPaper(String wrappingPaper) {
        if (Objects.isNull(this.wrappingPaper) &amp;&amp; Objects.nonNull(wrappingPaper)) {
            this.wrappingPaper = wrappingPaper;
        }
    }

    public boolean isExpensive() {
        return expensive;
    }

    public void setExpensive(Boolean expensive) {
        if (Objects.isNull(this.expensive) &amp;&amp; Objects.nonNull(expensive)) {
            this.expensive = expensive;
        }
    }

    public boolean isFragile() {
        return fragile;
    }

    public void setFragile(Boolean fragile) {
        if (Objects.isNull(this.fragile) &amp;&amp; Objects.nonNull(fragile)) {
            this.fragile = fragile;
        }
    }
}
</code></pre>

<p>So this class has the <code>Entity</code> annotation to mark it as an entity for the Hibernate framework to do it&#39;s magic. There is a novel approach here by having a sort of immutability by allowing the properties to be only set once. This is because the <strong>Entity</strong> should reflect the database values and it should be explicit when you want to do updates, not just willy-nilly throughout the services. This is the reason for the usage of the <code>Boolean</code> boxing instead of using <code>boolean</code>. A primitive like <code>boolean</code> will automatically become <code>false</code> in the checking for <code>isNull</code>.</p>

<h2 id="santaclausservice-java" id="santaclausservice-java">SantaClausService.java</h2>

<p>The contents of the <code>SantaClausService.java</code> are as follows:</p>

<pre><code class="language-Java">package com.stealthycoder.dto.services;

import com.stealthycoder.dto.models.dto.GiftRequestDTO;
import com.stealthycoder.dto.models.dto.GiftResponseDTO;
import com.stealthycoder.dto.models.entity.Gift;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.Objects;
import java.util.UUID;

@ApplicationScoped
public final class SantaClausService {

    @PersistenceContext
    EntityManager em;

    @Transactional
    public GiftResponseDTO createGift(GiftRequestDTO newGift){
        Gift gift = fromDTO(newGift);
        em.persist(gift);
        return toDTO(gift);
    }

    @Transactional
    public GiftResponseDTO updateGift(UUID uuid, GiftRequestDTO updatedGiftDto) {
        Gift originalGift = em.find(Gift.class, uuid);
        if (Objects.isNull(originalGift)) {
            return null;
        }

        Gift updatedGift = fromDTO(updatedGiftDto);
        updatedGift.setId(uuid);
        updatedGift.setWrappingPaper(originalGift.getWrappingPaper());
        updatedGift.setFragile(originalGift.isFragile());
        updatedGift.setExpensive(originalGift.isExpensive());
        updatedGift.setName(originalGift.getName());

        updatedGift = em.merge(updatedGift);
        em.flush();

        return toDTO(updatedGift);
    }

    public GiftResponseDTO getGift(UUID uuid) {
        return toDTO(em.find(Gift.class, uuid));
    }

    private GiftResponseDTO toDTO(Gift gift) {
        if (Objects.isNull(gift)) {
            return null;
        }
        return new GiftResponseDTO.Builder()
                .withName(gift.getName())
                .withWrapper(gift.getWrappingPaper())
                .isExpensive(gift.isExpensive())
                .isFragile(gift.isFragile())
                .withId(gift.getId())
                .build();
    }

    private Gift fromDTO(GiftRequestDTO requestDTO) {
        Gift gift = new Gift();
        gift.setName(requestDTO.getName());
        gift.setExpensive(requestDTO.isExpensive());
        gift.setFragile(requestDTO.isFragile());
        gift.setWrappingPaper(requestDTO.getWrapper());
        return gift;
    }
}
</code></pre>

<p>So here is the meat of the whole application basically. There are two helper methods that either take in an Entity and transmogrify it into a DTO or the other way around. Here is where we use the Builder to build the DTO. There is only one place now in the application where <code>GiftResponseDTO</code> classes can be instantiated and therefore after this service nobody can change it. The Gift that comes back from the helper method <code>fromDTO</code> might have properties that still can be set. Namely they can be still <code>null</code>.</p>

<p>The <strong>create</strong> and <strong>get</strong> methods are quite self explanatory. The <strong>update</strong> one might require some more explanation. So we get a DTO and we turn it into a Gift entity. Then we get the one that is currently in the database. That will set the Persistence Context to that object. Then we update the Gift from the DTO to set the properties that were not set yet (i.e. are still <code>null</code>), meaning the properties that were set override the ones in the database. Then the <code>em.merge</code> happens which will give back the representation in the database of the newly updated Gift with the correct properties. Then the <code>em.flush</code> call will make sure this is actually persisted/synchronised with the database.</p>

<p>The <code>Transactional</code> annotations make sure the methods will be transactional and that means if something fails at all, it will not be persisted and rolled back.</p>

<h1 id="getting-started" id="getting-started">Getting started</h1>

<p>After you copied all the content and setup the project exactly as is and have <a href="https://gradle.org/" rel="nofollow">Gradle</a> installed, run the following command in the root of the project: <code>gradle quarkusBuild</code> . Then run <code>docker-compose up</code> . Next use your favourite API exploration tool to <code>POST</code> something to <code>http://localhost:8080/gift</code> and see what happens.</p>

<h1 id="conclusion" id="conclusion">Conclusion</h1>

<p>I hope that the patterns above can be useful for you when you want to have immutability in Java and in general. I think this pattern is quite powerful as it also makes you think about what you are doing and what you want to change and where and why. This makes it transparent who generates the instances, who mutates them and what is being changed. Also I quite like the novel approach of only allowing to set the properties once.</p>

<p>Also I really like Quarkus. It gives you enough control but still allows for very fast development. It has some cool patterns like Event driven design out of the box as well as Reactive programming. Check out their <a href="https://quarkus.io/guides/" rel="nofollow">guides</a>.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/truths-in-java</guid>
      <pubDate>Tue, 06 Oct 2020 14:14:20 +0000</pubDate>
    </item>
  </channel>
</rss>