<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Fluent C++</title>
	<atom:link href="https://www.fluentcpp.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.fluentcpp.com/</link>
	<description>Jonathan Boccara&#039;s blog</description>
	<lastBuildDate>Wed, 18 Nov 2020 12:58:30 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.5.3</generator>
<site xmlns="com-wordpress:feed-additions:1">214950964</site>	<item>
		<title>Usage First, Implementation After: A Principle of Software Development</title>
		<link>https://www.fluentcpp.com/2022/06/25/usage-first-implementation-after-a-principle-of-software-development/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Sat, 25 Jun 2022 01:00:54 +0000</pubDate>
				<category><![CDATA[Expressive code]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[expressive]]></category>
		<category><![CDATA[principle]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[usage first]]></category>
		<category><![CDATA[user first]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=6261</guid>

					<description><![CDATA[<p>You know when you work on various projects, and you use various tricks and techniques, and they all seem independent from one another, until the big picture jumps at you and you realize it&#8217;s all connected? I experienced this kind of aha moment, that emerged from several (apparently) independent topics I wrote about, a guest [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2022/06/25/usage-first-implementation-after-a-principle-of-software-development/">Usage First, Implementation After: A Principle of Software Development</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>You know when you work on various projects, and you use various tricks and techniques, and they all seem independent from one another, until the big picture jumps at you and you realize it&#8217;s all connected?</p>
<p>I experienced this kind of aha moment, that emerged from several (apparently) independent topics I wrote about, a guest post from Miguel Raggi, and my work on three different recent projects. And I wanted to share this moment with you.</p>
<p>The common point between those sources is this: if throughout your development process, you think about Usage First, Implementation After, you will maximize your chances for:</p>
<ul>
<li>happy users,</li>
<li>expressive code,</li>
<li>faster development time.</li>
</ul>
<p>The interesting thing is that &#8220;usage&#8221; and &#8220;implementation&#8221; have various meanings depending on the different stages in the development process. Let&#8217;s see 3 contexts where applying Usage First, Implementation After can bring the three above benefits.</p>
<h3><span style="color: #ff6600;">The usage of the user</span></h3>
<p>When thinking about usage, the first thing that comes to mind is how the user is using the application.</p>
<p>In this case, the principle of Usage First, Implementation After translates into the following guideline: decide about what&#8217;s best for the experience of the user, without thinking about how to implement the change in the application to achieve this user experience.</p>
<p>Granted, at the end of the day you will have to implement some features in the application to make this user experience tangible. But if you don&#8217;t think about the implementation during the reflexion about what would be great for the user, you are freeing your thinking from any limits. <strong>Pretend that anything is possible!</strong> This leaves room for more awesome ideas.</p>
<p>Only when you&#8217;ve decided what you want to do for the user, find a way to make it happen with the application. It&#8217;s only at this time that you should take into account the constraints of the existing system, the costs, etc. If necessary, you can always trade off 20% of user experience at this stage to make the development 80% cheaper.</p>
<h3><span style="color: #ff6600;">The usage of the developer</span></h3>
<p>Another usage that we think less about is the usage of the developer.</p>
<p>We don&#8217;t think about that first because the developer doesn&#8217;t use the app, and at first glance they don&#8217;t use the code either, they <em>produce</em> the code.</p>
<p>This view stands if the code is one atomic chunk that makes the application run, but it is not the case. The code is made of parts, many parts, and at many scales.</p>
<p>For example, the code of an application is often split into client and server, or front-end and back-end. And within any of those parts, there are modules, that can be composed of several sub-parts. And each piece of code in them is broken down into classes and functions, and so on.</p>
<p>All those are under the control of developers, and at each scale, there are usages: the client uses the services provided by the server, the front-end uses the API of the back-end, the modules uses one another, the internal code of the module uses the public interfaces of the classes, the functions use the prototypes of other functions.</p>
<p>All this is to illustrate that, from the perspective of any part of the code, there is a <em>usage</em> of another part of the code.</p>
<h4><span style="color: #ff6600;">Write the call site first</span></h4>
<p>The principle of Usage First, Implementation After applies very well in this context. In practice, it consists in <strong>writing the call site first</strong>.</p>
<p>Take the example of designing a function: imagine yourself in the middle of writing a piece of code, and you need an intermediary result in order to move on with the writing of your algorithm. You decide to write a function in charge of producing this intermediary result.</p>
<p>One  way to design that sub-function is to think about what it will need and what it will produce, and then write the function. And once the function is written, to call it from the piece of code you were writing initially.</p>
<p>But a better way to go is the other way around: pretend the sub-function already exists, and call it. This leaves you all the liberty to write the call site that suits you best, including a name for the function that fits seamlessly in that context.</p>
<p>This is a very powerful technique to write expressive code.</p>
<p>For more details and a step by step example of this approach of writing code, have a look at this excellent article from Miguel Raggi: <a href="https://www.fluentcpp.com/2018/09/11/how-to-write-simple-code-to-accomplish-complex-tasks/">How to Write Simple Code to Accomplish Complex Tasks</a>.</p>
<h3><span style="color: #ff6600;">The usage of the data</span></h3>
<p>Another situation I found the principle of User First, Implementation Later come in handy is when you have a system where you input data, and that produces data in another form. In this case the principle makes the development process faster.</p>
<h4><span style="color: #ff6600;">Renting boats</span></h4>
<p>Let&#8217;s take an example to illustrate. Imagine you own a boat rental on the beautiful Lac d&#8217;Annecy, where tourists are pressing in the summer season. You rent boats to people for them to take a tour on the Lac, and you want people to be able to book their boat in advance on your website.</p>
<p>The busy days are on the weekends and national holidays, although there is some activity during weekdays in the summer too. The inputs you feed your system are:</p>
<ul>
<li>the specific times your rental is open, for each type of day (weekend, weekday, summer season, etc.),</li>
<li>the available boats and their hourly prices.</li>
</ul>
<p>People can then book a specific boat for any amount of time, ranging from 30 minutes to a full day.</p>
<p>All that is the data coming in your system. In output, you need an up-to-date view of the available boats on the available slots for each day, so that potential customers can see what&#8217;s available in order to book their boat.</p>
<h4><span style="color: #ff6600;">Designing the system</span></h4>
<p>There are at least two ways to design this system:</p>
<ul>
<li>in order following the workflow,</li>
<li>or Usage First, Implementation later.</li>
</ul>
<p>The natural order that would come up to (my) mind is to follow the workflow. The starting point is the data provided by the boat rental owner: the opening times and boats descriptions. It sound only logical to start by thinking about how to take the data in input and how to store it, keeping in mind it will be queried later to display available boats and slots.</p>
<p>I have found that a much faster way is to start designing the end of the system first: <strong>the Usage of the data</strong>.</p>
<p>Doing that consists in designing the querying and processing of the data as if the data was already present in database in the most convenient format. The nice thing is that <em>this</em> defines what the most convenient format is.</p>
<p>From there, we go back to the beginning of the process, to design how to store the input data in this convenient format.</p>
<p>I used this approach on a project I worked on recently (even though it wasn&#8217;t about boats on the Lac d&#8217;Annecy) and I was impressed how it resulted in a better design, and a much faster development time.</p>
<h3><span style="color: #ff6600;">How you design software</span></h3>
<p>We&#8217;ve seen three aspects of software development where the Usage First, Implementation Later principle brought expressive code, fast development and happy users.</p>
<p>Do you also follow this principle or something resembling it? Please let me know how in a comment below, I&#8217;d love to read about your experience.</p>
<p>What others principles do you use when designing software?</p>
<h3>You will also like</h3>
<ul>
<li><a href="https://www.fluentcpp.com/2016/12/15/respect-levels-of-abstraction/">It all comes down to respecting levels of abstraction</a></li>
<li><a href="https://www.fluentcpp.com/2018/11/23/function-parameters-making-interfaces-easy-to-use/">How to Design Function Parameters That Make Interfaces Easier to Use</a></li>
<li><a href="https://www.fluentcpp.com/2020/06/19/great-developers-dont-just-write-great-code/">Great Developers Don&#8217;t Just Write Great Code</a></li>
<li><a href="https://www.fluentcpp.com/2020/05/15/runtime-polymorphism-without-virtual-functions/">Runtime Polymorphism Without Objects or Virtual Functions</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F06%2F25%2Fusage-first-implementation-after-a-principle-of-software-development%2F&#038;t=Usage%20First%2C%20Implementation%20After%3A%20A%20Principle%20of%20Software%20Development&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F06%2F25%2Fusage-first-implementation-after-a-principle-of-software-development%2F&#038;p&#091;images&#093;&#091;0&#093;=&#038;p&#091;title&#093;=Usage%20First%2C%20Implementation%20After%3A%20A%20Principle%20of%20Software%20Development" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F06%2F25%2Fusage-first-implementation-after-a-principle-of-software-development%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F06%2F25%2Fusage-first-implementation-after-a-principle-of-software-development%2F&#038;title=Usage%20First%2C%20Implementation%20After%3A%20A%20Principle%20of%20Software%20Development" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2022/06/25/usage-first-implementation-after-a-principle-of-software-development/">Usage First, Implementation After: A Principle of Software Development</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6261</post-id>	</item>
		<item>
		<title>Design Patterns VS Design Principles: Factory method</title>
		<link>https://www.fluentcpp.com/2022/06/05/design-patterns-vs-design-principles-factory-method/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Sun, 05 Jun 2022 01:00:49 +0000</pubDate>
				<category><![CDATA[Expressive code]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[factory]]></category>
		<category><![CDATA[factory method]]></category>
		<category><![CDATA[GoF]]></category>
		<category><![CDATA[grasp]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=5982</guid>

					<description><![CDATA[<p>Let&#8217;s examine another design pattern in our &#8220;Design Patterns VS Design Principles&#8221; series, where we relate design patterns to design principles. Today, we focus on the Factory method design pattern. We&#8217;ll see the various forms the Factory method design pattern can take, the differences with the Abstract Factory method, and to which design principle the [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2022/06/05/design-patterns-vs-design-principles-factory-method/">Design Patterns VS Design Principles: Factory method</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Let&#8217;s examine another design pattern in our &#8220;Design Patterns VS Design Principles&#8221; series, where we relate design patterns to design principles. Today, we focus on the <strong>Factory method</strong> design pattern.</p>
<p>We&#8217;ll see the various forms the Factory method design pattern can take, the differences with the Abstract Factory method, and to which design principle the Factory method pattern relates to.</p>
<h3><span style="color: #ff6600;">Design patterns and design principles</span></h3>
<p>In case you&#8217;re just joining the series, let&#8217;s see what we call a design pattern and a design principle.</p>
<p>A design pattern is one of the patterns presented in the classic Gang of Four (GoF) book <a href="https://www.amazon.com/gp/product/0201633612/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0201633612&amp;linkId=8d82c9d9fb2521a0d54f2f07c0bc12e0">Design Patterns</a>:</p>
<p><a href="https://www.amazon.com/gp/product/0201633612/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0201633612&amp;linkId=8d82c9d9fb2521a0d54f2f07c0bc12e0"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-5042" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=400%2C503&#038;ssl=1" alt="design patterns book GoF" width="400" height="503" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?w=400&amp;ssl=1 400w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=119%2C150&amp;ssl=1 119w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=239%2C300&amp;ssl=1 239w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=25%2C32&amp;ssl=1 25w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=80%2C100&amp;ssl=1 80w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=160%2C201&amp;ssl=1 160w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=318%2C400&amp;ssl=1 318w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=350%2C440&amp;ssl=1 350w" sizes="(max-width: 400px) 100vw, 400px" data-recalc-dims="1" /></a></p>
<p>Design principles, on the other hand are more general guidelines to make design robust. The GRASP principles are 9 principles to assign responsibilities to components in code, and they are presented in Craig Larman&#8217;s <a href="https://www.amazon.com/gp/product/0131489062/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0131489062&amp;linkId=c8f9976423d1df2c59c9acd303a2ff14">Applying UML and Patterns</a> book:</p>
<p><a href="https://www.amazon.com/gp/product/0131489062/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0131489062&amp;linkId=c8f9976423d1df2c59c9acd303a2ff14"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4971" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=400%2C500&#038;ssl=1" alt="Applying UML and Patterns" width="400" height="500" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?w=400&amp;ssl=1 400w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=120%2C150&amp;ssl=1 120w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=240%2C300&amp;ssl=1 240w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=26%2C32&amp;ssl=1 26w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=80%2C100&amp;ssl=1 80w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=161%2C201&amp;ssl=1 161w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=320%2C400&amp;ssl=1 320w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=352%2C440&amp;ssl=1 352w" sizes="(max-width: 400px) 100vw, 400px" data-recalc-dims="1" /></a></p>
<p>The <a href="https://www.fluentcpp.com/2021/06/23/grasp-9-must-know-design-principles-for-code/">9 GRASP design principles</a> are:</p>
<ul>
<li>Low Coupling</li>
<li>High cohesion</li>
<li>Creator</li>
<li>Information expert</li>
<li>Polymorphism</li>
<li>Indirection</li>
<li>Protected Variations</li>
<li>Pure Fabrication</li>
<li>Controller</li>
</ul>
<p>Let&#8217;s analyse the GoF design pattern<strong> Factory method</strong>, and find out to which GRASP principle it relates most.</p>
<h3><span style="color: #ff6600;">Factory method</span></h3>
<p>To understand what factory method means, let&#8217;s analyse each of its two words:</p>
<ul>
<li>method: this means member function,</li>
<li>factory: this means something that creates objects.</li>
</ul>
<p>All this means that a factory method is a member function that creates objects.</p>
<p>It is important to note that this comes from a book on object oriented design (the GoF&#8217;s <a href="https://www.amazon.com/gp/product/0201633612/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0201633612&amp;linkId=8d82c9d9fb2521a0d54f2f07c0bc12e0'">Design Patterns</a> book) , that makes heavy use of member functions. But my understanding of the design pattern is that it applies beyond member functions. It applies to free functions too.</p>
<p>So a more generic and idiomatic name for this design pattern in C++ could be &#8220;Factory function&#8221;.</p>
<h4><span style="color: #ff6600;">Factory member functions</span></h4>
<p>The GoF book illustrates the Factory method pattern with a polymorphic member function that returns a polymorphic object. The example is (in essence and in more modern) something like this:</p>
<pre class="lang:c++ decode:true ">class X { /* ... */ };

class SomeTypeOfX : public X { /* ... */ };

class MyClass
{
public:
    // interface of MyClass...
    virtual std::unique_ptr&lt;X&gt; createX() const;
};

class MyDerivedClass : public MyClass
{
public:
    std::unique_ptr&lt;X&gt; createX() const override
    {
        return std::make_unique&lt;SomeTypeOfX&gt;();
    }
};
</pre>
<p>The Factory method here is <code>createX</code>. Its only role is to create an <code>X</code> (or an object behaving like an <code>X</code>) and it is the only place in the code that creates an <code>X</code>.</p>
<p>This example uses polymorphism in two places: the factory method is polymorphic, and the created object is polymorphic too. But I don&#8217;t think those are essential conditions for the design pattern. A non-polymorphic method could just as well be in charge of creating a non-polymorphic object too.</p>
<p>For this reason, I don&#8217;t think that Factory method, in its essence, relates to the Polymorphism design principle. Rather, I would relate it to <strong>Pure Fabrication</strong>. Indeed, it is convenient for cohesion to centralise the responsibility of creating an object in one member function, even if this function doesn&#8217;t represent an element of the domain of the application.</p>
<h4><span style="color: #ff6600;">Factory free functions</span></h4>
<p>To illustrate how Factory method can also be implemented with a free function, let&#8217;s see the common pattern of the factory function. Before learning design patterns, this is what I thought the generic name &#8220;factory&#8221; referred too.</p>
<p>Consider the case where we have a class hierarchy:</p>
<pre class="lang:c++ decode:true">class Base { /* ... */ };

class Derived1 : public Base { /* ... */ };

class Derived2 : public Base { /* ... */ };

class Derived3 : public Base { /* ... */ };</pre>
<p>And we only know at runtime the type of the object we need to create. This information is represented by an enum:</p>
<pre class="lang:c++ decode:true">enum class Type
{
    Type1,
    Type2,
    Type3
};</pre>
<p>(those are names to illustrate the concepts, in production code we wouldn&#8217;t use such names with no information!)</p>
<p>To create an object of the appropriate type, and let the rest of the code use it polymorphically through the <code>Base</code> interface, we can centralise the creation in one function:</p>
<pre class="lang:c++ decode:true ">std::unique_ptr&lt;Base&gt; createObject(Type type)
{
    switch (type)
    {
        case Type::Type1 :
            return std::make_unique&lt;Derived1&gt;();
        case Type::Type2 :
            return std::make_unique&lt;Derived2&gt;();
        case Type::Type3 :
        default:
            return std::make_unique&lt;Derived3&gt;();
    }
};</pre>
<p>This falls under the Factory method design pattern too. And I would also relate this form to the <strong>Pure Fabrication</strong> principle, as it is a convenient way to centralise the responsibility of creating the object even if it doesn&#8217;t mirror a domain concept.</p>
<h4><span style="color: #ff6600;">Why not Creator?</span></h4>
<p>It would have sounded nice to relate the Factory method design pattern to the Creator design principle. Indeed, the sole role of the Factory method pattern is to create object (we saw that it didn&#8217;t relate to the Polymorphism principle).</p>
<p>However, the Creator principle is something else: it suggests that B should create A if B is going to interact with A, has input to create A, or is, more generally, close to A.</p>
<p>The Factory method is not close to the object it creates, in my view. Once it created it, the factory doesn&#8217;t necessarily continue to interact with the object.</p>
<h3><span style="color: #ff6600;">The differences between Abstract Factory and Factory method</span></h3>
<p>Abstract Factory and Factory method are two design patterns with the name &#8220;factory&#8221; in it, and they both describe patterns to create objects. The classical question is then: what is the difference between them?</p>
<p>I won&#8217;t describe how Abstract Factory works because it is a topic in itself and it is out of the scope of this article (it you&#8217;re not sure about how Abstract Factory works, check out the <a href="https://www.fluentcpp.com/2022/04/06/design-patterns-vs-design-principles-abstract-factory/">article dedicated to Abstract Factory</a>).</p>
<p>Here are the differences I see between the two patterns:</p>
<ul>
<li>Abstract Factory creates several objects of the same family or brand, whereas Factory method only creates one.</li>
<li>The essence of Abstract Factory is to provide Polymorphism in the creation of objects, whereas Factory method is only a Pure Fabrication to centralise the creation of an object.</li>
</ul>
<p>Do you see other differences between the two patterns?</p>
<p>Do you agree with the attribution of Factory method to Pure Fabrication?</p>
<p>Do you often use design patterns and design principles in your code?</p>
<p>Leave a comment below.</p>
<h3>You will also like</h3>
<ul>
<li><a href="https://www.fluentcpp.com/2022/04/06/design-patterns-vs-design-principles-abstract-factory/">Design Patterns VS Design Principles: Abstract Factory</a></li>
<li><a href="https://www.fluentcpp.com/2021/07/01/minor-major-and-overarching-design-principles/">Minor, Major and Overarching Design Principles</a></li>
<li><a href="https://www.fluentcpp.com/2021/06/23/grasp-9-must-know-design-principles-for-code/">GRASP: 9 Must-Know Design Principles for Code</a></li>
<li><a href="https://www.fluentcpp.com/2021/09/12/design-patterns-vs-design-principles-iterator-mediator-and-memento/">Design Patterns VS Design Principles: Iterator, Mediator and Memento</a></li>
<li><a href="https://www.fluentcpp.com/2021/11/17/design-patterns-vs-design-principles-template-method/">Design Patterns VS Design Principles: Template Method</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F06%2F05%2Fdesign-patterns-vs-design-principles-factory-method%2F&#038;t=Design%20Patterns%20VS%20Design%20Principles%3A%20Factory%20method&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F06%2F05%2Fdesign-patterns-vs-design-principles-factory-method%2F&#038;p&#091;images&#093;&#091;0&#093;=https%3A%2F%2Fwww.fluentcpp.com%2Fwp-content%2Fuploads%2F2019%2F05%2Fdesign_patterns_book.jpg&#038;p&#091;title&#093;=Design%20Patterns%20VS%20Design%20Principles%3A%20Factory%20method" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F06%2F05%2Fdesign-patterns-vs-design-principles-factory-method%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F06%2F05%2Fdesign-patterns-vs-design-principles-factory-method%2F&#038;title=Design%20Patterns%20VS%20Design%20Principles%3A%20Factory%20method" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2022/06/05/design-patterns-vs-design-principles-factory-method/">Design Patterns VS Design Principles: Factory method</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5982</post-id>	</item>
		<item>
		<title>How to Store an lvalue or an rvalue in the Same Object</title>
		<link>https://www.fluentcpp.com/2022/05/16/how-to-store-an-lvalue-or-an-rvalue-in-the-same-object/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Mon, 16 May 2022 01:00:43 +0000</pubDate>
				<category><![CDATA[Expressive code]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[C++17]]></category>
		<category><![CDATA[lvalue]]></category>
		<category><![CDATA[rvalue]]></category>
		<category><![CDATA[variant]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=6206</guid>

					<description><![CDATA[<p>There seems to be a problem coming up every so often C++ code: how can an object keep track of a value, given that this value can come from either an lvalue or an rvalue? In short, if we keep the value as a reference then we can&#8217;t bind to temporary objects. And if we [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2022/05/16/how-to-store-an-lvalue-or-an-rvalue-in-the-same-object/">How to Store an lvalue or an rvalue in the Same Object</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>There seems to be a problem coming up every so often C++ code: how can an object keep track of a value, given that this value can come from either an lvalue or an rvalue?</p>
<p>In short, if we keep the value as a reference then we can&#8217;t bind to temporary objects. And if we keep it as a value, we incur unnecessary copies when it is initialized from an lvalue.</p>
<p>What&#8217;s a C++ programmer to do?</p>
<p>There are several ways to cope with this situation. I find that using <code>std::variant</code> offers a good trade-off to have expressive code.</p>
<h3><span style="color: #ff6600;">Keeping track of a value</span></h3>
<p>Here is a more detailed explanation of the problem.</p>
<p>Consider a class <code>MyClass</code>. We would like to give <code>MyClass</code> access to a certain <code>std::string</code>. How do we represent the string inside of <code>MyClass</code>?</p>
<p>We have two options:</p>
<ul>
<li>storing it as a reference,</li>
<li>storing it as a value.</li>
</ul>
<h4><span style="color: #ff6600;">Storing a reference</span></h4>
<p>If we store it as a reference, for example a const reference:</p>
<pre class="lang:c++ mark:10 decode:true">class MyClass
{
public:
    explicit MyClass(std::string const&amp; s) : s_(s) {}
    void print() const
    {
        std::cout &lt;&lt; s_ &lt;&lt; '\n';
    }
private:
    std::string const&amp; s_;
};</pre>
<p>Then we can initialize our reference with an lvalue:</p>
<pre class="lang:c++ decode:true">std::string s = "hello";
MyClass myObject{s};
myObject.print();</pre>
<p>This code prints out:</p>
<pre class="theme:dark-terminal lang:default decode:true ">hello</pre>
<p>All good. But what if we want to initialize our object with an rvalue? For example with this code:</p>
<pre class="lang:c++ decode:true">MyClass myObject{std::string{"hello"}};
myObject.print();</pre>
<p>Or with this code:</p>
<pre class="lang:c++ decode:true">std::string getString(); // function declaration returning by value

MyClass myObject{getString()};
myObject.print();</pre>
<p>Then the code has <strong>undefined behaviour</strong>. Indeed, the temporary string object is destroyed on the same statement it is created. When we call <code>print</code>, the string has already been destroyed and using it is illegal and leads to undefined behaviour.</p>
<h5><span style="color: #ff6600;">Really?</span></h5>
<p>To illustrate this, if we replace <code>std::string</code> with a type <code>X</code> where we log in the destructor:</p>
<pre class="lang:c++ decode:true">struct X
{
    ~X() { std::cout &lt;&lt; "X destroyed" &lt;&lt; '\n';}
};

class MyClass
{
public:
    explicit MyClass(X const&amp; x) : x_(x) {}
    void print() const
    {
        // using x_;
    }
private:
    X const&amp; x_;
};</pre>
<p>Let&#8217;s also add logging to the call site:</p>
<pre class="lang:c++ decode:true">MyClass myObject(X{});
std::cout &lt;&lt; "before print" &lt;&lt; '\n';
myObject.print();</pre>
<p>This program then prints (<a href="https://godbolt.org/z/ejaMze">live code here</a>):</p>
<pre class="theme:dark-terminal lang:default decode:true">X destroyed
before print</pre>
<p>We can see that the object is destroyed before we attempt to use it.</p>
<h4><span style="color: #ff6600;">Storing a value</span></h4>
<p>The other option we have is to store a value. This allows us to use move semantics to move the incoming temporary into the stored value:</p>
<pre class="lang:c++ mark:4,10 decode:true ">class MyClass
{
public:
    explicit MyClass(std::string s) : s_(std::move(s)) {}
    void print() const
    {
        std::cout &lt;&lt; s_ &lt;&lt; '\n';
    }
private:
    std::string s_;
};</pre>
<p>Now with this call site:</p>
<pre class="lang:c++ decode:true ">MyClass myObject{std::string{"hello"}};
myObject.print();</pre>
<p>We incur two moves (one to construct <code>s</code> and one to construct <code>s_</code>) and we don&#8217;t have undefined behaviour. Indeed, even if the temporary is destroyed, <code>print</code> uses the instance inside of the class.</p>
<p>Unfortunately, if we go back to our first call site, with an lvalue:</p>
<pre class="lang:c++ decode:true ">std::string s = "hello";
MyClass myObject{s};
myObject.print();</pre>
<p>Then we&#8217;re no longer making two moves: we&#8217;re making one copy (to construct <code>s</code>) and one move (to construct <code>s_</code>).</p>
<p>What&#8217;s more, our purpose was to give <code>MyClass</code> access to the string, and if we make a copy we have a different instance than the one that came in. So they won&#8217;t be in sync.</p>
<p>With the temporary object it wasn&#8217;t a problem because it was to be destroyed anyway and we moved it in just before, so we still had access to &#8220;that&#8221; string. But by making a copy we no longer give <code>MyClass</code> access to the incoming string.</p>
<p>So using a value is not a good solution either.</p>
<h3><span style="color: #ff6600;">Storing a variant</span></h3>
<p>Storing a reference is not a good solution, and storing a value is not a good solution either. What we would like to do is to store a reference if the value is initialised from an lvalue, and store a value if it is stored from an rvalue.</p>
<p>But a data member can only be of one type: value or reference, right?</p>
<p>Well, with a <code>std::variant</code>, it can be either one.</p>
<p>However, if we try to store a reference in a variant, like this:</p>
<pre class="lang:c++ decode:true ">std::variant&lt;std::string, std::string const&amp;&gt;</pre>
<p>We get an compilation error expressed with a broken static assert:</p>
<pre class="theme:dark-terminal lang:default decode:true ">variant must have no reference alternative</pre>
<p>To achieve our purpose we need to put our reference inside of another type.</p>
<p>This means that we have to write specific code to handle our data member. If we write such code for <code>std::string</code> we won&#8217;t be able to use it for another type.</p>
<p>At this point it would be good to write the code in a generic way.</p>
<h3><span style="color: #ff6600;">A generic storage class</span></h3>
<p>The storage of our motivating case needed to be either a value or a reference. Since we&#8217;re writing this code for a general purpose now, we may as well allow non-const references too.</p>
<p>Since the variant cannot hold references directly, let&#8217;s store them into wrappers:</p>
<pre class="lang:c++ decode:true ">template&lt;typename T&gt;
struct NonConstReference
{
    T&amp; value_;
    explicit NonConstReference(T&amp; value) : value_(value){};
};

template&lt;typename T&gt;
struct ConstReference
{
    T const&amp; value_;
    explicit ConstReference(T const&amp; value) : value_(value){};
};

template&lt;typename T&gt;
struct Value
{
    T value_;
    explicit Value(T&amp;&amp; value) : value_(std::move(value)) {}
};</pre>
<p>And let&#8217;s define our storage to be either one of those cases:</p>
<pre class="lang:c++ decode:true ">template&lt;typename T&gt;
using Storage = std::variant&lt;Value&lt;T&gt;, ConstReference&lt;T&gt;, NonConstReference&lt;T&gt;&gt;;</pre>
<p>Now we need to give access to the underlying value of our variant, by providing a reference. We create two types of access: one const and one not const.</p>
<h4><span style="color: #ff6600;">Defining const access</span></h4>
<p>To define const access, we need to make each of the three possible type inside of the variant produce a const reference.</p>
<p>To access data inside the variant, we&#8217;ll use <code>std::visit</code> and the canonical <code>overload</code> pattern, which can be implemented in C++17 the following way:</p>
<pre class="lang:c++ decode:true ">template&lt;typename... Functions&gt;
struct overload : Functions...
{
    using Functions::operator()...;
    overload(Functions... functions) : Functions(functions)... {}
};</pre>
<p>To get our const reference, we can just create one for each case of the variant:</p>
<pre class="lang:c++ decode:true">template&lt;typename T&gt;
T const&amp; getConstReference(Storage&lt;T&gt; const&amp; storage)
{
    return std::visit(
        overload(
            [](Value&lt;T&gt; const&amp; value) -&gt; T const&amp;             { return value.value_; },
            [](NonConstReference&lt;T&gt; const&amp; value) -&gt; T const&amp; { return value.value_; },
            [](ConstReference&lt;T&gt; const&amp; value) -&gt; T const&amp;    { return value.value_; }
        ),
        storage
    );
}</pre>
<h4><span style="color: #ff6600;">Defining non-const access</span></h4>
<p>The creation of a non const reference uses the same technique, except that if is variant is a <code>ConstReference</code>, it can&#8217;t produce a non-const reference. However, when we <code>std::visit</code> a variant, we have to write code for each of its possible types:</p>
<pre class="lang:c++ decode:true">template&lt;typename T&gt;
T&amp; getReference(Storage&lt;T&gt;&amp; storage)
{
    return std::visit(
        overload(
            [](Value&lt;T&gt;&amp; value) -&gt; T&amp;             { return value.value_; },
            [](NonConstReference&lt;T&gt;&amp; value) -&gt; T&amp; { return value.value_; },
            [](ConstReference&lt;T&gt;&amp; ) -&gt; T&amp;.        { /* code handling the error! */ }
        ),
        storage
    );
}</pre>
<p>We should never end up in that situation, but we still have to write some code for it. The first idea that comes to (my) mind is to throw an exception:</p>
<pre class="lang:c++ mark:13 decode:true">struct NonConstReferenceFromReference : public std::runtime_error
{
    explicit NonConstReferenceFromReference(std::string const&amp; what) : std::runtime_error{what} {}
};

template&lt;typename T&gt;
T&amp; getReference(Storage&lt;T&gt;&amp; storage)
{
    return std::visit(
        overload(
            [](Value&lt;T&gt;&amp; value) -&gt; T&amp;             { return value.value_; },
            [](NonConstReference&lt;T&gt;&amp; value) -&gt; T&amp; { return value.value_; },
            [](ConstReference&lt;T&gt;&amp; ) -&gt; T&amp; { throw NonConstReferenceFromReference{"Cannot get a non const reference from a const reference"} ; }
        ),
        storage
    );
}</pre>
<p>If you have other suggestions, I&#8217;d love to hear them!</p>
<h3><span style="color: #ff6600;"><span style="caret-color: #ff6600;">Creating the storage</span></span></h3>
<p>Now that we have defined our storage class, let&#8217;s use it in our motivating case to give access to the incoming <code>std::string</code> regardless of its value category:</p>
<pre class="lang:c++ decode:true">class MyClass
{
public:
    explicit MyClass(std::string&amp; value) :       storage_(NonConstReference(value)){}
    explicit MyClass(std::string const&amp; value) : storage_(ConstReference(value)){}
    explicit MyClass(std::string&amp;&amp; value) :      storage_(Value(std::move(value))){}

    void print() const
    {
        std::cout &lt;&lt; getConstReference(storage_) &lt;&lt; '\n';
    }

private:
    Storage&lt;std::string&gt; storage_;
};</pre>
<p>Consider the first call site, with an lvalue:</p>
<pre class="lang:c++ decode:true">std::string s = "hello";
MyClass myObject{s};
myObject.print();</pre>
<p>It matches the first constructor, and creates a <code>NonConstReference</code> inside of the storage member. The non-const reference is converted into a const reference when the <code>print</code> function calls <code>getConstReference</code>.</p>
<p>Now consider the second call site, with the temporary value:</p>
<pre class="lang:c++ decode:true ">MyClass myObject{std::string{"hello"}};
myObject.print();</pre>
<p>This one matches the third constructor, and moves the value inside of the storage. <code>getConstReference</code> then returns a const reference to that value to the <code>print</code> function.</p>
<h3><span style="color: #ff6600;">The evolution of the standard library</span></h3>
<p><code>std::variant</code> offers a very adapted solution to the classical problem of keeping track of either an lvalue or an rvalue in C++.</p>
<p>The code of this technique is expressive because <code>std::variant</code> allows to express something that is very close to our intention: &#8220;depending on the context, the object could be either this or that&#8221;. In our case, &#8220;this&#8221; and &#8220;that&#8221; are a &#8220;reference&#8221; or a &#8220;value&#8221;.</p>
<p>Before C++17 and <code>std::variant</code>, solving that problem was tricky and led to code that was difficult to write correctly. With the language evolving, the standard library gets more powerful and lets us express our intentions with more and more expressive code.</p>
<p>We will see other ways in which the evolution of the standard library helps us write more expressive code in a future article. Stay tuned!</p>
<h3><span style="color: #000000;">You will also like</span></h3>
<ul>
<li><a href="https://www.fluentcpp.com/2018/09/11/how-to-write-simple-code-to-accomplish-complex-tasks/">How to Write Simple Code to Accomplish Complex Tasks</a></li>
<li><a href="https://www.fluentcpp.com/2019/11/19/how-c17-benefits-from-boost-libraries-part-one/">How C++17 Benefits from Boost Libraries</a></li>
<li><a href="https://www.fluentcpp.com/2018/12/11/overview-of-std-map-insertion-emplacement-methods-in-cpp17/">Overview of std::map’s Insertion / Emplacement Methods in C++17</a></li>
<li><a href="https://www.fluentcpp.com/2018/06/19/3-simple-c17-features-that-will-make-your-code-simpler/">3 Simple C++17 Features That Will Make Your Code Simpler</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F05%2F16%2Fhow-to-store-an-lvalue-or-an-rvalue-in-the-same-object%2F&#038;t=How%20to%20Store%20an%20lvalue%20or%20an%20rvalue%20in%20the%20Same%20Object&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F05%2F16%2Fhow-to-store-an-lvalue-or-an-rvalue-in-the-same-object%2F&#038;p&#091;images&#093;&#091;0&#093;=&#038;p&#091;title&#093;=How%20to%20Store%20an%20lvalue%20or%20an%20rvalue%20in%20the%20Same%20Object" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F05%2F16%2Fhow-to-store-an-lvalue-or-an-rvalue-in-the-same-object%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F05%2F16%2Fhow-to-store-an-lvalue-or-an-rvalue-in-the-same-object%2F&#038;title=How%20to%20Store%20an%20lvalue%20or%20an%20rvalue%20in%20the%20Same%20Object" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2022/05/16/how-to-store-an-lvalue-or-an-rvalue-in-the-same-object/">How to Store an lvalue or an rvalue in the Same Object</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6206</post-id>	</item>
		<item>
		<title>Copy-Paste Developments</title>
		<link>https://www.fluentcpp.com/2022/04/26/copy-paste-developments/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Tue, 26 Apr 2022 01:00:54 +0000</pubDate>
				<category><![CDATA[Expressive code]]></category>
		<category><![CDATA[copy]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[DRY]]></category>
		<category><![CDATA[duplication]]></category>
		<category><![CDATA[legacy]]></category>
		<category><![CDATA[past]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=5789</guid>

					<description><![CDATA[<p>Amongst the many tasks a programmer does, one of them is to add a new feature in a location of the application where there are already many similar exising features. The temptation is then to warm up very specific muscles of our left hand: the pinky muscles that will press on the Ctrl key, the [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2022/04/26/copy-paste-developments/">Copy-Paste Developments</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Amongst the many tasks a programmer does, one of them is to add a new feature in a location of the application where there are already many similar exising features.</p>
<p>The temptation is then to warm up very specific muscles of our left hand:</p>
<ul>
<li>the pinky muscles that will press on the <strong>Ctrl</strong> key,</li>
<li>the index finger muscles to press on the <strong>C</strong> key</li>
<li>whatever muscles on the right-hand side of our index figer that will move it over the <strong>V</strong> key.</li>
</ul>
<p>In other words, we prepare ourselves for a <strong>copy-paste development</strong>. That is, we find something in the application that is similar to what we want to add, copy-paste it, and change the small bits that are specific to our new feature.</p>
<p>Although the nervous and muscular biological sequence behind a copy-paste is beautiful, there is another beautiful nervous element we can use: our brain.</p>
<p>Indeed, even in copy-paste development, injecting a bit of understanding can reap a lot of benefits, both for our satisfaction and for the quality of our code.</p>
<h3><span style="color: #ff6600;">Copy-paste developments</span></h3>
<p>First let&#8217;s agree on what we call copy-paste developments. I&#8217;m assuming that you follow the DRY (Don&#8217;t Repeat Yourself) principle, that is trying to avoid code duplication, at least <a href="https://www.fluentcpp.com/2018/11/13/to-dry-or-not-to-dry/">when this is reasonable</a>.</p>
<p>So copy-pasting is not your default approach. But in some developments, where the feature you&#8217;re adding is similar to <em>many</em> existing features that are all copy-pasted from one another, it can be difficult not to copy-paste your new one into existence.</p>
<p>For example, you&#8217;re asked to add a new field in a dictionary of existing fields. Or a new value in a report. Or a new field in an XML that is produced by your application.</p>
<p>And you&#8217;re not very familiar with the framework of that dictionary, or with that reporting module, or that XML library.</p>
<p>Fortunately, there are many fields in the dictionary, many values in the report, or many fields in the XML, and they all kind of look alike, except for some specific bits to each field.</p>
<p>Have you ever been asked to do such a development?</p>
<p>The temptation can be to just copy-paste, ignore what you don&#8217;t really understand, modify the specific part for your new field, and call it a day.</p>
<p>But there is a better way.</p>
<h3><span style="color: #ff6600;">The need to understand</span></h3>
<p>We generally don&#8217;t see those developments as very interesting or rewarding. But there is one thing we can do to make them more interesting and turn them into learning opportunities: <strong>understanding the code we&#8217;re copy-pasting</strong>.</p>
<p>Of course, not having to copy-paste any code because the framework you&#8217;re working in is very well designed is the ideal situation. But if you&#8217;re working with existing code, sometimes you don&#8217;t choose the quality of the code, or at least the quality it has when you start working with it.</p>
<p>But the least we can do is to understand the code we&#8217;re copy-pasting.</p>
<p>Here are several benefits this can bring.</p>
<h4><span style="color: #ff6600;">Dead code</span></h4>
<p>One reason to understand what you&#8217;re copy-pasting is that perhaps part of it is not necessary for your specific feature.</p>
<p>This has happened to me in a recent development, and realising it saved me from introducing a substantial amount of code inspired from another feature. The most amusing part is that I realised that this other feature I took as a model didn&#8217;t need that part too!</p>
<p>Introducing useless code is sad. It makes the code less expressive because there is more to read and understand for the next person. And we don&#8217;t get anything for it, because it&#8217;s useless.</p>
<p>Understanding what you&#8217;re copy-pasting, even if it&#8217;s a vague understanding about what each part is used for, can make your code simpler and more expressive.</p>
<h4><span style="color: #ff6600;">You&#8217;ll need to understand it anyway</span></h4>
<p>In general, when you add a new feature in legacy code, does it work the first time after you&#8217;ve compiled it and run the application?</p>
<p>Sometimes it does. But sometimes, we need to adjust the code to make it work and cover all cases. If we don&#8217;t understand how the code works, we&#8217;re crippled to solve its issues and make our new feature work.</p>
<p>The worst situation is when we think it works, and a bug is discovered later. Then we need to get back to the unfamiliar copy-pasted code and figure it out. And if the bug is urgent to fix because it has been uncovered late in the process&#8230; this is not a situation we want to be in, is it?</p>
<p>Since we&#8217;re likely going to figure out the code at some point anyway, let&#8217;s do it at the beginning and write the code as correctly as possible as early in the process as possible.</p>
<h4><span style="color: #ff6600;">Extending your known scope</span></h4>
<p>Taking the time to understand a new framework or module expands your knowledge, and in software engineering, and in legacy code in particular, Knowledge is Power.</p>
<p>For a lot more details about this, you can check out chapter 7 of <a href="https://leanpub.com/legacycode/">The Legacy Code Programmer&#8217;s Toolbox</a>.</p>
<h4><span style="color: #ff6600;">Intellectual interest</span></h4>
<p>A lot of us became developers because they enjoy the intellectual challenge in it. But copy-pasting is a pretty dumb activity.</p>
<p>Personally, the part of programming that I enjoy most is understanding how existing systems work. Even understanding how copy-pasted code work brings me more satisfaction than copy-pasting mysterious code and hoping for it to work.</p>
<p>Is this the same for you? What part of your job do you enjoy the most? Let me know in the comments section!</p>
<p>I wouldn&#8217;t presume of what brings you intellectual satisfaction in your job as a programmer, but I&#8217;d love to know if understanding systems bring you joy too.</p>
<h4><span style="color: #ff6600;"><em>Not</em> copy-pasting</span></h4>
<p>If you understand the code you&#8217;re copy-pasting, you&#8217;ll more able to see a common pattern between the various features.</p>
<p>This can give you the tools to put some code in common and copy-paste less code to implement your feature, thus applying the DRY principle.</p>
<p>At some point you may even be knowledgable enough about the patterns used by the framework you&#8217;re inserting your code in to refactor the framework itself, in a separate development.</p>
<p>This is great exercise, both in detecting abstractions in code and in formulating new ones. This is fundamental, as programming <a href="https://www.fluentcpp.com/2016/12/15/respect-levels-of-abstraction/">all comes down to respecting levels of abstraction</a>.</p>
<h3><span style="color: #ff6600;">Don&#8217;t let your fingers muscles do all the work</span></h3>
<p>Do copy-paste developments sound familiar?</p>
<p>When you have to do one, do you invest the time and effort to understand the copy-pasted code?</p>
<p>If you don&#8217;t, next time you have to do a copy-paste development, why not use your full brain power to understand the code you&#8217;re copy-pasting, and see what the benefits this can bring you?</p>
<p>Share your experience in the comments below!</p>
<h3>You will also like</h3>
<ul>
<li><a href="https://www.fluentcpp.com/2019/07/09/you-should-refuse-to-develop-what-you-dont-understand/">You Should Refuse to Develop What You Don&#8217;t Understand</a></li>
<li><a href="https://www.fluentcpp.com/2018/11/13/to-dry-or-not-to-dry/">To DRY or not to DRY?</a></li>
<li><a href="https://www.fluentcpp.com/2020/01/03/dry-comparisons-a-c-library-to-shorten-redundant-if-statements/">Dry-comparisons: A C++ Library to Shorten Redundant If Statements</a></li>
<li><a href="https://leanpub.com/legacycode/">The Legacy Code Programmer&#8217;s Toolbox</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F04%2F26%2Fcopy-paste-developments%2F&#038;t=Copy-Paste%20Developments&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F04%2F26%2Fcopy-paste-developments%2F&#038;p&#091;images&#093;&#091;0&#093;=&#038;p&#091;title&#093;=Copy-Paste%20Developments" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F04%2F26%2Fcopy-paste-developments%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F04%2F26%2Fcopy-paste-developments%2F&#038;title=Copy-Paste%20Developments" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2022/04/26/copy-paste-developments/">Copy-Paste Developments</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5789</post-id>	</item>
		<item>
		<title>Design Patterns VS Design Principles: Abstract Factory</title>
		<link>https://www.fluentcpp.com/2022/04/06/design-patterns-vs-design-principles-abstract-factory/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Wed, 06 Apr 2022 01:00:50 +0000</pubDate>
				<category><![CDATA[Expressive code]]></category>
		<category><![CDATA[abstract factory]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[GoF]]></category>
		<category><![CDATA[grasp]]></category>
		<category><![CDATA[principles]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=5975</guid>

					<description><![CDATA[<p>In the &#8220;Design Pattens VS Design Principles&#8221; series, we look at design patterns and relate them to design principles. In this episode, we examine the Abstract Factory pattern. Let&#8217;s see how Abstract Factory works and what it is useful for, then relate it to a design principle. We will also see a C++ technique to [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2022/04/06/design-patterns-vs-design-principles-abstract-factory/">Design Patterns VS Design Principles: Abstract Factory</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In the &#8220;Design Pattens VS Design Principles&#8221; series, we look at design patterns and relate them to design principles. In this episode, we examine the <strong>Abstract Factory</strong> pattern.</p>
<p>Let&#8217;s see how Abstract Factory works and what it is useful for, then relate it to a design principle. We will also see a C++ technique to implement Abstract Factory with classes nested in a function.</p>
<h3><span style="color: #ff6600;">Design Patterns and Design Principles</span></h3>
<p>What is the difference between design patterns and design principles?</p>
<p>The design patterns we talk about are the collection of patterns described in the popular <a href="https://www.amazon.com/gp/product/0201633612/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0201633612&amp;linkId=8d82c9d9fb2521a0d54f2f07c0bc12e0">GoF book</a>:</p>
<p><a href="https://www.amazon.com/gp/product/0201633612/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0201633612&amp;linkId=8d82c9d9fb2521a0d54f2f07c0bc12e0"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-5042" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=400%2C503&#038;ssl=1" alt="design patterns book GoF" width="400" height="503" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?w=400&amp;ssl=1 400w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=119%2C150&amp;ssl=1 119w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=239%2C300&amp;ssl=1 239w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=25%2C32&amp;ssl=1 25w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=80%2C100&amp;ssl=1 80w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=160%2C201&amp;ssl=1 160w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=318%2C400&amp;ssl=1 318w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=350%2C440&amp;ssl=1 350w" sizes="(max-width: 400px) 100vw, 400px" data-recalc-dims="1" /></a></p>
<p>Design patterns are typical ways to organise the components of a program in typical situations.</p>
<p>Design principles, on the other hand, are general guidelines te help create robust designs. The 9 GRASP principles are described in Craig Larman&#8217;s <a href="https://www.amazon.com/gp/product/0131489062/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0131489062&amp;linkId=c8f9976423d1df2c59c9acd303a2ff14">Applying UML and Patterns</a> book:</p>
<p><a href="https://www.amazon.com/gp/product/0131489062/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0131489062&amp;linkId=c8f9976423d1df2c59c9acd303a2ff14"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4971" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=400%2C500&#038;ssl=1" alt="Applying UML and Patterns" width="400" height="500" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?w=400&amp;ssl=1 400w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=120%2C150&amp;ssl=1 120w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=240%2C300&amp;ssl=1 240w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=26%2C32&amp;ssl=1 26w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=80%2C100&amp;ssl=1 80w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=161%2C201&amp;ssl=1 161w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=320%2C400&amp;ssl=1 320w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=352%2C440&amp;ssl=1 352w" sizes="(max-width: 400px) 100vw, 400px" data-recalc-dims="1" /></a></p>
<p>The <a href="https://www.fluentcpp.com/2021/06/23/grasp-9-must-know-design-principles-for-code/">9 GRASP design principles</a> are:</p>
<ul>
<li>Low Coupling</li>
<li>High cohesion</li>
<li>Creator</li>
<li>Information expert</li>
<li>Polymorphism</li>
<li>Indirection</li>
<li>Protected Variations</li>
<li>Pure Fabrication</li>
<li>Controller</li>
</ul>
<p>Let&#8217;s analyse the GoF design pattern <strong>Abstract Factory</strong>, and decide to which GRASP principle it relates the most.</p>
<h3><span style="color: #ff6600;">What Abstract Factory is useful for</span></h3>
<p>The goal of the Abstract Factory pattern is to make sure that objects are created consistently with each other.</p>
<p>This need arises when several objects can be created in a context, and there are several ways to create those objects. The GoF books uses the term of &#8220;family&#8221;: there are several families of objects. You can also see it as if there were several <strong>brands</strong> of objects, and in a given context you want all objects to be created <strong>of the same brand</strong>.</p>
<p>To do that, the Abstract Factory pattern consists in assigning to one class the responsibility of creating all the objects of a given family or brand.</p>
<h4><span style="color: #ff6600;">Concrete factories</span></h4>
<p>Let&#8217;s illustrate with a simple example, with an Abstract Factory that builds the parts of a house. In practice, the objects we create in code are more abstract (I&#8217;ve used Abstract Factory to create objects related to transactions for example), but let&#8217;s use this simple example to illustrate the structure of the pattern.</p>
<p>The objects we want to create are a door, a roof and a wall. There are several types of houses: blue houses, red houses, and yellow houses. And there may be more of them.</p>
<p>When we build a blue house, we want to make sure that all its components are blue. If we were to instantiate each object separately, each time there would be a risk of not instantiating the right type.</p>
<p>To mitigate that risk, we instantiate only one object: the blue house factory. Then we only use this object to create the others. This means that if we get the right factory, we&#8217;re guaranteed to get all the components of the right color too.</p>
<pre class="lang:c++ decode:true">BlueHouseFactory
{
    Door createDoor() const; // this returns a blue door
    Roof createRoof() const; // this returns a blue roof
    Wall createWall() const; // this returns a blue wall
};</pre>
<p>Note that this is a simple factory that doesn&#8217;t use polymorphism on the objects it creates (<code>Door</code>, etc.). Indeed, there could also be polymorphism in the objects that the factory creates:</p>
<pre class="lang:c++ decode:true">class BlueHouseFactory
{
public:
    std::unique_ptr&lt;Door&gt; createDoor() const; // this returns a blue door
    std::unique_ptr&lt;Roof&gt; createRoof() const; // this returns a blue roof
    std::unique_ptr&lt;Wall&gt; createWall() const; // this returns a blue wall
};</pre>
<p>With subclasses for each object:</p>
<pre class="lang:c++ decode:true">class BlueDoor : public Door
{
    // ...
};</pre>
<p>And the code for <code>createDoor</code> would then look like this:</p>
<pre class="lang:c++ decode:true">std::unique_ptr&lt;Door&gt; BlueHouseFactory::createDoor()
{
    return std::make_unique&lt;BlueDoor&gt;();
}</pre>
<h4><span style="color: #ff6600;">Abstract Factory</span></h4>
<p>Now we have one factory, that creates blue components. We go on and introduce other factories, that create other types of components: the <code>RedHouseFactory</code> and the <code>YellowHouseFactory</code>.</p>
<p>The goal is to use only one factory in a given context. To do that, we introduce an abstract factory, that can be either one of the above factories:</p>
<pre class="lang:c++ decode:true">class HouseFactory
{
public:
    virtual std::unique_ptr&lt;Door&gt; createDoor() const = 0;
    virtual std::unique_ptr&lt;Roof&gt; createRoof() const = 0;
    virtual std::unique_ptr&lt;Wall&gt; createWall() const = 0;
    virtual ~HouseFactory() = 0;
};</pre>
<p>The concrete factories then implement this interface:</p>
<pre class="lang:c++ decode:true ">class BlueHouseFactory : public HouseFactory
{
public:
    std::unique_ptr&lt;Door&gt; createDoor() const override; // this returns a blue door
    std::unique_ptr&lt;Roof&gt; createRoof() const override; // this returns a blue roof
    std::unique_ptr&lt;Wall&gt; createWall() const override; // this returns a blue wall
};

class RedHouseFactory : public HouseFactory
{
public:
    std::unique_ptr&lt;Door&gt; createDoor() const override; // this returns a red door
    std::unique_ptr&lt;Roof&gt; createRoof() const override; // this returns a red roof
    std::unique_ptr&lt;Wall&gt; createWall() const override; // this returns a red wall
};

class YellowHouseFactory : public HouseFactory
{
public:
    std::unique_ptr&lt;Door&gt; createDoor() const override; // this returns a yellow door
    std::unique_ptr&lt;Roof&gt; createRoof() const override; // this returns a yellow roof
    std::unique_ptr&lt;Wall&gt; createWall() const override; // this returns a yellow wall
};</pre>
<h3><span style="color: #ff6600;">Creating the factory</span></h3>
<p>The factory is made to create objects, but who creates the factory?</p>
<p>There are various ways to do that. One of them is to instantiate various concrete factories in various places of the code, depending on the context. Given a function that uses a factory:</p>
<pre class="lang:c++ decode:true ">House buildAHouse(HouseFactory const&amp; houseFactory);</pre>
<p>We could call this fonction with a concrete factory if we know which one to use:</p>
<pre class="lang:c++ decode:true">auto const blueHouse = buildAHouse(BlueHouseFactory{});</pre>
<p>Another option is to centralise the creation of the factory, in a function (that happens to follow another design pattern, Factory Method, which we&#8217;ll explore in another post):</p>
<pre class="lang:c++ decode:true">std::unique_ptr&lt;HouseFactory&gt; createHouseFactory(Color color)
{
    switch (color)
    {
        case Color::Blue:
        {
            return std::unique_ptr&lt;BlueHouseFactory&gt;{};
            break;
        }
        case Color::Red:
        {
            return std::unique_ptr&lt;RedHouseFactory&gt;{};
            break;
        }
        case Color::Yellow:
        default:
        {
            return std::unique_ptr&lt;YellowHouseFactory&gt;{};
            break;
        }
    }
}</pre>
<p>This has the drawback of having to deal with the <code>default</code> case (Should we have a default color as in the above code? Should we produce an error? Or return a nullptr that we test everywhere?).</p>
<p>If you centralise the creation of the factory, know that C++ gives you the option to centralise the definitions of the factories along with them, by using classes nested in a function:</p>
<pre class="lang:c++ decode:true ">std::unique_ptr&lt;HouseFactory&gt; createHouseFactory(Color color)
{
    switch (color)
    {
        case Color::Blue:
        {
            class BlueHouseFactory : public HouseFactory
            {
            public:
                std::unique_ptr&lt;Door&gt; createDoor() const override { return std::make_unique&lt;BlueDoor&gt;(); };
                std::unique_ptr&lt;Roof&gt; createRoof() const override { return std::make_unique&lt;BlueRoof&gt;(); };
                std::unique_ptr&lt;Wall&gt; createWall() const override { return std::make_unique&lt;BlueWall&gt;(); };
            };

            return std::unique_ptr&lt;BlueHouseFactory&gt;{};
            break;
        }

        case Color::Red:
        {
            class RedHouseFactory : public HouseFactory
            {
            public:
                std::unique_ptr&lt;Door&gt; createDoor() const override { return std::make_unique&lt;RedDoor&gt;(); };
                std::unique_ptr&lt;Roof&gt; createRoof() const override { return std::make_unique&lt;RedRoof&gt;(); };
                std::unique_ptr&lt;Wall&gt; createWall() const override { return std::make_unique&lt;RedWall&gt;(); };
            };

            return std::unique_ptr&lt;RedHouseFactory&gt;{};
            break;
        }

        case Color::Yellow:
        default:
        {
            class YellowHouseFactory : public HouseFactory
            {
            public:
                std::unique_ptr&lt;Door&gt; createDoor() const override { return std::make_unique&lt;YellowDoor&gt;(); };
                std::unique_ptr&lt;Roof&gt; createRoof() const override { return std::make_unique&lt;YellowRoof&gt;(); };
                std::unique_ptr&lt;Wall&gt; createWall() const override { return std::make_unique&lt;YellowWall&gt;(); };
            };

            return std::unique_ptr&lt;YellowHouseFactory&gt;{};
            break;
        }
    }
}</pre>
<p>An advantage of this is that all the factory code is located together, and you&#8217;re guaranteed that no other code can instantiate a <code>BlueHouseFactory</code>, because they don&#8217;t have access to that class.</p>
<p>But as a drawback, it makes the factory creation fonction bigger. If the implementations of the factories are not very simple, this makes the code hard to follow.</p>
<h3><span style="color: #ff6600;"><span style="caret-color: #ff6600;">Design principles</span></span></h3>
<p>The role of Abstract Factory is to present an interface for creating objects, that is implemented by various concrete factories. For this reason, I think Abstract Factory implements the <strong>Polymorphism</strong> GRASP design principle.</p>
<p>Also, the factory often doesn&#8217;t model a domain object. It is a technical helper to centralise the creation of consistent objects. This also makes it a <strong>Pure Fabrication</strong>.</p>
<p>Doesn&#8217;t Abstract Factory also implement the Creator GRASP design principle? Given its name, this is what I would have thought before digging in the analysis.</p>
<p>But if we go back to the definition of Creator, it suggests that B should create A if B is close to A: if it uses A, if it has inputs to create A, if it already contains other instances of A, etc. This does not match the description of Abstract Factory as well as Polymorphism does.</p>
<p>Would you also have reacted Abstract Factory to Polymorphism and Pure Fabrication, or to another one?</p>
<p>Do you know of creational patterns that are not in the GoF book?</p>
<p>Let me know by leaving a comment below.</p>
<h3><span style="color: #000000;">You will also like</span></h3>
<ul>
<li><a href="https://www.fluentcpp.com/2021/07/01/minor-major-and-overarching-design-principles/">Minor, Major and Overarching Design Principles</a></li>
<li><a href="https://www.fluentcpp.com/2021/06/23/grasp-9-must-know-design-principles-for-code/">GRASP: 9 Must-Know Design Principles for Code</a></li>
<li><a href="https://www.fluentcpp.com/2021/07/26/design-patterns-vs-design-principles-chain-of-responsibility-command-and-interpreter/">esign Patterns VS Design Principles: Chain of responsibility, Command and Interpreter</a></li>
<li><a href="https://www.fluentcpp.com/2021/09/12/design-patterns-vs-design-principles-iterator-mediator-and-memento/">Design Patterns VS Design Principles: Iterator, Mediator and Memento</a></li>
<li><a href="https://www.fluentcpp.com/2021/10/19/design-patterns-vs-design-principles-observer-state-and-strategy/">Design Patterns VS Design Principles: Observer, State and Strategy</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F04%2F06%2Fdesign-patterns-vs-design-principles-abstract-factory%2F&#038;t=Design%20Patterns%20VS%20Design%20Principles%3A%20Abstract%20Factory&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F04%2F06%2Fdesign-patterns-vs-design-principles-abstract-factory%2F&#038;p&#091;images&#093;&#091;0&#093;=https%3A%2F%2Fwww.fluentcpp.com%2Fwp-content%2Fuploads%2F2019%2F05%2Fdesign_patterns_book.jpg&#038;p&#091;title&#093;=Design%20Patterns%20VS%20Design%20Principles%3A%20Abstract%20Factory" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F04%2F06%2Fdesign-patterns-vs-design-principles-abstract-factory%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F04%2F06%2Fdesign-patterns-vs-design-principles-abstract-factory%2F&#038;title=Design%20Patterns%20VS%20Design%20Principles%3A%20Abstract%20Factory" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2022/04/06/design-patterns-vs-design-principles-abstract-factory/">Design Patterns VS Design Principles: Abstract Factory</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5975</post-id>	</item>
		<item>
		<title>How to Generate All the Combinations from Several Collections</title>
		<link>https://www.fluentcpp.com/2022/03/18/how-to-generate-all-the-combinations-from-several-collections/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Fri, 18 Mar 2022 01:00:58 +0000</pubDate>
				<category><![CDATA[Expressive code]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cartesian product]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[combinations]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=5625</guid>

					<description><![CDATA[<p>Generating all the possible combinations from a set of collections and applying a function to each combination is a need that comes up often in programming. This is called a &#8220;Cartesian product&#8221;. For example, this kind of operation is necessary in the cartesian_product range adaptor, in the cartesian_product pipe, and in the killer feature of [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2022/03/18/how-to-generate-all-the-combinations-from-several-collections/">How to Generate All the Combinations from Several Collections</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Generating all the possible combinations from a set of collections and applying a function to each combination is a need that comes up often in programming.</p>
<p>This is called a &#8220;Cartesian product&#8221;.</p>
<p>For example, this kind of operation is necessary in the <a href="https://www.fluentcpp.com/2017/04/14/understand-ranges-better-with-the-new-cartesian-product-adaptor/"><code>cartesian_product</code> range adaptor</a>, in the <a href="https://github.com/joboccara/pipes#operating-on-all-the-possible-combinations-between-several-collections"><code>cartesian_product</code> pipe</a>, and in the killer feature of <a href="https://github.com/approvals/ApprovalTests.cpp/blob/master/doc/TestingCombinations.md#top"><code>verifyAllCombinations</code></a> in the ApprovalTest.cpp library, to cite just a few.</p>
<p>The most basic usage of a Cartesian product looks like this:</p>
<pre class="lang:c++ decode:true">auto const inputs1 = std::vector&lt;int&gt; {1, 2, 3};
auto const inputs2 = std::vector&lt;std::string&gt;{"up", "down"};
auto const inputs3 = std::vector&lt;std::string&gt;{"blue", "red"};

cartesian_product(displayCombination,
                  inputs1,
                  inputs2,
                  inputs3);</pre>
<p>Where <code>displayCombination</code> is a function that takes one element from each collection:</p>
<pre class="lang:c++ decode:true">void displayCombination(int input1, std::string const&amp; input2, std::string const&amp; input3)
{
    std::cout &lt;&lt; input1 &lt;&lt; '-' &lt;&lt; input2 &lt;&lt; '-' &lt;&lt; input3 &lt;&lt; '\n';
}</pre>
<p>The above code generates all the possible combinations of the elements coming from the three input collections and sends each combination to <code>displayCombination</code>. The output of this program is then:</p>
<pre class="theme:dark-terminal lang:default decode:true ">1-up-blue
1-up-red
1-down-blue
1-down-red
2-up-blue
2-up-red
2-down-blue
2-down-red
3-up-blue
3-up-red
3-down-blue
3-down-red</pre>
<p>A few days ago I published a blog post that suggested that you try and code it up yourself. It&#8217;s not too late to try! Indeed, implementing <code>cartesian_product</code> is a very instructive experiment.</p>
<p>Let&#8217;s see one way of implementing such a <code>cartesian_product</code> in C++.</p>
<h3><span style="color: #ff6600;">The main loop</span></h3>
<p>The main body of the <code>cartesian_product</code> function consists in iterating over all the combinations of the elements coming from the input ranges, and sending each of those combinations to the incoming function.</p>
<p>In pseudo-code, that loops looks like this:</p>
<pre class="lang:c++ decode:true">template&lt;typename Function, typename... Ranges&gt;
void cartesian_product (Function function, Ranges const&amp;... ranges)
{
    for(combination = first combination;
        we finished iterating;
        go to next combination)
    {
        call function on that combination
    }
}</pre>
<p>Our goal is now to transform each of those bits of pseudo-code into real C++ code.</p>
<p>If there were only one collection, the above code would have used an iterator on that collection. To generalise from this, we can use a tuple of iterators: each element of the tuple contains an iterator to an element of one of the input ranges.</p>
<p>We then need to be able to:</p>
<ul>
<li>instantiate this tuple of iterators with the first combination,</li>
<li>call the incoming function on the current combination</li>
<li>make it advance to the next combination,</li>
<li>identify when we&#8217;ve been over all the combinations.</li>
</ul>
<p>By implementing those 4 steps, we&#8217;ll be able to flesh out the above pseudo-code into compiling C++ code.</p>
<h3><span style="color: #ff6600;">Instantiating the first combination</span></h3>
<p>The first combination is probably the easiest one to create: just take an iterator to the first element of each collection:</p>
<pre class="lang:c++ mark:4,6 decode:true">template&lt;typename Function, typename... Ranges&gt;
void cartesian_product (Function function, Ranges const&amp;... ranges)
{
    auto const beginIterators = std::make_tuple(begin(ranges)...);

    for(auto combination = beginIterators;
        we finished iterating;
        go to next combination)
    {
        call function on that combination
    }
}</pre>
<h3><span style="color: #ff6600;">Calling the function on a combination</span></h3>
<p>Now we have a tuple of iterators that represents a combination. But the incoming function doesn&#8217;t take iterators as parameters, much less a tuple of them.</p>
<p>We therefore need to do two things: break up the tuple in individual elements, and dereference each of those elements.</p>
<p>We&#8217;ll do this in the opposite order: we will first create a tuple of <em>references</em> to the elements (as opposed to iterators), then break up this tuple to send individual parameters to the incoming function.</p>
<h4><span style="color: #ff6600;">Creating a tuple of references</span></h4>
<p>Creating a tuple of references out of a tuple of iterators consists in applying a function (here, <code>operator*</code>) on each element. This sounds like a <a href="https://www.fluentcpp.com/2017/02/13/transform-central-algorithm/"><code>std::transform</code></a> but for tuples.</p>
<p>To achieve that we can use one of our <a href="https://www.fluentcpp.com/2019/03/08/stl-algorithms-on-tuples/">algorithm on tuples</a>:</p>
<pre class="lang:c++ decode:true ">template&lt;typename... Ts&gt;
auto dereference(std::tuple&lt;Ts...&gt; const&amp; tuple)
{
    return tuple_algos::transform(tuple, [](auto&amp;&amp; element) -&gt; decltype(auto) { return *element; });
}</pre>
<p>We need to be explicit about the return type of the lambda by using <code>decltype(auto)</code>, because the default type would have returned a copy and not a reference to the element referenced by the iterator. For more about the difference between <code>auto</code> and <code>decltype(auto)</code>, read item 3 of <a href="https://www.amazon.com/gp/product/1491903996/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1491903996&amp;linkCode=as2&amp;tag=fluentcpp-20&amp;linkId=c3922df74051882502a2d72f2e0e7f28">Effective Modern C++</a>.</p>
<h4><span style="color: #ff6600;">Breaking up a tuple into individual function parameters</span></h4>
<p>Now that we have a tuple of references, we have to pass each of them as an argument to the incoming function.</p>
<p>This is exactly what <code>std::apply</code> does:</p>
<pre class="lang:c++ mark:10 decode:true">template&lt;typename Function, typename... Ranges&gt;
void cartesian_product (Function function, Ranges const&amp;... ranges)
{
    auto const beginIterators = std::make_tuple(begin(ranges)...);

    for(auto combination = beginIterators;
        we finished iterating;
        go to next combination)
    {
        std::apply(function, dereference(combination));
    }
}</pre>
<p><code>std::apply</code> comes with C++17. If you don&#8217;t have access to C++17 yet, at the end of this post I will point you to adapted implementations of <code>cartesian_product</code> for C++11 and C++14.</p>
<p>We&#8217;re now left with the iteration itself.</p>
<h3><span style="color: #ff6600;">Generating the next collection</span></h3>
<p>If we have a given combination, what should the next one be?</p>
<p>The way that sounds the most natural to be it to iterate over combinations in a lexicographical order:</p>
<ul>
<li>1) increment the last iterator until reaching the end of the last collection,</li>
<li>2) when we reach the end of the last collection, increment the iterator of the collection before last, and reset the iterator of the last collection to its beginning,</li>
<li>3) repeat the two previous steps, until reaching the end of the collection before last,</li>
<li>then increment the iterators of the collection before the one that is before last,</li>
<li>repeat the previous steps,</li>
<li>and so on.</li>
</ul>
<p>Let&#8217;s implement this recursive definition of the traversal of the collection.</p>
<p>To start, let&#8217;s implement the general step of incrementing the iterator of the <code>I</code>-th collection (the calling code with call this with <code>I</code> = <code>N-1</code> to increment the last iterator, as in the algorithm described above):</p>
<pre class="lang:c++ decode:true">template&lt;size_t I, typename... Iterators&gt;
void increment_iterator(std::tuple&lt;Iterators...&gt;&amp; iterators,
                        std::tuple&lt;Iterators...&gt; const&amp; beginIterators,
                        std::tuple&lt;Iterators...&gt; const&amp; endIterators)
{
    auto&amp; it = std::get&lt;I&gt;(iterators);
    auto const begin = std::get&lt;I&gt;(beginIterators);
    auto const end = std::get&lt;I&gt;(endIterators);
    
    ++it; // step 1) of the algorithm above
    
    if (it == end)
    {
        it = begin; // step 2) of the algorithm above
        increment_iterator&lt;I - 1&gt;::_(iterators, beginIterators, endIterators);  // step 3) of the algorithm above
    }
}
</pre>
<p>The comments in the above snippet are not to be kept in the code, they just indicate which lines of code correspond to the steps listed in the recursive algorithms we described earlier.</p>
<p>We then need to implement the final step of the algorithm: incrementing the iterator in the first collection.</p>
<p>To do that, we need to specialise the above template for <code>I</code> = 0, to just increment the first iterator.</p>
<p>This would be a partial specialisation of the template, because the <code>Iterators...</code> types would still be template parameters. But since we can&#8217;t partially specialise template functions, we need to do the <a href="https://www.fluentcpp.com/2017/08/11/how-to-do-partial-template-specialization-in-c/">usual trick</a> of wrapping them as static function in a template <code>struct</code>.</p>
<p>The whole code of <code>increment_iterator</code> then becomes:</p>
<pre class="lang:c++ decode:true ">template&lt;size_t I&gt;
struct increment_iterator
{
    template&lt;typename... Iterators&gt;
    static void _(std::tuple&lt;Iterators...&gt;&amp; iterators, std::tuple&lt;Iterators...&gt; const&amp; beginIterators, std::tuple&lt;Iterators...&gt; const&amp; endIterators)
    {
        auto&amp; it = std::get&lt;I&gt;(iterators);
        auto const begin = std::get&lt;I&gt;(beginIterators);
        auto const end = std::get&lt;I&gt;(endIterators);
        
        ++it;
        
        if (it == end)
        {
            it = begin;
            increment_iterator&lt;I - 1&gt;::_(iterators, beginIterators, endIterators);
        }
    }
};

template&lt;&gt;
struct increment_iterator&lt;0&gt;
{
    template&lt;typename... Iterators&gt;
    static void _(std::tuple&lt;Iterators...&gt;&amp; iterators, std::tuple&lt;Iterators...&gt; const&amp;, std::tuple&lt;Iterators...&gt; const&amp;)
    {
        auto&amp; it = std::get&lt;0&gt;(iterators);
        
        ++it;
    }
};</pre>
<p>We can now use <code>increment_iterator</code> to generate the next combination:</p>
<pre class="lang:c++ decode:true ">template&lt;typename... Iterators&gt;
void next_combination(std::tuple&lt;Iterators...&gt;&amp; iterators,
                      std::tuple&lt;Iterators...&gt; const&amp; beginIterators,
                      std::tuple&lt;Iterators...&gt; const&amp; endIterators)
{
    constexpr auto N = sizeof...(Iterators);
    increment_iterator&lt;N - 1&gt;::_(iterators, beginIterators, endIterators);
}
</pre>
<p>Finally, we can use this in our main loop:</p>
<pre class="lang:c++ mark:5,9 decode:true">template&lt;typename Function, typename... Ranges&gt;
void cartesian_product (Function function, Ranges const&amp;... ranges)
{
    auto const beginIterators = std::make_tuple(begin(ranges)...);
    auto const endIterators = std::make_tuple(end(ranges)...);

    for(auto combination = beginIterators;
        we finished iterating;
        next_combination(combination, beginIterators, endIterators))
    {
        std::apply(function, dereference(combination));
    }
}</pre>
<p>This was the hardest part! The only step left is to know when to stop incrementing the iterators of the current combination.</p>
<h3><span style="color: #ff6600;">Identifying the end of the combinations</span></h3>
<p>Given our above way of going to the next permutation, we reach the last permutation when we reach the end of the first collection.</p>
<p>This make the stopping condition pretty simple:</p>
<pre class="lang:c++ mark:8 decode:true">template&lt;typename Function, typename... Ranges&gt;
void cartesian_product (Function function, Ranges const&amp;... ranges)
{
    auto const beginIterators = std::make_tuple(begin(ranges)...);
    auto const endIterators = std::make_tuple(end(ranges)...);

    for(auto combination = beginIterators;
        std::get&lt;0&gt;(combination) != std::get&lt;0&gt;(endIterators);
        next_combination(combination, beginIterators, endIterators))
    {
        std::apply(function, dereference(combination));
    }
}</pre>
<h3><span style="color: #ff6600;">The case of en empty collection</span></h3>
<p>There is at least one case that the above code does not cover: the case where there is an empty collection.</p>
<p>Indeed, with an empty collection, we should not dereference the iterator coming from that collection. What to do then?</p>
<p>Let&#8217;s go back to the need: what does it mean to generate all possible combinations of the elements of several collections when one if them is empty? It means: to do nothing at all!</p>
<p>For this reason, we can check that all collections contain data before starting the loop, in order to avoid dereferencing iterators that don&#8217;t reference data, which would make the application crash.</p>
<p>To do this we can use <a href="https://www.fluentcpp.com/2019/03/08/stl-algorithms-on-tuples/#all_of">our <code>any_of</code> algorithm on tuple</a> (while we&#8217;re at it, let&#8217;s also <code>static_assert</code> that there is more than one incoming range):</p>
<pre class="lang:c++ mark:4,5,7 decode:true">template&lt;typename Function, typename... Ranges&gt;
void cartesian_product (Function function, Ranges const&amp;... ranges)
{
    static_assert(sizeof...(Ranges) &gt; 0, "There should be at least one range in cartesian_product.");
    auto const hasEmptyRange = tuple_algos::any_of(std::forward_as_tuple(ranges...), [](auto&amp;&amp; range){ return range.size() == 0; });

    if (!hasEmptyRange)
    {
        auto const beginIterators = std::make_tuple(begin(ranges)...);
        auto const endIterators = std::make_tuple(end(ranges)...);
        
        for (auto combination = beginIterators; std::get&lt;0&gt;(combination) != std::get&lt;0&gt;(endIterators); next_combination(combination, beginIterators, endIterators))
        {
            std::apply(function, dereference(combination));
        }
    }
}</pre>
<p>Here is <a href="http://coliru.stacked-crooked.com/a/4c6e68e275e7736d">all the code put together</a>.</p>
<h3><span style="color: #ff6600;">Not yet at the latest version of C++?</span></h3>
<p>The above code uses several features of C++14 (<code>auto</code> in lambda parameters), and C++17 (<code>std::apply</code>).</p>
<p>If you&#8217;re still in the process of upgrading to the latest and greatest version of C++ but are not quite there yet (a lot of companies are like you!) then you can find a version of this code <a href="http://coliru.stacked-crooked.com/a/a576bcdc83e31850">using only C++14</a>, and one <a href="http://coliru.stacked-crooked.com/a/f60f3a1ea1a04d8e">using only C++11</a> (thanks mika-fischer).</p>
<h3>You will also like</h3>
<ul>
<li><a href="https://www.fluentcpp.com/2017/04/14/understand-ranges-better-with-the-new-cartesian-product-adaptor/">Understand ranges better with the new Cartesian Product adaptor</a></li>
<li><a href="https://www.fluentcpp.com/2019/11/05/mux-zip-without-using-tuples/">Mux: Zip Without Tuples</a></li>
<li><a href="https://www.fluentcpp.com/2019/09/03/the-demux-pipe/">The Demux Pipe</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F03%2F18%2Fhow-to-generate-all-the-combinations-from-several-collections%2F&#038;t=How%20to%20Generate%20All%20the%20Combinations%20from%20Several%20Collections&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F03%2F18%2Fhow-to-generate-all-the-combinations-from-several-collections%2F&#038;p&#091;images&#093;&#091;0&#093;=&#038;p&#091;title&#093;=How%20to%20Generate%20All%20the%20Combinations%20from%20Several%20Collections" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F03%2F18%2Fhow-to-generate-all-the-combinations-from-several-collections%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F03%2F18%2Fhow-to-generate-all-the-combinations-from-several-collections%2F&#038;title=How%20to%20Generate%20All%20the%20Combinations%20from%20Several%20Collections" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2022/03/18/how-to-generate-all-the-combinations-from-several-collections/">How to Generate All the Combinations from Several Collections</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5625</post-id>	</item>
		<item>
		<title>Code It Yourself: Generate All the Combinations from Several Collections</title>
		<link>https://www.fluentcpp.com/2022/03/14/code-it-yourself-generate-all-the-combinations-from-several-collections/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Mon, 14 Mar 2022 01:00:56 +0000</pubDate>
				<category><![CDATA[Expressive code]]></category>
		<category><![CDATA[cartesian product]]></category>
		<category><![CDATA[code it yourself]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=5647</guid>

					<description><![CDATA[<p>A Cartesian product consists in applying a function to all the possible combinations of the elements of several collections. For example, consider the three following collections: auto const inputs1 = std::vector&#60;int&#62; {1, 2, 3}; auto const inputs2 = std::vector&#60;std::string&#62;{"up", "down"}; auto const inputs3 = std::vector&#60;std::string&#62;{"blue", "red"}; Then (2, up, blue) and (3, up, red) are two of [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2022/03/14/code-it-yourself-generate-all-the-combinations-from-several-collections/">Code It Yourself: Generate All the Combinations from Several Collections</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>A Cartesian product consists in applying a function to all the possible combinations of the elements of several collections.</p>
<p>For example, consider the three following collections:</p>
<pre class="lang:c++ decode:true ">auto const inputs1 = std::vector&lt;int&gt; {1, 2, 3};
auto const inputs2 = std::vector&lt;std::string&gt;{"up", "down"};
auto const inputs3 = std::vector&lt;std::string&gt;{"blue", "red"};</pre>
<p>Then <code>(2, up, blue)</code> and <code>(3, up, red)</code> are two of the possible combinations of elements from those three collections.</p>
<p>In total, there are <code>3*2*2</code>, that is 12 possible combinations.</p>
<p>If we apply the following function to each combination:</p>
<pre class="lang:c++ decode:true ">void displayCombination(int input1, std::string const&amp; input2, std::string const&amp; input3)
{
    std::cout &lt;&lt; input1 &lt;&lt; '-' &lt;&lt; input2 &lt;&lt; '-' &lt;&lt; input3 &lt;&lt; '\n';
}</pre>
<p>Then we would expect an output looking like this:</p>
<pre class="theme:dark-terminal lang:default decode:true">1-up-blue
1-up-red
1-down-blue
1-down-red
2-up-blue
2-up-red
2-down-blue
2-down-red
3-up-blue
3-up-red
3-down-blue
3-down-red</pre>
<p>Writing code that generates all those possible combinations is a very instructive exercise.</p>
<p>We&#8217;re going to see one way of achieving that in C++ but, since it&#8217;s instructive, I&#8217;d suggest that you give it a go first to benefit from the reflexion. You&#8217;ll have a chance to code it up right on this page, and in the next post we&#8217;ll see one possible solution.</p>
<h3><span style="color: #ff6600;">The interface</span></h3>
<p>We&#8217;d like to implement a Cartesian product that applies a function to each of the combinations of the elements coming from of an arbitrary number of collections.</p>
<p>A natural interface is to take the function as the first parameter, followed by a variadic pack of ranges:</p>
<pre class="lang:c++ decode:true ">template&lt;typename Function, typename... Ranges&gt;
void cartesian_product (Function function, Ranges const&amp;... ranges)
{
    //...</pre>
<p>There are as many parameters in <code>function</code> as the number of <code>ranges</code> in the variadic pack.</p>
<p><code>cartesian_product</code> picks an element from each range of the pack and passes it to <code>function</code>.</p>
<h3><span style="color: #ff6600;">Give it a try</span></h3>
<p>If the requirement is clear, you can now try to implement it yourself!</p>
<p>Here is a playground with several test cases: a main one with a couple of ranges, and a few corner cases where one of the ranges is empty. In those last cases, we don&#8217;t expect the <code>cartesian_product</code> to generate any combination. Indeed, a combination has to take elements from <em>all</em> the input ranges.</p>
<p>Here is the playground:</p>
<p><iframe loading="lazy" src="https://paiza.io/projects/e/-MLyvOxKGNGfwkosbRQOTg?theme=eclipse" width="100%" height="500" scrolling="no" seamless="seamless"></iframe></p>
<p>Alternatively, you can use this <a href="http://coliru.stacked-crooked.com/a/916f95ca2823232c">Coliru link</a> and keep your attempts for later reference.</p>
<p>In a couple of days I&#8217;ll share with you one possible way to implement <code>cartesian_product</code>. In the meantime, if you write expressive code that passes the above tests, I&#8217;d love to see it!</p>
<p>Please share it a Godbolt link in the comment section below.</p>
<p>Happy coding!</p>
<h3>You will also like</h3>
<ul>
<li><a href="https://www.fluentcpp.com/2019/10/11/code-it-yourself-merging-consecutive-elements-in-a-c-collection/">Code It Yourself: Merging Consecutive Elements in a C++ Collection</a></li>
<li><a href="https://www.fluentcpp.com/2017/04/14/understand-ranges-better-with-the-new-cartesian-product-adaptor/">Understand ranges better with the new Cartesian Product adaptor</a></li>
<li><a href="https://www.fluentcpp.com/2019/11/05/mux-zip-without-using-tuples/">Mux: Zip Without Tuples</a></li>
<li><a href="https://www.fluentcpp.com/2019/01/25/variadic-number-function-parameters-type/">How to Define a Variadic Number of Arguments of the Same Type</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F03%2F14%2Fcode-it-yourself-generate-all-the-combinations-from-several-collections%2F&#038;t=Code%20It%20Yourself%3A%20Generate%20All%20the%20Combinations%20from%20Several%20Collections&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F03%2F14%2Fcode-it-yourself-generate-all-the-combinations-from-several-collections%2F&#038;p&#091;images&#093;&#091;0&#093;=&#038;p&#091;title&#093;=Code%20It%20Yourself%3A%20Generate%20All%20the%20Combinations%20from%20Several%20Collections" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F03%2F14%2Fcode-it-yourself-generate-all-the-combinations-from-several-collections%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F03%2F14%2Fcode-it-yourself-generate-all-the-combinations-from-several-collections%2F&#038;title=Code%20It%20Yourself%3A%20Generate%20All%20the%20Combinations%20from%20Several%20Collections" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2022/03/14/code-it-yourself-generate-all-the-combinations-from-several-collections/">Code It Yourself: Generate All the Combinations from Several Collections</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5647</post-id>	</item>
		<item>
		<title>A Good Way to Handle Errors Is To Prevent Them from Happening in the First Place</title>
		<link>https://www.fluentcpp.com/2022/02/25/a-good-way-to-handle-errors-is-to-prevent-them-from-happening-in-the-first-place/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Fri, 25 Feb 2022 01:00:27 +0000</pubDate>
				<category><![CDATA[Expressive code]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[exceptions]]></category>
		<category><![CDATA[expressive]]></category>
		<category><![CDATA[handling]]></category>
		<category><![CDATA[optional]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[UX]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=5553</guid>

					<description><![CDATA[<p>Error handling is a tricky part of software programming. It&#8217;s tricky in several aspects: it&#8217;s difficult to get right, and it can make code less expressive. But it doesn&#8217;t always have to be that way. Sometimes asking the question &#8220;how can we prevent the error from happening in the first place?&#8221; can avoid the need [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2022/02/25/a-good-way-to-handle-errors-is-to-prevent-them-from-happening-in-the-first-place/">A Good Way to Handle Errors Is To Prevent Them from Happening in the First Place</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><a href="https://www.fluentcpp.com/dailycpp"><img loading="lazy" decoding="async" class="aligncenter wp-image-1947 size-full" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/09/daily-able-content-e1505330890615.png?resize=120%2C116&#038;ssl=1" alt="Daily C++" width="120" height="116" data-recalc-dims="1" /></a></p>
<p>Error handling is a tricky part of software programming.</p>
<p>It&#8217;s tricky in several aspects: it&#8217;s difficult to get right, and it can make code less expressive.</p>
<p>But it doesn&#8217;t always have to be that way. Sometimes asking the question &#8220;how can we prevent the error from happening in the first place?&#8221; can avoid the need for error handling altogether.</p>
<h3><span style="color: #ff6600;">Why handling errors is difficult</span></h3>
<p>Several things make error handling in code difficult.</p>
<h4><span style="color: #ff6600;">We haven&#8217;t got the right tool yet</span></h4>
<p>If you look back on the history of C++, the number of tools for errors handling has been growing at a steady pace.</p>
<p>C used error numbers returned from a function to indicate whether an operation succeeded, and give an error ID to identify the reason why it failed.</p>
<p>C also provided <code>errno</code>, a global indicator for an error number qualifying the last error that happened.</p>
<p>C++ came with exceptions, which allow to exit a function early if it can&#8217;t react to an error.</p>
<p>C++11&#8217;s <code>error_code</code> improved on the concept of error codes.</p>
<p>C++17 brought <code>std::optional</code> into the standard, allowing a function to return nothing in the case it failed to return what it was supposed to. This makes function <a href="https://www.fluentcpp.com/2016/11/24/clearer-interfaces-with-optionalt/">interfaces more expressive</a>.</p>
<p>C++20 almost had contracts (but they were taken out at the last moment). Contracts are a way to handle errors by checking the pre-conditions and post-conditions of an operation.</p>
<p>Looking back on this historical perspective, at any given point in time, better tools to handle errors were to be added in the future. So we never had optimal tools to handle errors.</p>
<p>It&#8217;s no different now. If we take a peek at what the future might hold for us in terms of error handling tools, there are at least two things.</p>
<p>First, <a href="https://www.boost.org/doc/libs/1_70_0/libs/outcome/doc/html/tutorial/essential/outcome.html">Boost Outcome</a> could well make it into a future version of the standard. Boost Outcome is a bit like <code>std::optional</code> in that it allows a function not to return its result if it&#8217;s not able to. But contrary to <code>std::optional</code>, Outcome embeds some information about what went wrong during the operation.</p>
<p><code>expected</code>, which is in the same spirit as Boost Outcome, has been <a href="http://www.open-std.org/jtc1/SC22/wg21/docs/papers/2018/p0323r7.html">proposed</a> to the C++ standard.</p>
<p>Another component that could make it in the standard are <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0709r0.pdf">static exceptions</a>, which have been pushed forward by Herb Sutter. Herb talked about error handling and static exceptions in his <a href="https://www.youtube.com/watch?v=os7cqJ5qlzo">ACCU 2019 keynote</a>.</p>
<p>If you&#8217;d like to see a more detailed overview of C++ errors handling tools than this quick overview, Phil Nash made a good job of listing and comparing error handling strategies in his <a href="https://www.youtube.com/watch?v=OsRty0KNDZ0">C++Now 2018</a> talk.</p>
<p>The point is, there are many tools to handle errors in C++, and more to come, and until we&#8217;re at the final version of C++, we will probably have to wait more to get yet a better tool to handle errors.</p>
<h4><span style="color: #ff6600;">The current tools are difficult to use correctly</span></h4>
<p>If we look back on the first error handling tools, such as error codes, they were quite difficult to use correctly. We couldn&#8217;t make sure the caller checked them at all, and if they checked them, they needed to be very careful not to mix up the error codes.</p>
<p>Exceptions made it impossible for their caller to ignore them, and made the qualification of the error more explicit. But they came with their constraints, in particular having exception safe code.</p>
<p>Making code exception safe is a good thing in itself, as exception safe code tends to have a better design. But there are lots of not-exception-safe code out there, which makes it difficult to use exceptions.</p>
<p>The more recent tools don&#8217;t have those issues, but whatever the tool we use to handle errors, we still need to write code to deal with them. This is code that is not in the &#8220;happy path&#8221;, which is the code that gets executed when no error is happening.</p>
<p>When we think about coding up a feature, we (or at least, myself) tend to think about the happy path. Whatever the tool we use, handling errors adds more complexity to the code, and makes it by itself more difficult to understand and creates potential sources for incorrect behaviour.</p>
<h3><span style="color: #ff6600;">Preventing errors from happening in the first place</span></h3>
<p>Another approach when designing a software solution for a problem is to prevent errors from happening in the first place.</p>
<p>When we struggle with handling errors in code, we can simply ask ourselves: &#8220;can we prevent this error from happening in the first place?&#8221;</p>
<p>The very fact of thinking about this possibility opens a range of solutions that we don&#8217;t explore when we focus on choosing between using exceptions or <code>std::optional</code>.</p>
<p>One way to prevent errors from happening is by working on the user interface. In an application with a GUI, we can make small fixes that make certain combinations of configuration impossible to set up.</p>
<p>When the user chooses a certain option in the GUI, we can make the components react to that action. For example, we can open a modal window to force the user to go all the way through a series of choices or cancel that first option altogether. Or we can hide or disable some components to prevent the user from selecting inconsistent options.</p>
<p>I&#8217;m no UX expert, but several times a simple fix in the UI avoided us to put cumbersome error handling in our code. And it&#8217;s better for the user too: if no error happens, the user doesn&#8217;t get to see annoying error messages. The user is guided by the UI to make sure they stay in the &#8220;happy path&#8221;.</p>
<p>This has the advantage of making the user aware of what the happy path is. I&#8217;ve seen once an application was silently falling back on the happy path when the user selected a configuration the application wasn&#8217;t supporting. Even if this led to the application producing a &#8220;happy path&#8221; result, it silently fell back on a behaviour that the user didn&#8217;t ask for. This doesn&#8217;t look like a good solution overall.</p>
<p>I&#8217;m not saying that all errors can be handled by constraining the user interface. But some can, and every time it starts by asking the question &#8220;can we prevent this error from happening in the first place?&#8221;</p>
<p>Does your team usually think about this question? How do you prevent errors from happening in the first place?</p>
<h3>You will also like</h3>
<ul>
<li><a href="https://www.fluentcpp.com/2019/08/20/a-concise-implementation-of-fizzbuzz-with-stdoptional/">A Concise Implementation of Fizzbuzz with std::optional</a></li>
<li><a href="https://www.fluentcpp.com/2016/11/24/clearer-interfaces-with-optionalt/">Clearer interfaces with optional&lt;T&gt;</a></li>
<li><a href="https://www.fluentcpp.com/2019/08/27/extract-function-should-i-extract-the-condition-too/">Extract Function: Should I Extract the Condition Too?</a></li>
<li><a href="https://www.fluentcpp.com/2017/07/21/making-if-statements-understandable/">How to Make If Statements More Understandable</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F02%2F25%2Fa-good-way-to-handle-errors-is-to-prevent-them-from-happening-in-the-first-place%2F&#038;t=A%20Good%20Way%20to%20Handle%20Errors%20Is%20To%20Prevent%20Them%20from%20Happening%20in%20the%20First%20Place&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F02%2F25%2Fa-good-way-to-handle-errors-is-to-prevent-them-from-happening-in-the-first-place%2F&#038;p&#091;images&#093;&#091;0&#093;=https%3A%2F%2Fwww.fluentcpp.com%2Fwp-content%2Fuploads%2F2017%2F09%2Fdaily-able-content-e1505330890615.png&#038;p&#091;title&#093;=A%20Good%20Way%20to%20Handle%20Errors%20Is%20To%20Prevent%20Them%20from%20Happening%20in%20the%20First%20Place" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F02%2F25%2Fa-good-way-to-handle-errors-is-to-prevent-them-from-happening-in-the-first-place%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F02%2F25%2Fa-good-way-to-handle-errors-is-to-prevent-them-from-happening-in-the-first-place%2F&#038;title=A%20Good%20Way%20to%20Handle%20Errors%20Is%20To%20Prevent%20Them%20from%20Happening%20in%20the%20First%20Place" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2022/02/25/a-good-way-to-handle-errors-is-to-prevent-them-from-happening-in-the-first-place/">A Good Way to Handle Errors Is To Prevent Them from Happening in the First Place</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5553</post-id>	</item>
		<item>
		<title>Design Patterns VS Design Principles: Visitor</title>
		<link>https://www.fluentcpp.com/2022/02/09/design-patterns-vs-design-principles-visitor/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Wed, 09 Feb 2022 01:00:23 +0000</pubDate>
				<category><![CDATA[Expressive code]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[design principles]]></category>
		<category><![CDATA[GoF]]></category>
		<category><![CDATA[grasp]]></category>
		<category><![CDATA[visitor]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=5131</guid>

					<description><![CDATA[<p>In today&#8217;s episode of the series &#8220;Design Pattens VS Design Principles&#8221;, we&#8217;re focusing on the last behavioural design pattern: Visitor, and see how it relates to the High Cohesion design principle. The GoF meets the GRASP If you&#8217;re just joining the series, The GoF meets the GRASP is about relating each of the GoF design [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2022/02/09/design-patterns-vs-design-principles-visitor/">Design Patterns VS Design Principles: Visitor</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In today&#8217;s episode of the series &#8220;Design Pattens VS Design Principles&#8221;, we&#8217;re focusing on the last behavioural design pattern: <strong>Visitor</strong>, and see how it relates to the High Cohesion design principle.</p>
<h3><span style="color: #ff6600;">The GoF meets the GRASP</span></h3>
<p>If you&#8217;re just joining the series, The GoF meets the GRASP is about relating each of the GoF design patterns with one of the 9 GRASP design principles.</p>
<p>GoF design patterns are the 23 patterns in the hugely popular <a href="https://www.amazon.com/gp/product/0201633612/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0201633612&amp;linkId=8d82c9d9fb2521a0d54f2f07c0bc12e0">Design Patterns</a> book:</p>
<p><a href="https://www.amazon.com/gp/product/0201633612/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0201633612&amp;linkId=8d82c9d9fb2521a0d54f2f07c0bc12e0"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-5042" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=400%2C503&#038;ssl=1" alt="design patterns book GoF" width="400" height="503" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?w=400&amp;ssl=1 400w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=119%2C150&amp;ssl=1 119w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=239%2C300&amp;ssl=1 239w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=25%2C32&amp;ssl=1 25w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=80%2C100&amp;ssl=1 80w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=160%2C201&amp;ssl=1 160w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=318%2C400&amp;ssl=1 318w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/design_patterns_book.jpg?resize=350%2C440&amp;ssl=1 350w" sizes="(max-width: 400px) 100vw, 400px" data-recalc-dims="1" /></a></p>
<p>GRASP design principles are higher level principles that are explained in Craig Larman&#8217;s <a href="https://www.amazon.com/gp/product/0131489062/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0131489062&amp;linkId=c8f9976423d1df2c59c9acd303a2ff14">Applying UML and Patterns</a>:</p>
<p><a href="https://www.amazon.com/gp/product/0131489062/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0131489062&amp;linkId=c8f9976423d1df2c59c9acd303a2ff14"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4971" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=400%2C500&#038;ssl=1" alt="Applying UML and Patterns" width="400" height="500" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?w=400&amp;ssl=1 400w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=120%2C150&amp;ssl=1 120w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=240%2C300&amp;ssl=1 240w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=26%2C32&amp;ssl=1 26w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=80%2C100&amp;ssl=1 80w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=161%2C201&amp;ssl=1 161w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=320%2C400&amp;ssl=1 320w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/04/51gVLEtrCNL._SX398_BO1204203200_.jpg?resize=352%2C440&amp;ssl=1 352w" sizes="(max-width: 400px) 100vw, 400px" data-recalc-dims="1" /></a></p>
<p>The <a href="https://www.fluentcpp.com/2021/06/23/grasp-9-must-know-design-principles-for-code/">9 GRASP design principles</a> are:</p>
<ul>
<li>Low Coupling</li>
<li>High cohesion</li>
<li>Creator</li>
<li>Information expert</li>
<li>Polymorphism</li>
<li>Indirection</li>
<li>Protected Variations</li>
<li>Pure Fabrication</li>
<li>Controller</li>
</ul>
<p>Let&#8217;s analyse the GoF design pattern <strong>Visitor</strong>, and decide to which GRASP principle it relates the most.</p>
<h3><span style="color: #ff6600;">Visitor</span></h3>
<p>In short, the Visitor design pattern consists in separating objects from operations into two separate class hierarchies.</p>
<p>In more details, consider a set of classes representing objects:</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-5132" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor1.png?resize=469%2C152&#038;ssl=1" alt="" width="469" height="152" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor1.png?w=469&amp;ssl=1 469w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor1.png?resize=150%2C49&amp;ssl=1 150w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor1.png?resize=300%2C97&amp;ssl=1 300w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor1.png?resize=32%2C10&amp;ssl=1 32w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor1.png?resize=250%2C81&amp;ssl=1 250w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor1.png?resize=201%2C65&amp;ssl=1 201w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor1.png?resize=350%2C113&amp;ssl=1 350w" sizes="(max-width: 469px) 100vw, 469px" data-recalc-dims="1" /></p>
<p>Those objects have operations X, Y and Z. Those operations share the same semantics, but not the same implementation. Put another way, each class has a specific way to accomplish X, a specific way to accomplish Y, and a specific way to accomplish Z:</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-5134" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor2.png?resize=469%2C152&#038;ssl=1" alt="" width="469" height="152" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor2.png?w=469&amp;ssl=1 469w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor2.png?resize=150%2C49&amp;ssl=1 150w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor2.png?resize=300%2C97&amp;ssl=1 300w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor2.png?resize=32%2C10&amp;ssl=1 32w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor2.png?resize=250%2C81&amp;ssl=1 250w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor2.png?resize=201%2C65&amp;ssl=1 201w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor2.png?resize=350%2C113&amp;ssl=1 350w" sizes="(max-width: 469px) 100vw, 469px" data-recalc-dims="1" /></p>
<p>The Visitor design pattern consists in refactoring this design by dedicating specific classes to X, Y and Z:</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-5135" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor3.png?resize=985%2C152&#038;ssl=1" alt="" width="985" height="152" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor3.png?w=985&amp;ssl=1 985w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor3.png?resize=150%2C23&amp;ssl=1 150w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor3.png?resize=300%2C46&amp;ssl=1 300w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor3.png?resize=768%2C119&amp;ssl=1 768w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor3.png?resize=32%2C5&amp;ssl=1 32w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor3.png?resize=250%2C39&amp;ssl=1 250w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor3.png?resize=201%2C31&amp;ssl=1 201w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor3.png?resize=350%2C54&amp;ssl=1 350w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor3.png?resize=729%2C112&amp;ssl=1 729w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor3.png?resize=800%2C123&amp;ssl=1 800w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor3.png?resize=980%2C151&amp;ssl=1 980w" sizes="(max-width: 985px) 100vw, 985px" data-recalc-dims="1" /></p>
<p>Seen this way, Visitor allows to create <strong>High Cohesion</strong>. Indeed, without Visitor, class A was concerned about X, Y and Z. With Visitor, there is a class X of which the sole responsibility is to perform the operation X.</p>
<p>Note that even if Visitor is a way to achieve High Cohesion, I don&#8217;t think that Visitor is a Pure Fabrication. Indeed, operations such as X, Y and Z can map to operations of the domain that the code is modelling.</p>
<h4><span style="color: #ff6600;">But what about the <code>visit()</code> method?</span></h4>
<p>If you&#8217;ve ever read a description of the Visitor design pattern, chances are that it drew attention on the <code>visit</code> and <code>accept</code> methods.</p>
<p>In the above description, they don&#8217;t appear once. Why?</p>
<p>I think that they are just one way to implement Visitor as described, and they are not part of the essence of the pattern.</p>
<p>Just in case you haven&#8217;t come across the <code>visit</code> and <code>accept</code> method, here is how they work. First, they require you to put the code of the operations as methods of the corresponding classes:</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-5137" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor4.png?resize=985%2C152&#038;ssl=1" alt="" width="985" height="152" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor4.png?w=985&amp;ssl=1 985w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor4.png?resize=150%2C23&amp;ssl=1 150w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor4.png?resize=300%2C46&amp;ssl=1 300w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor4.png?resize=768%2C119&amp;ssl=1 768w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor4.png?resize=32%2C5&amp;ssl=1 32w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor4.png?resize=250%2C39&amp;ssl=1 250w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor4.png?resize=201%2C31&amp;ssl=1 201w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor4.png?resize=350%2C54&amp;ssl=1 350w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor4.png?resize=729%2C112&amp;ssl=1 729w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor4.png?resize=800%2C123&amp;ssl=1 800w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor4.png?resize=980%2C151&amp;ssl=1 980w" sizes="(max-width: 985px) 100vw, 985px" data-recalc-dims="1" /></p>
<p>Second, they require to have an interface above each of the two groups of classes. Those interfaces contain the <code>visit</code> and <code>accept</code> methods:</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-5138" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor5.png?resize=985%2C327&#038;ssl=1" alt="" width="985" height="327" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor5.png?w=985&amp;ssl=1 985w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor5.png?resize=150%2C50&amp;ssl=1 150w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor5.png?resize=300%2C100&amp;ssl=1 300w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor5.png?resize=768%2C255&amp;ssl=1 768w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor5.png?resize=32%2C11&amp;ssl=1 32w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor5.png?resize=250%2C83&amp;ssl=1 250w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor5.png?resize=201%2C67&amp;ssl=1 201w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor5.png?resize=350%2C116&amp;ssl=1 350w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor5.png?resize=729%2C242&amp;ssl=1 729w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor5.png?resize=800%2C266&amp;ssl=1 800w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/visitor5.png?resize=980%2C325&amp;ssl=1 980w" sizes="(max-width: 985px) 100vw, 985px" data-recalc-dims="1" /></p>
<p>Notes: <code>Object</code> and <code>Operation</code> are generic terms used here for the explanation. In practice, they would carry domain names. In the example, <code>operation</code> is <code>const</code> and <code>object</code> is not, but that could be different in practice too. And the operations return <code>void</code>, but they could also return something.</p>
<p>Then the <code>visit</code> and <code>accept</code> methods play a ping pong game in order to reach the implementation of the correct operation on the correct class. Here is how it works:</p>
<p>The user has an <code>Object&amp; object</code> reference and a <code>Operation const&amp; operation</code> reference. The user calls <code>visit</code> on the operation by passing the object:</p>
<pre class="lang:c++ decode:true ">operation.visit(object);</pre>
<p>The implementation of <code>visit</code> looks like this:</p>
<pre class="lang:c++ decode:true">void Operation::visit(Object&amp; object) const
{
    object.accept(*this);
}</pre>
<p>This calls the virtual method <code>accept</code> on the object hierarchy, which goes into one of the concrete implementation (not on the above diagram for simplicity). Say that the concrete type of the Object is A. The execution goes into:</p>
<pre class="lang:c++ decode:true ">void A::accept(Operation const&amp; operation)
{
    operation.operateOnA(*this);
}</pre>
<p>The object A passes the ball back to the operation hierarchy, calling the virtual method <code>operateOnA</code> (the fact that it&#8217;s virtual is omitted from the above diagram for simplicity). This leads to the concrete implementation of <code>operateOnA</code> in the concrete operation.</p>
<p>Say that the concrete operation is X. Then the execution goes to:</p>
<pre class="lang:c++ decode:true">void X::operateOnA(A&amp; a)
{
    // actual operation, the code that used
    // to be in doX() of class A,
    // at the beginning of the article.
}</pre>
<p>The execution was sent from the operation to the object, and back to the operation. Why?</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-5139" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/table-tennis-1208376_640.jpg?resize=640%2C434&#038;ssl=1" alt="" width="640" height="434" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/table-tennis-1208376_640.jpg?w=640&amp;ssl=1 640w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/table-tennis-1208376_640.jpg?resize=150%2C102&amp;ssl=1 150w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/table-tennis-1208376_640.jpg?resize=300%2C203&amp;ssl=1 300w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/table-tennis-1208376_640.jpg?resize=32%2C22&amp;ssl=1 32w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/table-tennis-1208376_640.jpg?resize=147%2C100&amp;ssl=1 147w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/table-tennis-1208376_640.jpg?resize=201%2C136&amp;ssl=1 201w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/table-tennis-1208376_640.jpg?resize=350%2C237&amp;ssl=1 350w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2019/05/table-tennis-1208376_640.jpg?resize=590%2C400&amp;ssl=1 590w" sizes="(max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<h4><span style="color: #ff6600;">An emulation of double dispatch</span></h4>
<p>That table tennis exchange comes from the fact that in C++, like in many languages, we can only resolve virtual calls on <strong>one type at the same time</strong>.</p>
<p>It would have been ideal to be able to write code like this:</p>
<pre class="lang:c++ decode:true">void perform(Operation const&amp; operation, Object&amp; object);

perform(operation, object);</pre>
<p>And that would have called one of nine functions taking each possible combination of (A,B,C) with (X,Y,Z). This is called runtime double-dispatch. Some languages do that (Smalltalk, I think?) but C++ doesn&#8217;t.</p>
<p>Therefore, we have to resolve one polymorphic interface at a time. First the <code>Object</code> interface in the <code>visit</code> method, then the <code>Operation</code> interface in the <code>accept</code> method.</p>
<p>In fact, there is a way to emulate this in C++, relying on <code>std::map</code> and <code>std::type_info</code>, that Scott Meyers explains in detail in Item 31 of <a href="https://www.amazon.com/gp/product/020163371X/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=020163371X&amp;linkCode=as2&amp;tag=fluentcpp-20&amp;linkId=df11bf21fa25de620998ae20b17eb9e7">More Effective C++</a>. Check out the book for more details about that.</p>
<p>Note though that C++ has compile-time multiple-dispatch, a.k.a function overloading, that could be used to implement the Visitor design pattern, without <code>visit</code> and <code>accept</code>, and even without the <code>Object</code> and <code>Operation</code> interfaces.</p>
<p>But to use it, we need to know the concrete types of the object and the operation at compile time.</p>
<p>If the last two sentences didn&#8217;t make sense, that&#8217;s all right. It&#8217;s outside of the scope of this post, and we&#8217;ll get back to it in detail in articles dedicated to polymorphism.</p>
<h4><code><span style="color: #ff6600;">std::variant</span></code><span style="color: #ff6600;">&#8216;s visitor</span></h4>
<p>There is yet another implementation of the Visitor design pattern in the C++ standard library, in C++17, with <code>std::variant</code>. The standard library even offers a function called <code>std::visit</code>.</p>
<p>You can pass it an object that can be called on each type of the variant, along with the variant itself:</p>
<pre class="lang:c++ decode:true ">auto const object = std::variant&lt;int, std::string, double&gt;{"forty-two"};

auto const x = [](auto const&amp; object){ std::cout &lt;&lt; object &lt;&lt; '\n'; };

std::visit(x, object);</pre>
<p>This code displays:</p>
<pre class="theme:dark-terminal lang:default decode:true ">forty-two</pre>
<p>For more forms of operations, check out the <a href="https://en.cppreference.com/w/cpp/utility/variant/visit">reference page of <code>std::visit</code></a>.</p>
<p>The variant type plays the role of the <code>Object</code> interface, and the lambda plays the role of one of the operations.</p>
<p>So this is like <strong>half a Visitor</strong>. Indeed, there can be several types of objects, but only one type of operation. There is no polymorphism on the operation side. Only on the object side.</p>
<h3><span style="color: #ff6600;">Various levels of polymorphism</span></h3>
<p>In the Visitor design pattern, the various polymorphisms are just ways to implement the pattern. Its essence is rather to create <strong>High Cohesion</strong> by separating objects from operations.</p>
<p>The various types of polymorphism only make Visitor more or less generic:</p>
<p>In its rawest expression, the Visitor design pattern could separate one operation from one class, and have no interface nor polymorphism in place.</p>
<p>A more elaborate form is to have one operation on several types of objects. Then we need some sort of polymorphism in place. If you only need polymorphism on the object side and you know the set of possible types of objects, you don&#8217;t need more than a <code>std::variant</code>. Otherwise you need virtual functions in one hierarchy.</p>
<p>Now if you have several types of objects and several types of operations, you need a double polymorphism, which is commonly called double-dispatch. If you know the types at compile time you can use function overloading.</p>
<p>If you don&#8217;t know the types at compile time, you have to resort to the full-fledged construction of <code>visit</code> and <code>accept</code> that is commonly presented for the Visitor pattern, or use the C++-y solution in Item 31 of <a href="https://www.amazon.com/gp/product/020163371X/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=020163371X&amp;linkCode=as2&amp;tag=fluentcpp-20&amp;linkId=df11bf21fa25de620998ae20b17eb9e7">More Effective C++</a>.</p>
<h3>You will also like</h3>
<ul>
<li><a href="https://www.fluentcpp.com/2021/07/26/design-patterns-vs-design-principles-chain-of-responsibility-command-and-interpreter/">Design Patterns VS Design Principles: Chain of responsibility, Command and Interpreter</a></li>
<li><a href="https://www.fluentcpp.com/2021/09/12/design-patterns-vs-design-principles-iterator-mediator-and-memento/">Design Patterns VS Design Principles: Iterator, Mediator and Memento</a></li>
<li><a href="https://www.fluentcpp.com/2021/10/19/design-patterns-vs-design-principles-observer-state-and-strategy/">Design Patterns VS Design Principles: Observer, State and Strategy</a></li>
<li><a href="https://www.fluentcpp.com/2021/11/17/design-patterns-vs-design-principles-template-method/">Design Patterns VS Design Principles: Template Method</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F02%2F09%2Fdesign-patterns-vs-design-principles-visitor%2F&#038;t=Design%20Patterns%20VS%20Design%20Principles%3A%20Visitor&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F02%2F09%2Fdesign-patterns-vs-design-principles-visitor%2F&#038;p&#091;images&#093;&#091;0&#093;=https%3A%2F%2Fwww.fluentcpp.com%2Fwp-content%2Fuploads%2F2019%2F05%2Fdesign_patterns_book.jpg&#038;p&#091;title&#093;=Design%20Patterns%20VS%20Design%20Principles%3A%20Visitor" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F02%2F09%2Fdesign-patterns-vs-design-principles-visitor%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F02%2F09%2Fdesign-patterns-vs-design-principles-visitor%2F&#038;title=Design%20Patterns%20VS%20Design%20Principles%3A%20Visitor" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2022/02/09/design-patterns-vs-design-principles-visitor/">Design Patterns VS Design Principles: Visitor</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5131</post-id>	</item>
		<item>
		<title>Which Programming Paradigm Gives the Most Expressive Code?</title>
		<link>https://www.fluentcpp.com/2022/01/24/programming-paradigm-gives-expressive-code/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Mon, 24 Jan 2022 01:00:16 +0000</pubDate>
				<category><![CDATA[Expressive code]]></category>
		<category><![CDATA[best code]]></category>
		<category><![CDATA[declarative]]></category>
		<category><![CDATA[expressive]]></category>
		<category><![CDATA[functional]]></category>
		<category><![CDATA[imperative]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[oriented]]></category>
		<category><![CDATA[paradigm]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=3236</guid>

					<description><![CDATA[<p>Warning: this post gets into a very opinionated subject. You may agree with some points, you may disagree with others, it may trigger controversy, and you may be tempted to seize your keyboard to tell how you have a completely different view on programming. This is exactly what I want you to do. Rather than [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2022/01/24/programming-paradigm-gives-expressive-code/">Which Programming Paradigm Gives the Most Expressive Code?</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><span style="text-decoration: underline;"><strong>Warning</strong></span>: this post gets into a very opinionated subject. You may agree with some points, you may disagree with others, it may trigger controversy, and you may be tempted to seize your keyboard to tell how you have a completely different view on programming.</p>
<p>This is exactly what I want you to do. Rather than pouring down my opinions, my point is to ignite a debate with you on how to use programming paradigms to write expressive code.</p>
<p>In fact, as you&#8217;ll see, I will largely quote the opinions of some other people I had the chance to watch or talk to. There is no right or wrong answer so please, let us hear your opinion too! <strong><span style="text-decoration: underline;">End of warning</span></strong></p>
<p>In her <a href="https://youtu.be/uNPdZm5oF_E" target="_blank" rel="noopener noreferrer">closing keynote</a> of Polyconf 2017, Anjana Vakil classifies programming paradigms into 4:</p>
<ul>
<li><strong>the imperative paradigm</strong>: the program consists in a structured set of instructions for the computer to execute,</li>
<li><strong>the object-oriented paradigm</strong>: the program consists in objects that send messages to each other,</li>
<li><strong>the functional paradigm</strong>: the program consists in functions that call each other,</li>
<li><strong>the declarative paradigm</strong>: the program consists in statements that describe the intention of the programmer.</li>
</ul>
<p>They roughly correspond to overlapping periods in the history of computer programming.</p>
<p>Some languages fall into one of those paradigms. For instance, Haskell is totally in the functional programming paradigm, whereas SmallTalk is in the object-oriented one. Some other languages, like C++ or Python, span across several programming paradigms.</p>
<p>So choosing a programming paradigm doesn&#8217;t always mean choosing a language. It can also be programming in your language with a certain programming style. As Steve McConnell puts it, rather than programming in a language, you want to program <strong>into</strong> a language. This essentially means that we should strive to work around the capabilities of a language to implement what we think is the most adapted style possible.</p>
<p>So, what is the best paradigm to write expressive code in C++, or in any other language?</p>
<h3><span style="color: #ff6600;">Functional <span style="color: #000000;"><span style="color: #ff6600;">is the new</span> object-oriented</span></span></h3>
<p>It&#8217;s funny to see how paradigms shape our view on programming.</p>
<p>Well, that&#8217;s essentially the definition of a paradigm after all, but it&#8217;s striking to dig writings from the past and see how the world of programming sometimes revolved around a unique concept.</p>
<p>Take for example the excellent article <a href="http://www.laputan.org/pub/patterns/noble/noble.pdf" target="_blank" rel="noopener noreferrer">Arguments and Results</a> from James Noble. This article was published in 1997 and, back then, the ultimate view on programming was to be object-oriented. The hype was then around Java, the OO part of C++, SmallTalk and the like.</p>
<p>In this article, James describes object methods as &#8220;protocols&#8221; and he writes:</p>
<blockquote>
<div class="page" title="Page 3">
<div class="layoutArea">
<div class="column">
<p>a program&#8217;s protocols are the glue that binds its objects together</p>
</div>
</div>
</div>
</blockquote>
<p>He also states that &#8220;Object&#8217;s protocols also known as interfaces are very important in object oriented design&#8221;, but the above quotation says a lot about what the emphasis was on at the time: <strong>objects</strong>.</p>
<p>The 90&#8217;s were the glory of the object-oriented paradigm, but today this is no longer quite true. Objects still have a large share in programs, but today the <strong>functional programming</strong> paradigm is becoming increasingly popular.</p>
<p>We&#8217;ve seen functional languages, such as Haskell, that had lived in the academic field for decades, burst out to the public attention over the past few years. So much so that some universities that I know (EPITECH in Paris) require their students to hand in some of the assignments in Haskell.</p>
<p>Also, the functional trend is seeping its way into mainstream languages, with Java 8 taking on streams and lambdas, and modern C++ also including lambdas and (hopefully, hopefully soon) range-like constructs.</p>
<p>What&#8217;s so good about functional programming?</p>
<p>One typical property of functional programming is that <strong>it forbids mutable state</strong>. In pure functional programming, variables don&#8217;t even exist. And in imperative and object-oriented programming, a lot of bugs come from a mutable state&#8230; that is not in the state it should be. This immutability property allows to get rid of a whole class of bugs, and is at least partly responsible for the success of functional programming.</p>
<p>Also, not having mutable state has another nice consequence: when reading code, you don&#8217;t have to maintain in your head the various states of the program. This makes the code that much easier to understand, and that much expressive.</p>
<h3><span style="color: #ff6600;">Is object-oriented hopeless then?</span></h3>
<p>Seduced by the modern trend of functional programming and its advantages, one may be tempted to think that the object-oriented paradigm is a steam engine of programming: it was convenient at the time we didn&#8217;t know better, but its most useful place now is in a museum.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-3238" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/02/steam-train.jpg?resize=800%2C504&#038;ssl=1" alt="programming paradigms" width="800" height="504" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/02/steam-train.jpg?w=800&amp;ssl=1 800w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/02/steam-train.jpg?resize=150%2C95&amp;ssl=1 150w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/02/steam-train.jpg?resize=300%2C189&amp;ssl=1 300w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/02/steam-train.jpg?resize=768%2C484&amp;ssl=1 768w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/02/steam-train.jpg?resize=32%2C20&amp;ssl=1 32w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/02/steam-train.jpg?resize=159%2C100&amp;ssl=1 159w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/02/steam-train.jpg?resize=201%2C127&amp;ssl=1 201w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/02/steam-train.jpg?resize=350%2C221&amp;ssl=1 350w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/02/steam-train.jpg?resize=635%2C400&amp;ssl=1 635w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/02/steam-train.jpg?resize=698%2C440&amp;ssl=1 698w" sizes="(max-width: 800px) 100vw, 800px" data-recalc-dims="1" /></p>
<p>But programming paradigms aren&#8217;t really like trains.</p>
<p>Rather, when a programming paradigm ousts another one there are <strong>two things</strong> we can do:</p>
<ul>
<li>find what the two paradigms <strong>have in common</strong>. This points us to even deeper programming concepts that outlive paradigms,</li>
</ul>
<ul>
<li>search for useful ways to <strong>make them work together</strong>. After all, all paradigms had enough traction to change the world&#8217;s view on programming. There must be some of their specific aspects that are worth saving from the trash, right?</li>
</ul>
<p>Let&#8217;s dig into those two aspects.</p>
<h3><span style="color: #ff6600;">Modularity and its siblings don&#8217;t want to die</span></h3>
<p>One of the big things about <strong>objects</strong> is that they <strong>expose an interface</strong>, that hides data and behaviour that stay confined to an implementation behind that interface. Then the other objects can evolve around that interfaces, without seeing the implementations.</p>
<p>This concept of exposing an interface has several facets:</p>
<ul>
<li><strong>modularity </strong>and decoupling: interfaces create clear boundaries between the various objects interacting together and helps making them independent from one another. This makes the system more structured, and therefore easier to understand and change.</li>
</ul>
<ul>
<li><strong>encapsulation</strong>: the implementation being hidden from the clients of an object, changing it only goes so far as the internal boundary of that objects delimited by the interface.</li>
</ul>
<ul>
<li><strong>polymorphism</strong>: another possible change is to swap out an implementation of an interface for another. In object-oriented systems, this can even happen at runtime with <code>virtual</code> methods,</li>
</ul>
<ul>
<li><strong>levels of abstraction</strong>: an interface defines a level of abstraction, and its implementation is at the level immediately below it. And writing expressive code mostly <a href="https://www.fluentcpp.com/2016/12/15/respect-levels-of-abstraction/">comes down to respecting levels of abstraction</a>.</li>
</ul>
<p>It turns out that those concepts are also present in functional programming. For one thing, functions define an interface and you could nearly replace the word &#8220;object&#8221; with &#8220;function&#8221; in the 4 above concepts. But functional languages also have more elaborate ways to define interfaces, like with Haskell&#8217;s type classes.</p>
<p>And when you think about it, those concepts where also present in imperative programming, although in a much more basic way: by splitting the code into subroutines.</p>
<p>All this illustrates the interesting fact that modularity, encapsulation, polymorphism and levels of abstractions are fundamental notions to write good code, and they transcend programming languages and even programming paradigms.</p>
<p>This ties up well with the two main aspects of programming defined by Steve McConnell in <a href="https://www.amazon.com/gp/product/0735619670/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0735619670&amp;linkCode=as2&amp;tag=fluentcpp-20&amp;linkId=d5740a1b637d19f7324be8302bc12b6b">Code Complete</a>: managing complexity and reacting to change.</p>
<h3><span style="color: #ff6600;">Making paradigms collaborate</span></h3>
<p>Another way to benefit from the variety of paradigms is to <strong>make them work together</strong>.</p>
<p>John Carmack takes the position of <a href="https://web.archive.org/web/20130819160454/http://www.altdevblogaday.com/2012/04/26/functional-programming-in-c/" target="_blank" rel="noopener noreferrer">avoiding mutating state in general</a>, whenever this is practical and doesn&#8217;t kill performance. In the rarer cases where it does impact performance, he advocates to be practical and go for the side effects (for instance don&#8217;t return a copy of a C++ standard container each time you want to add something to it).</p>
<p>I have had the opportunity to talk with Michael Feathers about that question too. His view on the topic sounded quite sensible to me: a good way to mix object-oriented code with functional code is to structure your code with objects, and implement their methods in a functional programming style.</p>
<p>It seems to me that there are also cases where using objects inside of a functional-like piece of code can help making the code more expressive.</p>
<p>Take the example of <strong>curried objects</strong>. These objects can lump several functions together and make them share a common input. They can even play the role of adapters by embedding some logic and translate an interface into another.</p>
<p>Actually, and I know this can sound surprising in this context, those objects can even hold some mutable state. Take the example of an object that builds a CSV line from various strings that you send to it. The object remembers if it is at the beginning of the line to know whether or not to write a comma. If you have to have a mutable state, you might as well encapsulate it in an object rather that let it spill over the various call sites in the code.</p>
<h3><span style="color: #ff6600;">The declarative paradigm, the ultimate style or just another passing paradigm?</span></h3>
<p>The declarative paradigm is a interesting trend even though there aren&#8217;t as many programs that use it compared to the other paradigms. By declarative, I mean code where you merely state your intentions of the desired behaviour, as opposed to how to implement the desired behaviour.</p>
<p>At this stage, this style seems very attractive to me. Indeed, you have to state your intentions at some point, as the computer can&#8217;t figure them out for you. But if we could do <em>only</em> that, it would transform the face of programming.</p>
<p>When I talk about expressive code, I usually describe this as code where you can understand the intent of the person who wrote it. If the code were merely intentions, well, we would be there.</p>
<p>However, it seems difficult to achieve from a practical point of view today. The closest we can get is by designing <strong>declarative interfaces</strong>, and writing code to implement them.</p>
<p>One example is by implementing Domain Specific Languages (DSL). Another example we&#8217;ve come across is to use a rules engine to make declarative if statements:</p>
<pre class="lang:c++ decode:true">auto isAGoodCustomer = RulesEngine{};

isGoodCustomer.If(customer.purchasedGoodsValue()) &gt;= 1000);
isGoodCustomer.If(!customer.hasReturnedItems()));
isGoodCustomer.If(std::find(begin(surveyResponders), end(surveyResponders), customer) != end(surveyResponders));

auto isNotAGoodCustomer = isAGoodCustomer.Not;
isNotAGoodCustomer.If(customer.hasDefaulted());

if (isAGoodCustomer())
{
    // ...
}
else
{
    // ...
}</pre>
<p>Apart for a few technical artifacts, this syntax of this code shares similarities with a specification document that expresses the intent we have for the program.</p>
<p>Declarative programming is a fascinating area, and if you have ideas on how to write declarative code, I would be grateful if you shared them with me.</p>
<h3><span style="color: #ff6600;">Let&#8217;s discuss programming paradigms</span></h3>
<p>If you found this article interesting and generally agree with it, that&#8217;s cool. But if you disagree and have a different view on programming and paradigms, it&#8217;s great, and now is the time to let your voice be heard in the comments section that&#8217;s all yours!</p>
<p>Related articles:</p>
<ul>
<li>Using a rules engine to make declarative if statements</li>
<li><a href="https://www.fluentcpp.com/2016/12/15/respect-levels-of-abstraction/">It all comes down to respecting levels of abstraction</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F01%2F24%2Fprogramming-paradigm-gives-expressive-code%2F&#038;t=Which%20Programming%20Paradigm%20Gives%20the%20Most%20Expressive%20Code%3F&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F01%2F24%2Fprogramming-paradigm-gives-expressive-code%2F&#038;p&#091;images&#093;&#091;0&#093;=https%3A%2F%2Fwww.fluentcpp.com%2Fwp-content%2Fuploads%2F2018%2F02%2Fsteam-train.jpg&#038;p&#091;title&#093;=Which%20Programming%20Paradigm%20Gives%20the%20Most%20Expressive%20Code%3F" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F01%2F24%2Fprogramming-paradigm-gives-expressive-code%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2022%2F01%2F24%2Fprogramming-paradigm-gives-expressive-code%2F&#038;title=Which%20Programming%20Paradigm%20Gives%20the%20Most%20Expressive%20Code%3F" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2022/01/24/programming-paradigm-gives-expressive-code/">Which Programming Paradigm Gives the Most Expressive Code?</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3236</post-id>	</item>
	</channel>
</rss>
