<?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 Ionut Ciuta on Medium]]></title>
        <description><![CDATA[Stories by Ionut Ciuta on Medium]]></description>
        <link>https://medium.com/@ionutciuta?source=rss-743393d64502------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7KLr1YHIg4WHleIkXHb4mw.jpeg</url>
            <title>Stories by Ionut Ciuta on Medium</title>
            <link>https://medium.com/@ionutciuta?source=rss-743393d64502------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 06:40:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ionutciuta/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[Rules Pattern]]></title>
            <link>https://medium.com/swlh/rules-pattern-1c59854547b?source=rss-743393d64502------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c59854547b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Ionut Ciuta]]></dc:creator>
            <pubDate>Sun, 18 Oct 2020 20:40:58 GMT</pubDate>
            <atom:updated>2020-10-28T05:53:25.145Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKzTR8rLmh8ZCRC6xD9ACg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@joshuamiranda?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Joshua Miranda</a> from <a href="https://www.pexels.com/photo/similar-cubes-with-rules-inscription-on-windowsill-in-building-4027658/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>A few weeks back, someone tagged me in a company wide “Good Practices” challenge and I ended up writing a long post that I shared on Teams. I enjoyed doing that quite a lot and I decided to share it here as well, in a more detailed format. Here’s what I came up with.</p><p>On multiple occasions in my career I was tasked with checking some input data — e.g. an incoming HTTP request — against multiple business rules. Most of the time, my instinct would say “Just drag that thing through some if statements”. However, after doing this a couple of times, I realised that there has to be a better way of implementing this. Managing a big if-else block is not fun especially when the number of conditions you have to check is dynamic and can vary based on business needs. I’m also not very keen on using switch statements for many of the same reasons.</p><p>In my quest to become a more productive programmer, I ended up doing a bit of studying and came across the Rule Pattern. All of the code that you’ll see bellow is hosted <a href="https://github.com/IonutCiuta/applied-design-patterns/tree/master/rules-pattern">here on GitHub</a>. It’s mostly Java with a few <a href="https://spring.io/">Spring</a> annotations on top of it.</p><h3>The problem</h3><p>Say we have an online shop. We want our shop to be smart so that we can give our customers<em> contextual offers</em> based on <em>the content of their basket</em> and other variables such as<em> the date of the order</em>.</p><p><strong>e.g.</strong> It’s October, Halloween 🎃 season is in full effect and, soon after that, Christmas 🎄 is just around the corner. We want our shop to have promotions for both holidays. However we want to apply them accordingly. How should we go about this?</p><p>Let’s say we have this basket:</p><pre>Basket basket = new Basket();<br>basket.addItem(new Item(&quot;The Shinning Book&quot;, 5.0));<br>basket.addItem(new Item(&quot;Hereditary Bluray&quot;, 15.00));<br>basket.addItem(new Item(&quot;The extremely expensive new Iphone&quot;, 1400.00));</pre><p>The easiest way to check what promotions to apply is to just drag the basket through an unpleasant <strong>if-else</strong> <strong>block</strong> or even — God forbid — a <strong>switch</strong> 👻.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7e7d10d79edbb4afc42cfd1b4886dc8/href">https://medium.com/media/b7e7d10d79edbb4afc42cfd1b4886dc8/href</a></iframe><p>Yes, the code above is <em>awful</em>. It <em>breaks</em> many common sense rules. It’s <em>dense</em>, it does <em>too many things</em> and <em>handles</em> <em>too much business</em>. It also <em>resists change</em>. Adding a new rule means adding a new if statement. Also, <em>good luck testing this</em>.</p><p>The way I like to design this is by using <strong>rules</strong>. After I found this pattern, I used this approach on several projects and it proved to be a <strong>flexible way of decomposing large decision logic</strong>.</p><h3>The solution</h3><p>We first need to define what a rule is. A rule should contain <em>the logic that dictates whether or not it can be applied to a target object</em> and <em>the logic that it should apply</em>.</p><pre>public interface IRule&lt;E&gt; {<br>    boolean matches(E input);<br>    void apply(E input);<br>}</pre><p>The rule above is a bit too generic, E is not an actual type. Let’s make it a bit more specific.</p><pre>public interface BasketRule extends IRule&lt;Basket&gt; {}</pre><p>Based on this blueprint, we can set up actual rules that apply promotion logic to our basket. Here is an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf573476325a0ab5909117f33c3ac91e/href">https://medium.com/media/cf573476325a0ab5909117f33c3ac91e/href</a></iframe><p>Our <strong>HalloweenPromotion</strong> gives all of our customers <em>a free skeleton suit</em> 💀 and a <em>13</em> <em>(dollars?) discount</em> based on the logic in the <strong>apply</strong> function. That’s a pretty neat deal if you ask me! However, as per the <strong>matches</strong> function, this is applicable only if the order was created in October and it’s still October when rule is evaluated.</p><p>Let’s add a simpler rule:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f09030b06c320ef9fc9a420825a98902/href">https://medium.com/media/f09030b06c320ef9fc9a420825a98902/href</a></iframe><p>This rule is straightforward. If your order <em>is bigger than 1000</em>, you get a <em>discount of 100</em>. Let’s add a 3rd rule that hopefully won’t be applied during Halloween season:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1383fc171feac6d42b73a9c980fc858/href">https://medium.com/media/d1383fc171feac6d42b73a9c980fc858/href</a></iframe><p>This last rule would give you a free Santa hat 🎅🏻 and a small discount if your order was placed near Christmas. Notice that all the rules described above are annotated with <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/stereotype/Component.html">Spring’s Component</a>. This example works neatly with Spring, but you can apply it just as well for plain Java.</p><pre>@Autowired<br>private List&lt;BasketRule&gt; promotionRules;</pre><p>Through some Spring magic and plain old polymorphism, we now have all our rules nicely grouped together. We just need the logic to apply them which again is super smooth and can be as simple as using streams and Lambdas:</p><pre>promotionRules.stream()<br>    .filter(rule -&gt; rule.matches(basket))<br>    .forEach(rule -&gt; rule.apply(basket));</pre><p>For the sake of coherence, I’ve put these two pieces of code in the <a href="https://github.com/IonutCiuta/applied-design-patterns/blob/master/rules-pattern/src/main/java/com/ionutciuta/patterns/rules/impl/PromotionEngine.java"><strong>PromotionEngine</strong></a> class.</p><h3>Conclusion</h3><p>If you run my demo code, you’ll see the following output:</p><pre>=== BEFORE Promotions ===<br>Basket:<br><strong>Created</strong>: 2020-10-18T21:58:50.760277<br>Name: The Shinning Book<br>Price: 5.0<br>---<br>Name: Hereditary Bluray<br>Price: 15.0<br>---<br>Name: The extremely expensive new Iphone<br>Price: 1400.0<br>---<br>========<br><strong>Total</strong>: 1420.0<br><br>Applying promotions<br>Applying <strong>DiscountForBigOrdersPromotion</strong> promotion <strong>-100.00</strong><br>Applying <strong>HalloweenPromotion</strong> promotion <strong>-13.00</strong><br>Promotions applies<br><br>=== AFTER Promotions ===<br>Basket:<br>Created: 2020-10-18T21:58:50.760277<br>Name: The Shinning Book<br>Price: 5.0<br>---<br>Name: Hereditary Bluray<br>Price: 15.0<br>---<br>Name: The extremely expensive new Iphone<br>Price: 1400.0<br>---<br>Name: <strong>Promo - Creepy Skeleton Suit</strong><br>Price: 0.0<br>---<br>========<br><strong>Total</strong>: 1307.0</pre><p>Let’s take a look at what just happened:</p><ul><li>your basket has <strong>total value</strong> of <strong>1420.0</strong> and was <strong>created in October</strong>.</li><li><strong>two</strong> promotions were applied: <strong>DiscountForBigOrdersPromotion</strong> that gave us<strong> -100 discount</strong> and <strong>HalloweenPromotion</strong> that gave us a <strong>-13 discount.</strong></li><li>most importantly, you get that <strong>free Creepy Skeleton Suit</strong> for your socially distant Halloween party 😉💀</li></ul><p><em>“Ok, but isn’t this more complicated?”</em> You might ask. Well, <strong>not really</strong>. Here’s why:</p><ul><li>you can easily add new rules or remove old ones</li><li>rule specific logic is isolated from other rules</li><li>you can easily test each rule in isolation or you can mock them accordingly</li><li>the code is much cleaner overall</li></ul><h3>Related reads</h3><p>After I posted this on my company’s Teams, a colleague of mine mentioned that there might be a connection between the <strong>Rules Pattern</strong> and the <strong>Chain of Responsibility (CoR) pattern</strong>. While I’ve read about CoR in the past, I felt the need to look up some implementation examples and I stumbled across <a href="https://refactoring.guru/design-patterns/chain-of-responsibility">this thorough article</a>. I highly recommend you read through it. I would say that the Rules Pattern is <strong>a specialisation</strong> of the CoR pattern <strong>with some caveats</strong>.<br>In the version I described, the rules — or handlers as per the mentioned article — are <strong>unordered</strong> and are <strong>applied exhaustively</strong> meaning the input is processed by all rules in no particular order.</p><p>Don’t forget to take a look at the demo code on <a href="https://github.com/IonutCiuta/applied-design-patterns/tree/master/rules-pattern">GitHub</a>.</p><p>Thanks for reading! 🙏🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c59854547b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/rules-pattern-1c59854547b">Rules Pattern</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>