<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Benoît Liessens on Medium]]></title>
        <description><![CDATA[Stories by Benoît Liessens on Medium]]></description>
        <link>https://medium.com/@benoitliessens?source=rss-63b828a4dd3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Benoît Liessens on Medium</title>
            <link>https://medium.com/@benoitliessens?source=rss-63b828a4dd3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:56:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benoitliessens/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[IntelliJ — Replace Structurally]]></title>
            <link>https://benoitliessens.medium.com/intellij-replace-structurally-630700ae6135?source=rss-63b828a4dd3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/630700ae6135</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[intellij]]></category>
            <dc:creator><![CDATA[Benoît Liessens]]></dc:creator>
            <pubDate>Tue, 02 Feb 2021 08:20:19 GMT</pubDate>
            <atom:updated>2021-02-03T08:12:33.167Z</atom:updated>
            <content:encoded><![CDATA[<h3>IntelliJ — Replace Structurally</h3><h4>Leverage your tools</h4><p>Looking back at my years as professional software developer — over 15 years now — I realise some tools are meant to stay. Tools that I gained experience with over the years and that systematically rely on to perform day to day tasks. IntelliJ is definitely such a tool. A colleague introduced to IntelliJ to our team and I did not spent a single working day without it since them. Despite IntelliJ being an established value I‘m always on the lookout to find new features, plugins, keyboard shortcuts etc.</p><p>One feature I discovered long time ago was the <em>Find</em> and <em>Replace Structurally</em> feature but I never really grasped how to use it. It always seemed like a very powerful thing but never felt the needed to explore it in dept. Until recently.</p><p>A few months ago I joined a new software development team that is working on a fairly large Java code base. To improve overall code quality the team is introducing static code analysis. The approach we have taken to fix the revealed issues is to tackle them by severity and by issue type. Which means you get to fix one particular issue throughout the entire source code. One such issue I needed to tackle was to remove all conditional log statements. Simply put: drop the if statement from following fragments:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e943b876884c9c795f68ce22f8601f3e/href">https://medium.com/media/e943b876884c9c795f68ce22f8601f3e/href</a></iframe><p>A simple but repetitive task. And that is yet another problem by itself: it’s boring to endlessly repeat the same fix over and over again. Sure you get faster at it after some iterations (keyboard shortcuts?) … at the cost of reduced focus and potentially more accidental typos. Time for a different approach!</p><p>Instead of spending a hours (days?) on such repetitive work, why not learn something new and try to automate (part of) a solution? That is exactly what what we are about to with IntelliJ <em>Search Structurally</em>.</p><h3>Search Structurally</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ha-WMq7nxsw4ztI2863GBA.png" /><figcaption>Open the tool window</figcaption></figure><p>The Search Structurally tool window is accessible from the <em>Edit -&gt; Find</em> menu. Alternatively open <em>Search Everywhere</em> (double shift) and type “structurally”.</p><p>As you can see on the first screenshot, both <em>Search Structurally</em> and <em>Replace Structurally</em> exist. Whichever you pick, you can easily switch between <em>Search</em> and <em>Replace Structurally</em> with the tools icon in the top right corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZgUMeekMP-opOcL89s5nuQ.png" /></figure><p>On the same menu icon you can also find <em>Existing Templates…</em> I highly recommend you explore the templates to uncover the possibilities of this hidden gem.</p><p>The upper editor pane is where you specify what to search for. You can write (Java) code here. The editor has a syntax checker — a red frame around the editor is shown when the syntax is incorrect. On the top you can limit the search to files of specific type: We’ll target Java sources files here.</p><p>In the upper editor, write (copy-n-paste) this snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5be224601bfca0010018209406f1ebe/href">https://medium.com/media/d5be224601bfca0010018209406f1ebe/href</a></iframe><p>To find the conditional loggers, we need to search for (static) logger fields on which isDebugEnabled() is invoked. The name of the field does not matter, its type on the other hand does. The fields we are interested in must be instances of org.slf4j.Logger. This is where variables come in handy. A variable is anything surrounded with literal $ signs. <br>(Note: I’m not sure what these are called in the official IntelliJ docs, I’ll simply refer to them as variables)</p><p>Variables are highlighted in red and can be associated with filters which operate as additional search criteria. We’ll use a filter with the $logger$ variable to search for instances of class org.slf4j.Logger. <br>Put your cursor on the $logger$ variable (in the first line) and observe the right part of the editor. An option is shown to add a <em>filter</em> to this variable. Click the + sign on the right toolbar and select a <em>Type</em> filter. In the input field write org.slf4j.Logger. The <em>filter</em> is now also shown in the editor pane, next to the $logger$variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVf1eJXKuXG_-7rraJ2bhA.png" /><figcaption>The cursor is positioned on variable $<em>logger</em>$ in the first line.</figcaption></figure><p>Next we proceed with the body of the if statement: We expect this block to contain a log statement using the same $logger$ variable. The actual method name does not matter so we have not specified any <em>filter</em> for$method$. For $args$ however we did: we match for any number of arguments (between zero and infinite).</p><p>If you can’t wait to try this search, switch to <em>Search Structurally</em> and hit the <em>Find</em> button at the bottom of the window to search your own source code.</p><h3>The replacement</h3><p>If you did run the search, open the <em>Replace Structurally</em> tool again, the previously used search template should be there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vITyRtiZXFJzRNMAHqFRVA.png" /></figure><p>The lower editor pane is where we write the replacement. We can reuse any variable used in the search criteria (upper editor). We’ll just copy the body of the if block from the upper editor pane.</p><p>Right below the editor you can define the scope of the search: <em>In Project</em>, <em>Module</em>, <em>Directory</em> or <em>Scope</em>. Pick whatever scope suits you. <br>The purpose of the <em>Search target</em> option isn’t entirely clear to me unfortunately.<br>We are ready to hit the <em>Find</em> button. IntelliJ will open the <em>Find </em>tool window to list all matching code fragments.</p><p>As we defined a <em>replacement </em>expression IntelliJ gives you the option to preview the replacement as well as to replace occurrences one by one or all at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKN1XPYfMQDdJNiaymX8lQ.png" /></figure><p>How neat is that! We built a scripted solution. And … the best is yet to come!</p><h3>Save your endeavour</h3><p>Try the button on the bottom left: <em>Create Inspection from Template… </em>you can save this <em>Structural Replace</em> tool’s configuration as an IntelliJ inspection. When saved as an inspection you can reuse this structural replace operation in the future. You can properly name the inspection and even share it with colleagues. As the inspection is based on a structural replace operation the inspection will find matching code occurrences and allow you to apply the replacement too!</p><p>Below screenshot shows the inspection window. The <em>Structural Search</em> was saved as an inspection named <em>conditional DEBUG logger</em> so we can rerun the inspection by name (<em>Analyze -&gt; Run inspection by Name</em> menu item)<em>. </em>After running the inspection all occurrences are listed in the Inspection tool window. You can simply apply the solution by hitting the <em>Replace Structurally</em> button right away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjL-awqC5wB0AKQAlpMIHw.png" /></figure><p>Open up IntelliJ’s Preferences and got to the <em>Inspections</em>. Your freshly saved work is listed here in section <em>Structural Search</em>. You can edit it’s name and description as well as the underlying structural replace configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xj4l7SmqN3mAi_FHmJOCA.png" /></figure><h3>Final Thoughts</h3><p>No doubt the present solution was helpful to me. Admittedly I don’t expect it to find every possible edge case (e.g. does it work when if block lacks braces?). If the tool can help me reliably fix 90% of occurrences, I’m ok to fix the remaining 10% manually. <br>And true, there is room for improvement too:</p><ul><li>We do not handle cases with multiple statements in the if block such as this:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd6b4061a4c4bdbfc7105054966d466c/href">https://medium.com/media/cd6b4061a4c4bdbfc7105054966d466c/href</a></iframe><ul><li>we do not handle variants likeLOGGER.isInfoEnabled()</li><li>our solution is only suitable for slf4j loggers</li><li>…</li></ul><p>Nevertheless it’s a bloody neat future and it saved me a lot of time. The possibilities with <em>Structural Search</em> are vast, the integration with inspections isa brilliant idea. It’s somewhat sad so say there is so little documentation available for this little gem. <br>But most of all I’m very happy to have conquered yet another feature of this superbe IDE. If anything, I hope many of you will find their way to even better use cases for this superbe feature. ;-)</p><p>Cheers,</p><p>Benoît</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=630700ae6135" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lessons learned with AxonFramework]]></title>
            <link>https://benoitliessens.medium.com/lessons-learned-with-axonframework-4a51d7e17f3e?source=rss-63b828a4dd3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a51d7e17f3e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[cqrs]]></category>
            <dc:creator><![CDATA[Benoît Liessens]]></dc:creator>
            <pubDate>Thu, 27 Dec 2018 21:29:58 GMT</pubDate>
            <atom:updated>2018-12-28T20:32:05.753Z</atom:updated>
            <content:encoded><![CDATA[<h4>Advice from a team lead having integrated AxonFramework in half a dozen applications over the past 3 years</h4><p>It must have been about three to four years ago that I first came across <a href="https://github.com/AxonFramework/AxonFramework">AxonFramework</a>. I head read about DDD and CQRS before but never saw any fully fledged Java framework until then. Fortunately the project had some documentation and a <a href="https://groups.google.com/forum/m/#!forum/axonframework">Google group</a> so I took a deep dive …</p><p>At that time I was architect on a healthcare project — I still am today BTW — and we where about to kickstart a new greenfield application to handle the user accounts of our main customer facing web application. Having acquired enough understanding of DDD, CQRS and the AxonFramework I decided to use it for this new application.</p><h4>Fast forward, December 2018</h4><p>That Axon based application has been in production for quite a while now without major issues — at least not when it comes to the Axon framework. In preparation of the new features the team will be developing it’s a good time to upgrade Axon 2.4 to version 3.x. While doing so I came across a couple of decisions &amp; suggestions I made 3 years ago — when I was still an Axon novice — that are worth a warning.</p><h4>No 1: Where to validate commands</h4><p>I recall having advised to implement the @CommandHandlers outside the aggregate, in a separate Spring component. Most of the commands in that application contain entity references for which validation (of that reference) requires a remote call. I didn’t want to clutter the aggregate class with that and it felt more natural to handle these reference checks in an <em>application layer</em>, before invoking the actual aggregate instance. As a consequence we ended up having to load the aggregate instances from the Repository ourselves and invoke methods on the aggregate to apply() the events.</p><p>This approach resulted in pretty convoluted code. Command validation was done in the application layer as well as in the aggregate. There were no guidelines as to what validation ought to be done where.<br>This approach also forced us to leak aggregate state: most commonly the CommandHandler needs access to aggregate state for validation. With validation happening outside the aggregate, state had to get out of the aggregate too.</p><p>No doubt about it: this was not a good idea!</p><p>The better way is to have Axon load the aggregate instance for you and autowire anything needed for validation through the command handler method.</p><pre>@Aggregate<br>class Bakery {</pre><pre>  private Stock stock; </pre><pre>  @CommandHandler<br>  public void handle(OrderFlourCommand cmd,<br>                     @Autowired BakerySupplier supplier) {<br>     if (stock.belowThreshold()) {<br>       supplier.orderFlour();<br>       apply(new FlourOrderedEvent());<br>     }<br>  }</pre><pre>}</pre><p>Note that the @Autowired annotation is not required. We added it just for readability; to remind us that parameter is resolved to a Spring bean. <br>I remember having struggled to properly configure the Axon infrastructure (SpringBeanParameterResolverFactory) needed for this. Such parameter injection is also supported with @CommandHandler annotated aggregate constructors. The AggregateTestFixture also supports this type of parameter injection. Just register the BakerySupplier as <em>injectable resource</em> in the test fixture.</p><h4>No. 2: Guard your (stored) events</h4><p>I’m sure every CQRS article will tell you that: events are the primary storage mechanism. For as long as your application will be used, you must be able to read any historic event from the event store. Changing the name or structure of an event class should never break compatibility with previously stored events. Be vigilant!</p><p>With that in mind it’s valuable to carefully consider which event serialisation technique to use. Axon supports both XML (XStreamSerializer) and JSON (JacksonSerializer). <br>Whichever you chose take some time to write thorough test cases to guarantee your events remain backwards compatible. You wouldn’t want to break (de)serialization by moving the events to another package or renaming an event’s private field. You might consider to include the Metadata in these tests too.</p><p>XStream for example will — by default — use the fully qualified class name of the event as root tag of the generated XML fragment.</p><p>Given class</p><pre>package com.backery;</pre><pre>public class FlourOrderedEvent {<br>  // omitted fields<br>}</pre><p>XStream will produce</p><pre>&lt;com.backery.FlourOrderedEvent&gt;<br>  &lt;!-- omitted fields --&gt;<br>&lt;/com.backery.FlourOrderedEvent&gt;</pre><p>The implication is that the package where your events classes are defined leaks into your storage — eternally. Is that a problem? Well, not really until you move the events to package com.backery.api. That’s when you will have to deal with the consequences:</p><ol><li>How to deserialize legacy tag &lt;com.backery.FlourOrderedEvent&gt; to event com.backery.<strong>api</strong>.FlourOrderedEvent?</li><li>And how to serialize a new FlourOrderedEvent: Will you use the legacy XML tag as previously (and add technical dept) or use a new tag &lt;com.backery.<strong>api</strong>.FlourOrderedEvent&gt; (and add technical dept)?</li></ol><p>These aspects need to be dealt with early on. Preferably before going to an acceptance environment. Tune XStream til it fits your needs!<br>Already using JSON as storage format? Nice! And have you thought about decoupling your event’s field names from the storage format too? You should.<br>Use the annotations corresponding to your serializer to decouple field names from serialized the xml tags or json keys:</p><pre>public final class FlourOrderedEvent {<br>  @JsonProperty(&quot;id&quot;)<br>  private final BakeryIdentifier bakeryId;<br>  @JsonProperty(&quot;qty&quot;)<br>  private final int quantity;</pre><pre>  @JsonCreator<br>  public FlourOrderedEvent(@JsonProperty(&quot;id&quot;) BakeryIdentifier id,<br>                           @JsonProperty(&quot;qty&quot;) int qty) {<br>    this.bakeryId = id;<br>    this.quantity = qty;<br>  } </pre><pre> // omitted getters<br>}</pre><p>With this in place it’s safe to rename fieldBakeryIdentifier bakeryId to bakery. This will not impact the JSON (de)serialization. XStream has equivalent annotations.</p><h4>No. 3: Keep your API clean</h4><p>As you probably read in several other DDD books or articles, your events represent whatever occurred in your business. The event (class) names should be meaningful to anyone in the business. Normally they pretty well depict the business process your company operates. These events are you API. Hence, any other type used in these events effectively belongs to the API too. <br>I favour rich types; types that better convey what they represent. Instead of using a UUID as (aggregate) identifier type I prefer to wrap that UUID with a more meaningful type such as BakeryIdentifier for example. This is even more true when dealing with several aggregates in a single application.</p><p>The same can be applied to values in your events. Likely some String, Integer or other primitive typed field in the events deserves a proper type. In real life we don’t reason with String or Integers, so why accept them in your application’s API?</p><p>These types belong to the API just like the events themselves. As such, make sure to keep them lightweight. You shouldn’t need a ton of dependencies to compile them. For example, don’t add JPA annotations to these types for sake of reusing them your JPA-based read models. It despises your API and such rich types aren’t really helpful to write nice(r) JPA-queries. Especially not with Spring-JPA.</p><pre>public final class FlourOrderedEvent {<br>  @JsonProperty(&quot;id&quot;)<br>  private final BakeryIdentifier bakeryId;<br>  @JsonProperty(&quot;qty&quot;)<br>  private final int quantity; <br>  @JSonProperty(&quot;unit&quot;) <br>  private final Unit unit;</pre><pre>  @JsonCreator<br>  public FlourOrderedEvent(@JsonProperty(&quot;id&quot;) BakeryIdentifier id,<br>                           @JsonProperty(&quot;qty&quot;) int qty,<br>                           @JsonProperty(&quot;unit&quot;) Unit u) {<br>    this.bakeryId = id;<br>    this.quantity = qty; <br>    this.unit = u;  <br>  }<br>  // omitted getters<br>}</pre><p>In above sample class BakeryIdentifier and Unit belong to the API. The only dependencies are the JRE and Jackson annotation library (Maven coordinatescom.fasterxml.jackson.core:jackson-annotation:${version}).</p><p>That all for now folks, hope you enjoyed the read. Next episode I’ll discuss another command validation anti-pattern.</p><p>Regards,</p><p>Benoît</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a51d7e17f3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>