<?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/"
	>

<channel>
	<title>The GITS Blog &#187; c++</title>
	<atom:link href="http://ginstrom.com/scribbles/category/programming/cpp/feed/" rel="self" type="application/rss+xml" />
	<link>http://ginstrom.com/scribbles</link>
	<description>Random scribbling about programming, translation, and Japan</description>
	<lastBuildDate>Wed, 20 Apr 2011 05:09:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>cpptempl: A string templating library for C++</title>
		<link>http://ginstrom.com/scribbles/2010/10/30/cpptempl-a-template-language-for-c/</link>
		<comments>http://ginstrom.com/scribbles/2010/10/30/cpptempl-a-template-language-for-c/#comments</comments>
		<pubDate>Sat, 30 Oct 2010 12:42:27 +0000</pubDate>
		<dc:creator>Ryan Ginstrom</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://ginstrom.com/scribbles/?p=1629</guid>
		<description><![CDATA[cpptempl is a simple string templating language (or templating engine) for C++. It has loops, conditionals, and variable interpolation. cpptempl relies on the boost libraries (shared_ptr, string_algo, and lexical_cast). I originally wrote this engine because I was generating HTML files in C++, and generating the HTML right in the C++ quickly got very hairy, besides [...]]]></description>
			<content:encoded><![CDATA[<p><a href="https://bitbucket.org/ginstrom/cpptemplate/overview">cpptempl</a> is a simple string templating language (or <em>templating engine</em>) for C++. It has loops, conditionals, and variable interpolation. cpptempl relies on the boost libraries (shared_ptr, string_algo, and lexical_cast).</p>
<p>I originally wrote this engine because I was generating HTML files in C++, and generating the HTML right in the C++ quickly got very hairy, besides the fact that it made the content very hard to maintain. If all you need is string interpolation, something like <a href="http://live.boost.org/doc/libs/1_42_0/libs/format/index.html">Boost.Format</a> would probably be enough, but I quickly found myself wanting to include lists of objects (e.g. search results), include content conditionally, and so on.</p>
<p>I was inspired to write this library by the approach of the major web frameworks like django and rails.</p>
<p>Here's a quick example:</p>
<div class="dean_ch" style="white-space: wrap;">
<span class="co1">// The text template</span><br />
wstring text = L<span class="st0">&quot;I heart {$place}!&quot;</span> ;<br />
<span class="co1">// Data to feed the template engine</span><br />
cpptempl::<span class="me2">data_map</span> data ;<br />
<span class="co1">// {$place} =&gt; Okinawa</span><br />
data<span class="br0">&#91;</span>L<span class="st0">&quot;place&quot;</span><span class="br0">&#93;</span> = cpptempl::<span class="me2">make_data</span><span class="br0">&#40;</span>L<span class="st0">&quot;Okinawa&quot;</span><span class="br0">&#41;</span>;<br />
<span class="co1">// parse the template with the supplied data dictionary</span><br />
wstring result = cpptempl::<span class="me2">parse</span><span class="br0">&#40;</span>text, data<span class="br0">&#41;</span> ;</div>
<p>The result will be:</p>
<div class="dean_ch" style="white-space: wrap;">
I heart Okinawa!</div>
<p>Here's how you might generate an HTML unordered list:</p>
<div class="dean_ch" style="white-space: wrap;">
<span class="co1">// You'd probably load this template from a file in real life.</span><br />
wstring text = L<span class="st0">&quot;&lt;h3&gt;Locations&lt;/h3&gt;<span class="es0">\n</span>&lt;ul&gt;<span class="es0">\n</span>&quot;</span><br />
&nbsp; &nbsp; L<span class="st0">&quot;{% for place in places %}&quot;</span><br />
&nbsp; &nbsp; L<span class="st0">&quot;&lt;li&gt;{$place}&lt;/li&gt;<span class="es0">\n</span>&quot;</span><br />
&nbsp; &nbsp; L<span class="st0">&quot;{% endfor %}&quot;</span><br />
&nbsp; &nbsp; L<span class="st0">&quot;&lt;/ul&gt;&quot;</span> ;</p>
<p><span class="co1">// Create the list of items</span><br />
cpptempl::<span class="me2">data_list</span> places;<br />
places.<span class="me1">push_back</span><span class="br0">&#40;</span>cpptempl::<span class="me2">make_data</span><span class="br0">&#40;</span>L<span class="st0">&quot;Okinawa&quot;</span><span class="br0">&#41;</span><span class="br0">&#41;</span>;<br />
places.<span class="me1">push_back</span><span class="br0">&#40;</span>cpptempl::<span class="me2">make_data</span><span class="br0">&#40;</span>L<span class="st0">&quot;San Francisco&quot;</span><span class="br0">&#41;</span><span class="br0">&#41;</span>;<br />
<span class="co1">// Now set this in the data map</span><br />
cpptempl::<span class="me2">data_map</span> data ;<br />
data<span class="br0">&#91;</span>L<span class="st0">&quot;places&quot;</span><span class="br0">&#93;</span> = cpptempl::<span class="me2">make_data</span><span class="br0">&#40;</span>places<span class="br0">&#41;</span>;<br />
<span class="co1">// parse the template with the supplied data dictionary</span><br />
wstring result = cpptempl::<span class="me2">parse</span><span class="br0">&#40;</span>text, data<span class="br0">&#41;</span> ;</div>
<p>The result will be:</p>
<div class="dean_ch" style="white-space: wrap;">&lt;h3&gt;Locations&lt;/h3&gt;<br />
&lt;ul&gt;<br />
&lt;li&gt;Okinawa&lt;/li&gt;<br />
&lt;li&gt;San Francisco&lt;/li&gt;<br />
&lt;/ul&gt;</div>
<h3>Syntax</h3>
<p>The template syntax is fairly simple and highly influenced by Python. You can use loops, conditionals, and variables. You can use dotted notation (item.thing) for dictionary-like variables. The only data type is string.</p>
<h4>Variable Syntax</h4>
<p>Use {$<em>variable_name</em>} for variables. You can use dotted notation for sub-fields.</p>
<div class="dean_ch" style="white-space: wrap;">
His name <span class="kw1">is</span> <span class="br0">&#123;</span>$name<span class="br0">&#125;</span>.<br />
<span class="me1">His</span> telephone <span class="kw1">is</span> <span class="br0">&#123;</span>$person.<span class="me1">telephone</span><span class="br0">&#125;</span>.<br />
&nbsp;</div>
<h4>Loop Syntax</h4>
<div class="dean_ch" style="white-space: wrap;">
<span class="br0">&#123;</span>% <span class="kw1">for</span> item <span class="kw1">in</span> items %<span class="br0">&#125;</span><br />
<span class="br0">&#123;</span>$loop<span class="br0">&#125;</span>. <span class="br0">&#123;</span>$item<span class="br0">&#125;</span><br />
<span class="br0">&#123;</span>% endfor %<span class="br0">&#125;</span></p>
<p>Friends:<br />
<span class="br0">&#123;</span>% <span class="kw1">for</span> friend <span class="kw1">in</span> person.<span class="me1">friends</span> %<span class="br0">&#125;</span><br />
<span class="br0">&#123;</span>$loop<span class="br0">&#125;</span>. <span class="br0">&#123;</span>$friend.<span class="me1">name</span><span class="br0">&#125;</span><br />
<span class="br0">&#123;</span>% endfor %<span class="br0">&#125;</span></div>
<p>Note the "<code>loop</code>" variable that provides a counter in all loops. <code>loop0</code> is zero-indexed.</p>
<h4>If Syntax</h4>
<div class="dean_ch" style="white-space: wrap;">
<span class="br0">&#123;</span>% <span class="kw1">if</span> name == <span class="st0">&quot;Bob&quot;</span> %<span class="br0">&#125;</span><br />
<span class="br0">&#40;</span>His name <span class="kw1">is</span> really Robert<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span>% endif %<span class="br0">&#125;</span></p>
<p><span class="br0">&#123;</span>% <span class="kw1">if</span> name != <span class="st0">&quot;Bob&quot;</span> %<span class="br0">&#125;</span><br />
<span class="br0">&#40;</span>His name <span class="kw1">is</span> <span class="kw1">not</span> Bob<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span>% endif %<span class="br0">&#125;</span></p>
<p><span class="br0">&#123;</span>% <span class="kw1">if</span> name %<span class="br0">&#125;</span><br />
<span class="br0">&#40;</span>He has a name<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span>% endif %<span class="br0">&#125;</span></p>
<p><span class="br0">&#123;</span>% <span class="kw1">if</span> <span class="kw1">not</span> name %<span class="br0">&#125;</span><br />
<span class="br0">&#40;</span>He has no name<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span>% endif %<span class="br0">&#125;</span></div>
<p>Note that <code>not</code> means empty: If the variable name doesn't exist, then an exception will be thrown.</p>
<h4>API Example</h4>
<p>Here's a slightly more involved example of using the API, showing dot notation and loop syntax.</p>
<div class="dean_ch" style="white-space: wrap;">using namespace cpptempl ;</p>
<p><span class="co1">// The text template. Loop through person's friends</span><br />
wstring text = L<span class="st0">&quot;{% for friend in person.friends %}&quot;</span><br />
&nbsp; &nbsp; L<span class="st0">&quot;{$loop}. {$friend.name} &quot;</span><br />
&nbsp; &nbsp; L<span class="st0">&quot;{% endfor %}&quot;</span> ;</p>
<p><span class="co1">// Bob</span><br />
data_map bob ;<br />
bob<span class="br0">&#91;</span>L<span class="st0">&quot;name&quot;</span><span class="br0">&#93;</span> = make_data<span class="br0">&#40;</span>L<span class="st0">&quot;Bob&quot;</span><span class="br0">&#41;</span> ;<br />
<span class="co1">// Betty</span><br />
data_map betty ;<br />
betty<span class="br0">&#91;</span>L<span class="st0">&quot;name&quot;</span><span class="br0">&#93;</span> = make_data<span class="br0">&#40;</span>L<span class="st0">&quot;Betty&quot;</span><span class="br0">&#41;</span> ;<br />
<span class="co1">// List of friends</span><br />
data_list friends ;<br />
friends.<span class="me1">push_back</span><span class="br0">&#40;</span>make_data<span class="br0">&#40;</span>bob<span class="br0">&#41;</span><span class="br0">&#41;</span> ;<br />
friends.<span class="me1">push_back</span><span class="br0">&#40;</span>make_data<span class="br0">&#40;</span>betty<span class="br0">&#41;</span><span class="br0">&#41;</span> ;<br />
<span class="co1">// Person and person's list of friends</span><br />
data_map person ;<br />
person<span class="br0">&#91;</span>L<span class="st0">&quot;friends&quot;</span><span class="br0">&#93;</span> = make_data<span class="br0">&#40;</span>friends<span class="br0">&#41;</span> ;<br />
<span class="co1">// The data</span><br />
data_map data ;<br />
data<span class="br0">&#91;</span>L<span class="st0">&quot;person&quot;</span><span class="br0">&#93;</span> = make_data<span class="br0">&#40;</span>person<span class="br0">&#41;</span> ;</p>
<p><span class="co1">// Resolve the template</span><br />
wstring result = cpptempl::<span class="me2">parse</span><span class="br0">&#40;</span>text, data<span class="br0">&#41;</span> ;</div>
<p>The output will be:</p>
<div class="dean_ch" style="white-space: wrap;">1. Bob 2. Betty</div>
<p>See the <a href="https://bitbucket.org/ginstrom/cpptemplate/wiki/Home">bitbucket wiki page</a> for more details.</p>
]]></content:encoded>
			<wfw:commentRss>http://ginstrom.com/scribbles/2010/10/30/cpptempl-a-template-language-for-c/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Implementing IDocHostUIHandler in a C++ WTL/ATL project</title>
		<link>http://ginstrom.com/scribbles/2009/11/18/implementing-idochostuihandler/</link>
		<comments>http://ginstrom.com/scribbles/2009/11/18/implementing-idochostuihandler/#comments</comments>
		<pubDate>Tue, 17 Nov 2009 22:41:13 +0000</pubDate>
		<dc:creator>Ryan Ginstrom</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[IDocHostUIHandler]]></category>
		<category><![CDATA[web browser]]></category>
		<category><![CDATA[wtl]]></category>

		<guid isPermaLink="false">http://ginstrom.com/scribbles/?p=1370</guid>
		<description><![CDATA[I recently implemented IDocHostUIHandler in one of my WTL projects hosting the web browser. You need to implement this interface if you want to do things like control the context menu of the web browser. I had to go spelunking in various forums and documentation to piece together how to do this, and I never [...]]]></description>
			<content:encoded><![CDATA[<p>I recently implemented <a href="http://msdn.microsoft.com/en-us/library/aa753260%28VS.85%29.aspx">IDocHostUIHandler</a> in one of my <a href="http://wtl.sourceforge.net/">WTL</a> projects hosting the web browser. You need to implement this interface if you want to do things like control the context menu of the web browser.</p>
<p>I had to go spelunking in various forums and documentation to piece together how to do this, and I never found the complete story online, so I thought I'd save any future searchers some trouble. I only did this in Visual Studio 2008, but I've done similar things in VS 2005, so it should work there also.</p>
<p>You should already have a WTL project with an .idl file that implements a COM server. If not, create a new WTL project with the wizard named "MyProject", and choose the option to make it a COM server.</p>
<h3>Add an ATL Simple Object</h3>
<p>Next, add a new class to your project, and select the type "ATL Simple Object."</p>
<p>Here's where you might hit your first snag. You might see the following error dialog:</p>
<div id="attachment_1379" class="wp-caption alignnone" style="width: 496px"><img src="http://ginstrom.com/scribbles/wp-content/uploads/2009/11/err_only_mfc1.png" alt="Error, only MFC projects please" title="Error only MFC" width="486" height="185" class="size-full wp-image-1379" /><p class="wp-caption-text">ATL classes can only be added to MFC EXE and MFC Regular DLL projects or projects with full ATL support</p></div>
<p>"I'm using the ATL, you idiot!" you yell vainly at your computer screen. But alas, the compiler gods did not consider that you might want to use something as esoteric as the WTL for your GUI project, when you have the obviously superior choice of MFC.</p>
<p>To convince Visual Studio that yes, you do deserve to add an ATL Simple Object to your project, you've got to modify the file "VS Root/VC/VCWizards/1033/common.js". Specifically, you've got to have the function <code>IsATLProject</code> return <code>true</code>.</p>
<p>On the Internet, you'll see all sorts of fixes to this function, but I just cut to the chase:</p>
<div class="dean_ch" style="white-space: wrap;">
<span class="kw2">function</span> IsATLProject<span class="br0">&#40;</span>oProj<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp; <span class="co1">// I promise that I will use this only for good and not evil.</span><br />
&nbsp; &nbsp; <span class="kw1">return</span> <span class="kw2">true</span> ;<br />
&nbsp; &nbsp; <span class="kw1">try</span><br />
&nbsp; &nbsp; <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &#8230;</div>
<p>Try adding the object again; this time, you should be successful. Name your class something descriptive, like "MyHandler" ( <img src='http://ginstrom.com/scribbles/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ), and accept all the defaults.</p>
<h3>Modify the .idl file</h3>
<p>Now go into your .idl file, and make some edits. First, <code>import "atliface.idl"</code>, and <code>#include "olectl.h"</code>. The top of your file should now look like this:</p>
<div class="dean_ch" style="white-space: wrap;">
import <span class="st0">&quot;oaidl.idl&quot;</span>;<br />
import <span class="st0">&quot;ocidl.idl&quot;</span>;<br />
import <span class="st0">&quot;atliface.idl&quot;</span>;</p>
<p><span class="co2">#include &quot;olectl.h&quot;</span></div>
<p>Now, go to your IMyHandler interface, and change the base class from <code>IDispatch</code> to <code>IDocHostUIHandlerDispatch</code>, like so:</p>
<div class="dean_ch" style="white-space: wrap;">
<span class="br0">&#91;</span><br />
&nbsp; &nbsp; object,<br />
&nbsp; &nbsp; uuid<span class="br0">&#40;</span><span class="nu0">12345678</span><span class="nu0">-1234</span><span class="nu0">-1234</span><span class="nu0">-1234</span>-123456789ABC<span class="br0">&#41;</span>,<br />
&nbsp; &nbsp; dual,<br />
&nbsp; &nbsp; nonextensible,<br />
&nbsp; &nbsp; helpstring<span class="br0">&#40;</span><span class="st0">&quot;IMyHandler Interface&quot;</span><span class="br0">&#41;</span>,<br />
&nbsp; &nbsp; pointer_default<span class="br0">&#40;</span>unique<span class="br0">&#41;</span><br />
<span class="br0">&#93;</span><br />
<span class="kw1">interface</span> IMyHandler : IDocHostUIHandlerDispatch<span class="br0">&#123;</span><br />
<span class="br0">&#125;</span>;</div>
<h3>Modify your MyHandler.h file</h3>
<p>Go into your CMyHandler class file, and <code>#include "Atliface.h"</code>. Next, add an entry to your COM map for <code>IDocHostUIHandlerDispatch</code>. The top of your file should now look something like this:</p>
<div class="dean_ch" style="white-space: wrap;">
<span class="co2">#pragma once</span><br />
<span class="co2">#include &quot;resource.h&quot; &nbsp; &nbsp; &nbsp; // main symbols</span><br />
<span class="co2">#include &quot;Atliface.h&quot;</span><br />
<span class="co2">#include &quot;MyProject.h&quot;</span></p>
<p><span class="co2">#if defined(_WIN32_WCE) &amp;&amp; !defined(_CE_DCOM) &amp;&amp; !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA)</span><br />
<span class="co2">#error &quot;Blah blah blah&quot;</span><br />
<span class="co2">#endif</span></p>
<p><span class="co1">// CMyHandler</span></p>
<p><span class="kw2">class</span> ATL_NO_VTABLE CMyHandler :<br />
&nbsp; &nbsp; <span class="kw2">public</span> CComObjectRootEx&lt;CComSingleThreadModel&gt;,<br />
&nbsp; &nbsp; <span class="kw2">public</span> CComCoClass&lt;CMyHandler, &amp;CLSID_MyHandler&gt;,<br />
&nbsp; &nbsp; <span class="kw2">public</span> IDispatchImpl&lt;IMyHandler, &amp;IID_MyHandler, &amp;LIBID_MyProject, <span class="coMULTI">/*wMajor =*/</span> <span class="nu0">1</span>, <span class="coMULTI">/*wMinor =*/</span> <span class="nu0">0</span>&gt;<br />
<span class="br0">&#123;</span><br />
<span class="kw2">public</span>:</p>
<p>&nbsp; &nbsp; CMyHandler<span class="br0">&#40;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; <span class="br0">&#123;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span></p>
<p>DECLARE_REGISTRY_RESOURCEID<span class="br0">&#40;</span>IDR_MYHANDLER<span class="br0">&#41;</span></p>
<p>
BEGIN_COM_MAP<span class="br0">&#40;</span>CMyHandler<span class="br0">&#41;</span><br />
&nbsp; &nbsp; COM_INTERFACE_ENTRY<span class="br0">&#40;</span>IMyHandler<span class="br0">&#41;</span><br />
&nbsp; &nbsp; COM_INTERFACE_ENTRY<span class="br0">&#40;</span>IDocHostUIHandlerDispatch<span class="br0">&#41;</span><br />
&nbsp; &nbsp; COM_INTERFACE_ENTRY<span class="br0">&#40;</span>IDispatch<span class="br0">&#41;</span><br />
END_COM_MAP<span class="br0">&#40;</span><span class="br0">&#41;</span></div>
<h3>Add skeletons for the IDocHostUIHandler methods</h3>
<p>Add skeletons for all the methods implemented by <code>IDocHostUIHandler</code>. You can simply copy and paste the method signatures from IDocHostUIHandlerDispatch in "Atliface.h". Now implement the method bodies so that they all return <code>E_NOTIMPL</code>.</p>
<h3>Compile your code</h3>
<p>Now compile, and make sure that everything's working. </p>
<p>Here's where you might hit another snag: by failing to show proper respect to the compiler gods above, you could see an obscure MIDL error when you try to compile. Even if you don't, I recommend compiling your .idl file manually just to be sure. Go to <strong>All Programs</strong> &gt;&gt; <strong>Visual Studio 200X</strong> &gt;&gt; <strong>Visual Studio Tools</strong> &gt;&gt; <strong>Command Prompt</strong> (this loads the command prompt with all your VS symbols defined). </p>
<p>Next, navigate to your source directory, and compile your .idl file:</p>
<div class="dean_ch" style="white-space: wrap;">
midl MyProject.idl</div>
<h3>Implement methods of interest</h3>
<p>Now, you can implement the methods you're interested in. For example, if you want to suppress the context menu, or show your own menu in its place:</p>
<div class="dean_ch" style="white-space: wrap;">
HRESULT STDMETHODCALLTYPE ShowContextMenu<span class="br0">&#40;</span>DWORD dwID, DWORD x, DWORD y, IUnknown *pcmdtReserved, IDispatch *pdispReserved, HRESULT *dwRetVal <span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp; *dwRetVal = S_OK;<br />
&nbsp; &nbsp; <span class="co1">// Show your own context menu here if you want.</span><br />
&nbsp; &nbsp; <span class="kw1">return</span> S_OK;<br />
<span class="br0">&#125;</span></div>
<h3>Set the handler in your web browser</h3>
<p>In your OnCreate handler, set your handler in the web browser.</p>
<div class="dean_ch" style="white-space: wrap;">
&nbsp; &nbsp; CComObject&lt;CMyHandler&gt; *pUIH = <span class="kw2">NULL</span>;<br />
&nbsp; &nbsp; HRESULT hr = CComObject&lt;CMyHandler&gt;::<span class="me2">CreateInstance</span> <span class="br0">&#40;</span>&amp;pUIH<span class="br0">&#41;</span>;<br />
&nbsp; &nbsp; <span class="kw1">if</span> <span class="br0">&#40;</span>SUCCEEDED<span class="br0">&#40;</span>hr<span class="br0">&#41;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">// Make our custom DocHostUIHandler the window.external handler</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; CComQIPtr&lt;IDocHostUIHandlerDispatch&gt; pIUIH = pUIH;<br />
&nbsp; &nbsp; &nbsp; &nbsp; hr = m_view.<span class="me1">SetExternalUIHandler</span><span class="br0">&#40;</span>pIUIH<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; ATLASSERT<span class="br0">&#40;</span>SUCCEEDED<span class="br0">&#40;</span>hr<span class="br0">&#41;</span><span class="br0">&#41;</span> ;</div>
<p>That's it. Compile and run.</p>
]]></content:encoded>
			<wfw:commentRss>http://ginstrom.com/scribbles/2009/11/18/implementing-idochostuihandler/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Coming from C++/Java to Python should bend your mind</title>
		<link>http://ginstrom.com/scribbles/2009/02/03/coming-from-cjava-to-python-should-bend-your-mind/</link>
		<comments>http://ginstrom.com/scribbles/2009/02/03/coming-from-cjava-to-python-should-bend-your-mind/#comments</comments>
		<pubDate>Tue, 03 Feb 2009 02:30:38 +0000</pubDate>
		<dc:creator>Ryan Ginstrom</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[pythonic]]></category>

		<guid isPermaLink="false">http://ginstrom.com/scribbles/?p=839</guid>
		<description><![CDATA[Coming from C++ or Java to Python should bend your mind. If it doesn't, then you haven't learned Python yet &#8212; you're just writing C++ or Java in Python. If you only knew a statically typed and compiled language like C++ or Java before, and learning Python hasn't changed the way you think about programming, [...]]]></description>
			<content:encoded><![CDATA[<p>Coming from C++ or Java to Python should bend your mind. If it doesn't, then you haven't learned Python yet &#8212; you're just writing C++ or Java in Python.</p>
<p>If you only knew a statically typed and compiled language like C++ or Java before, and learning Python hasn't changed the way you think about programming, then check your programs for lots of type-checking code, inheritance, array indexing, and mutable variables. Look at some <a href="http://effbot.org/">excellent</a> <a href="http://www.aleax.it/python_mat_en.html">Python</a> <a href="http://code.activestate.com/recipes/">code</a>, and identify where your code diverges from it.</p>
]]></content:encoded>
			<wfw:commentRss>http://ginstrom.com/scribbles/2009/02/03/coming-from-cjava-to-python-should-bend-your-mind/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Google&#8217;s Chrome browser uses the WTL for Windows</title>
		<link>http://ginstrom.com/scribbles/2008/09/18/googles-chrome-browser-uses-the-wtl-for-windows/</link>
		<comments>http://ginstrom.com/scribbles/2008/09/18/googles-chrome-browser-uses-the-wtl-for-windows/#comments</comments>
		<pubDate>Thu, 18 Sep 2008 10:49:38 +0000</pubDate>
		<dc:creator>Ryan Ginstrom</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[c++ wtl google chrome]]></category>

		<guid isPermaLink="false">http://ginstrom.com/scribbles/?p=272</guid>
		<description><![CDATA[As pointed out in this post, Google's new Chrome browser uses the Windows Template Library (WTL) in its Windows version. I've long been a fan of the WTL &#8212; I've written several programs in it, including Felix, Doc2Html, and Tag Assist &#8212; and it's great to see it getting some love. In my opinion, the [...]]]></description>
			<content:encoded><![CDATA[<p>As pointed out in <a href="http://www.hanselman.com/blog/TheWeeklySourceCode33MicrosoftOpenSourceInsideGoogleChrome.aspx">this post</a>, Google's new <a href="http://www.google.com/chrome">Chrome browser</a> uses the <a href="http://wtl.sourceforge.net/">Windows Template Library (WTL)</a> in its Windows version.</p>
<p>I've long been a fan of the WTL &#8212; I've written several programs in it, including <a href="http://felix-cat.com/">Felix</a>, <a href="/software/doc2html/">Doc2Html</a>, and <a href="http://felix-cat.com/tagassist/">Tag Assist</a> &#8212; and it's great to see it getting some love.</p>
<p>In my opinion, the WTL is simply the best way to write Win32 programs in C++. <a href="http://en.wikipedia.org/wiki/Microsoft_Foundation_Class_Library">MFC</a> was written before Visual Studio really supported templates. One of the MFC team once said that the WTL is what they would have written if good template support had been available.</p>
]]></content:encoded>
			<wfw:commentRss>http://ginstrom.com/scribbles/2008/09/18/googles-chrome-browser-uses-the-wtl-for-windows/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mocking file output for unit testing</title>
		<link>http://ginstrom.com/scribbles/2008/08/29/mocking-file-output-for-unit-testing/</link>
		<comments>http://ginstrom.com/scribbles/2008/08/29/mocking-file-output-for-unit-testing/#comments</comments>
		<pubDate>Fri, 29 Aug 2008 04:05:31 +0000</pubDate>
		<dc:creator>Ryan Ginstrom</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[c++ unit-testing]]></category>

		<guid isPermaLink="false">http://ginstrom.com/scribbles/?p=130</guid>
		<description><![CDATA[Having a unit test harness makes modifying code a lot easier, because it lets you quickly spot anything you've broken as you're coding. But when you've got legacy code that doesn't have unit tests, getting the code into a test harness can be a lot of work. You've got code connecting to databases, touching the [...]]]></description>
			<content:encoded><![CDATA[<p>Having a unit test harness makes modifying code a lot easier, because it lets you quickly spot anything you've broken as you're coding. But when you've got legacy code that doesn't have unit tests, getting the code into a test harness can be a lot of work. You've got code connecting to databases, touching the file system, and interacting with the GUI all over the place.</p>
<p>In order to get that kind of code into a test harness, I first create "characterization tests" &#8212; tests that simply verify what the code is doing. I let the code write files, connect to databases, etc. Then I gradually modify them to create a layer between the code and the outside world, which I can then manipulate for testing.</p>
<p>Here's a very simple example. I have a ConfigWriter class, which (duh) writes config files. The class lets you set and get various properties, and then write the config file, specifying a file name.</p>
<div class="dean_ch" style="white-space: wrap;">
class ConfigWriter<br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp; map&lt;string, string&gt; m_props ;<br />
public:<br />
&nbsp; &nbsp; <span class="kw4">void</span> set_prop<span class="br0">&#40;</span><span class="kw4">const</span> <span class="kw4">string</span> &amp;key, <span class="kw4">const</span> <span class="kw4">string</span> &amp;val<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; <span class="kw4">string</span> get_prop<span class="br0">&#40;</span><span class="kw4">const</span> <span class="kw4">string</span> &amp;key<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; <span class="kw4">void</span> write<span class="br0">&#40;</span><span class="kw4">const</span> <span class="kw4">string</span> &amp;filename<span class="br0">&#41;</span> ;<br />
<span class="br0">&#125;</span> ;</div>
<p>The class has been doing great, but now I want to modify it. Maybe I want to add functionality, or maybe I've found a bug. At any rate, before I make the changes I want to get this class into a test harness &#8212; but I want to be able to unit test it without touching the file system.</p>
<p>My first step is to write a unit test that confirms what the class actually does. I use <a href="http://easyunit.sourceforge.net/">EasyUnit</a> as my unit-testing framework, but you can use any framework you're happy with.</p>
<div class="dean_ch" style="white-space: wrap;">
TEST<span class="br0">&#40;</span> TestConfigWriter, write <span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp; ConfigWriter writer ;<br />
&nbsp; &nbsp; writer.<span class="me1">set_prop</span><span class="br0">&#40;</span><span class="st0">&quot;files&quot;</span>, <span class="st0">&quot;3&quot;</span><span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; writer.<span class="me1">set_prop</span><span class="br0">&#40;</span><span class="st0">&quot;drives&quot;</span>, <span class="st0">&quot;1&quot;</span><span class="br0">&#41;</span> ;</p>
<p>&nbsp; &nbsp; <span class="kw4">string</span> fname = <span class="st0">&quot;/tmp/config_test1.ini&quot;</span> ;<br />
&nbsp; &nbsp; writer.<span class="me1">write</span><span class="br0">&#40;</span>fname<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; <span class="kw4">string</span> expected = <span class="st0">&quot;files=3<span class="es0">\r</span><span class="es0">\n</span>drives=1&quot;</span> ;<br />
&nbsp; &nbsp; <span class="co1">// a helper class that creates a memory-mapped file</span><br />
&nbsp; &nbsp; MMFile mm_file ;<br />
&nbsp; &nbsp; <span class="kw4">string</span> actual = mm_file.<span class="me1">create_view</span><span class="br0">&#40;</span>fname<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; ASSERT_EQUALS_V<span class="br0">&#40;</span>expected, actual<span class="br0">&#41;</span> ;<br />
<span class="br0">&#125;</span></div>
<p>I run the test, and it passes. Now I add a new <code>write</code> method, which takes a pointer to an <code>ostream</code> instead of a file name.</p>
<div class="dean_ch" style="white-space: wrap;">
class ConfigWriter<br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp; map&lt;string, string&gt; m_props ;<br />
public:<br />
&nbsp; &nbsp; <span class="kw4">void</span> set_prop<span class="br0">&#40;</span><span class="kw4">const</span> <span class="kw4">string</span> &amp;key, <span class="kw4">const</span> <span class="kw4">string</span> &amp;val<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; <span class="kw4">string</span> get_prop<span class="br0">&#40;</span><span class="kw4">const</span> <span class="kw4">string</span> &amp;key<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; <span class="kw4">void</span> write<span class="br0">&#40;</span><span class="kw4">const</span> <span class="kw4">string</span> &amp;filename<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; <span class="kw4">void</span> write<span class="br0">&#40;</span>ostream *writer<span class="br0">&#41;</span> ;<br />
<span class="br0">&#125;</span> ;</div>
<p>I run my unit tests, and make sure that they still work. Then I add a new unit test to test the new method:</p>
<div class="dean_ch" style="white-space: wrap;">
TEST<span class="br0">&#40;</span> TestConfigWriter, write_stream <span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp; ConfigWriter writer ;<br />
&nbsp; &nbsp; writer.<span class="me1">set_prop</span><span class="br0">&#40;</span><span class="st0">&quot;files&quot;</span>, <span class="st0">&quot;3&quot;</span><span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; writer.<span class="me1">set_prop</span><span class="br0">&#40;</span><span class="st0">&quot;drives&quot;</span>, <span class="st0">&quot;1&quot;</span><span class="br0">&#41;</span> ;</p>
<p>&nbsp; &nbsp; <span class="kw4">string</span> fname = <span class="st0">&quot;/tmp/config_test1.ini&quot;</span> ;<br />
&nbsp; &nbsp; ofstream stream ;<br />
&nbsp; &nbsp; stream.<span class="me1">open</span><span class="br0">&#40;</span>fname.<span class="me1">c_str</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; writer.<span class="me1">write</span><span class="br0">&#40;</span>&amp;stream<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; stream.<span class="me1">close</span><span class="br0">&#40;</span><span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; <span class="kw4">string</span> expected = <span class="st0">&quot;files=3<span class="es0">\r</span><span class="es0">\n</span>drives=1&quot;</span> ;<br />
&nbsp; &nbsp; <span class="co1">// a helper class that creates a memory-mapped file</span><br />
&nbsp; &nbsp; MMFile mm_file ;<br />
&nbsp; &nbsp; <span class="kw4">string</span> actual = mm_file.<span class="me1">create_view</span><span class="br0">&#40;</span>fname<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; ASSERT_EQUALS_V<span class="br0">&#40;</span>expected, actual<span class="br0">&#41;</span> ;<br />
<span class="br0">&#125;</span></div>
<p>Once I make sure they pass, I modify the <code>write(const string &#038;fname)</code> method so that it calls the <code>ostream</code> version.</p>
<div class="dean_ch" style="white-space: wrap;">
<span class="kw4">void</span> ConfigWriter::<span class="me2">write</span><span class="br0">&#40;</span><span class="kw4">const</span> <span class="kw4">string</span> &amp;filename<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp; ofstream stream ;<br />
&nbsp; &nbsp; stream.<span class="me1">open</span><span class="br0">&#40;</span>filename.<span class="me1">c_str</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; this-&gt;write<span class="br0">&#40;</span>&amp;stream<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; stream.<span class="me1">close</span><span class="br0">&#40;</span><span class="br0">&#41;</span> ;<br />
<span class="br0">&#125;</span></div>
<p>I run the unit tests, and make sure they all pass.</p>
<p>Now I'm ready to mock the file output. I change the <code>ofstream</code> in my unit test to an <code>ostringstream</code>:</p>
<div class="dean_ch" style="white-space: wrap;">
TEST<span class="br0">&#40;</span> TestConfigWriter, write_stream <span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp; ConfigWriter writer ;<br />
&nbsp; &nbsp; writer.<span class="me1">set_prop</span><span class="br0">&#40;</span><span class="st0">&quot;files&quot;</span>, <span class="st0">&quot;3&quot;</span><span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; writer.<span class="me1">set_prop</span><span class="br0">&#40;</span><span class="st0">&quot;drives&quot;</span>, <span class="st0">&quot;1&quot;</span><span class="br0">&#41;</span> ;</p>
<p>&nbsp; &nbsp; ostringstream stream ;<br />
&nbsp; &nbsp; writer.<span class="me1">write</span><span class="br0">&#40;</span>&amp;stream<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; <span class="kw4">string</span> expected = <span class="st0">&quot;files=3<span class="es0">\r</span><span class="es0">\n</span>drives=1&quot;</span> ;<br />
&nbsp; &nbsp; <span class="co1">// look ma, we didn't touch the file system!</span><br />
&nbsp; &nbsp; <span class="kw4">string</span> actual = stream.<span class="me1">str</span><span class="br0">&#40;</span><span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; ASSERT_EQUALS_V<span class="br0">&#40;</span>expected, actual<span class="br0">&#41;</span> ;<br />
<span class="br0">&#125;</span></div>
<p>I run the unit tests again. Now I'm able to unit test the class without touching the file system. I delete the unit test for the <code>write(const string &#038;fname)</code> method.</p>
<p>I'll still have regression and function tests that actually write config files and test their output, but I want my unit tests to run very quickly, without affecting the "outside world."</p>
]]></content:encoded>
			<wfw:commentRss>http://ginstrom.com/scribbles/2008/08/29/mocking-file-output-for-unit-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Aim high</title>
		<link>http://ginstrom.com/scribbles/2007/12/14/aim-high/</link>
		<comments>http://ginstrom.com/scribbles/2007/12/14/aim-high/#comments</comments>
		<pubDate>Fri, 14 Dec 2007 08:30:21 +0000</pubDate>
		<dc:creator>Ryan Ginstrom</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.ginstrom.com/scribbles/2007/12/14/aim-high/</guid>
		<description><![CDATA[Alex Martelli has a great quote on optimization in Python in a Nutshell: Start by designing, coding, and testing your application in Python, using available extension modules if they save you work. This takes much less time than it would with a classic compiled language. Then benchmark the application to find out if the resulting [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Alex_Martelli">Alex Martelli</a> has a great quote on optimization in <a href="http://books.google.co.jp/books?id=6TEcaEzA8N0C">Python in a Nutshell</a>:</p>
<blockquote><p>Start by designing, coding, and testing your application in Python, using available extension modules if they save you work. This takes much less time than it would with a classic compiled language. Then benchmark the application to find out if the resulting code is fast enough. Often it is, and you're done &#8212; congratulations! Ship it!</p>
<p>Since much of Python itself is coded in highly optimized C, as are many of its standard and extension modules, your application may even turn out to be already faster than typical C code. However, if the application is too slow, you need to reexamine your algorithms and data structures. Check for bottlenecks due to application architecture, network traffic, database access, and operating system interactions. For typical applications, each of these factors is more likely than language choice to cause slowdowns. Tinkering with large-scale architectural aspects can often speed up an application dramatically, and Python is an excellent medium for such experimentation.</p>
<p>If your program is still too slow, profile it to find out where the time is going. Applications often exhibit computational bottlenecks: small areas of the source code, often between 10 and 20 percent, which account for 80 percent or more of the running time. Then optimize the bottlenecks&#8230;</p></blockquote>
<p>I write just about all my code in Python first. Then if it's not fast enough, I profile it to find the bottlenecks. First, I try optimizing the algorithms for the bottlenecks. If it's still too slow, I try optimizing the code &#8212; things like hoisting method lookups out of the loop, replacing slower idioms like string concatenation with list joins, etc.</p>
<p>If it's still too slow, I'll rewrite the remaining bottlenecks in a lower-level language. I continue to profile to ensure that I'm speeding up what I think I am.</p>
<p>Even when I have a pretty good idea that I'm going to have to implement a certain function in a lower-level language, I'll still write it in Python first. Having the high-level implementation makes writing the lower-level one a lot easier. Plus the resulting code is likely to be cleaner and have fewer bugs.</p>
<p>As an example, I once wrote a file-parser in Python. It was too slow, so I rewrote some parts of it in C++. Overall, development took me about two days &#8212; a day for the Python, and a day for the C++.</p>
<p>Some time before, I had written a different file parser entirely in C++. The level of complexity was about the same &#8212; but this parser took me about a week to write, and I was finding bugs in it for a couple of months.</p>
<p>The Python-based parser was much more free of bugs; it was also a lot easier to maintain and extend, something that has been of huge value. But the real kicker was that my hybrid Python/C++ parser performed as well or better than the pure-C++ version (it's impossible to compare them directly, because they were parsing different things).</p>
<p>So my motto now is to aim high &#8212; put everything into a high-level language (usually Python in my case), dipping down to lower-level languages only when necessary.</p>
]]></content:encoded>
			<wfw:commentRss>http://ginstrom.com/scribbles/2007/12/14/aim-high/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The past, present, and future of optimization</title>
		<link>http://ginstrom.com/scribbles/2007/12/11/the-past-present-and-future-of-optimization/</link>
		<comments>http://ginstrom.com/scribbles/2007/12/11/the-past-present-and-future-of-optimization/#comments</comments>
		<pubDate>Tue, 11 Dec 2007 14:31:20 +0000</pubDate>
		<dc:creator>Ryan Ginstrom</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.ginstrom.com/scribbles/2007/12/11/the-past-present-and-future-of-optimization/</guid>
		<description><![CDATA[I have a relative ("Dan") who used to earn a living optimizing code in the late 70s and early 80s. Around then, a new-fangled high-level language named "C" was starting to catch on, but companies didn't like all the wasted cycles in C programs due to the under-optimized assembly code that their C compilers were [...]]]></description>
			<content:encoded><![CDATA[<p>I have a relative ("Dan") who used to earn a living optimizing code in the late 70s and early 80s. Around then, a new-fangled high-level language named "C" was starting to catch on, but companies didn't like all the wasted cycles in C programs due to the under-optimized assembly code that their C compilers were writing.</p>
<p>So Dan would go through and hand-optimize the assembly code to get rid of those wasted cycles and squeeze out every possible lick of performance. He earned quite a decent living at it, until the mid 1980s when the work dried up.</p>
<p>Did his work dry up because machines had grown so fast that companies didn't care about wasted cycles anymore? No, they were just as stingy about their computer resources as they used to be. The reason why the work dried up was because the compilers eventually got so good that the amount of tuning Dan could do was no longer worth the cost.</p>
<p>Today, you can write assembly language that's faster than C, but you really have to know what you're doing if you want to gain much speed &#8212; C compilers today are pretty smart. Nowadays, you might drop down to assembly for a really tight loop, where every machine cycle counts, but writing an entire program in assembly is &#8212; shall we say &#8212; no longer mainstream. <img src='http://ginstrom.com/scribbles/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>There's an obvious parallel with Dan's job today: saving machine cycles by rewriting code in very high-level languages like Python and Ruby in faster, lower-level languages.</p>
<p>Certainly, <a href="/scribbles/2007/12/02/extending-python-with-c-a-case-study/">there's still a place for this kind of optimization today</a>. But how long will this still be the general case? It's already true that you have to <a href="http://blogs.msdn.com/oldnewthing/archive/2005/05/19/420038.aspx">know what you're doing</a> to <a href="http://blogs.msdn.com/jonathanh/archive/2005/05/20/optimizing-managed-c-vs-native-c-code.aspx">beat C#</a> or Java with C/C++. Yes, C and C++ are still faster than C# and Java when you know what you're doing. But simply writing in those languages doesn't <em>guarantee</em> that your code'll be faster (and for simplicity's sake, I'll leave out considerations of automatically versus manually managed memory).</p>
<p>When JIT compiling becomes a reality for Python, it might become true for this language as well. Then we might see ever-diminishing returns on rewriting Python code in lower-level languages.</p>
<p>"Bare metal" programming used to mean assembly language &#8212; now it mostly means C. I for one can't wait for the day when "dropping down to the bare metal" means writing Python code!</p>
]]></content:encoded>
			<wfw:commentRss>http://ginstrom.com/scribbles/2007/12/11/the-past-present-and-future-of-optimization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Three reasons to avoid private class members</title>
		<link>http://ginstrom.com/scribbles/2007/11/12/three-reasons-to-avoid-private-class-members/</link>
		<comments>http://ginstrom.com/scribbles/2007/11/12/three-reasons-to-avoid-private-class-members/#comments</comments>
		<pubDate>Mon, 12 Nov 2007 11:24:29 +0000</pubDate>
		<dc:creator>Ryan Ginstrom</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.ginstrom.com/scribbles/2007/11/12/three-reasons-to-avoid-private-class-members/</guid>
		<description><![CDATA[I recently read an interesting post about the need for access control via the private keyword (or an equivalent mechanism) on the CodeThinked blog. The post raises some valid points, but I still think enforced private/protected access is something to be used sparingly at most. Here are three reasons why. Private members are a pain [...]]]></description>
			<content:encoded><![CDATA[<p>I recently read <a href="http://www.codethinked.com/post/2007/11/Your-language-deficiency-is-not-a-feature.aspx">an interesting post about the need for access control</a> via the private keyword (or an equivalent mechanism) on the <a href="http://www.codethinked.com/">CodeThinked blog</a>. The post raises some valid points, but I still think enforced private/protected access is something to be used sparingly at most. Here are three reasons why.</p>
<h3>Private members are a pain to unit test</h3>
<p>Classes with lots of private methods and variables are a pain to unit test. The pathological case is the "iceberg class" &#8212; one public method with a void return, and lots of hidden private members.</p>
<div class="dean_ch" style="white-space: wrap;">
class LogParser<br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp; <span class="kw4">typedef</span> list&lt; <span class="kw4">string</span> &gt;::<span class="me2">iterator</span> token_iterator ;<br />
&nbsp; &nbsp; list&lt; <span class="kw4">string</span> &gt; m_tokens ;<br />
&nbsp; &nbsp; list&lt; <span class="kw4">string</span> &gt; m_parsed_tokens ;<br />
public:<br />
&nbsp; &nbsp; <span class="kw4">void</span> parse_log<span class="br0">&#40;</span><span class="kw4">const</span> tstring &amp;logfile_name,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span class="kw4">const</span> tstring &amp;outfile_name<span class="br0">&#41;</span> ;<br />
private:<br />
&nbsp; &nbsp; <span class="kw4">void</span> write_results<span class="br0">&#40;</span><span class="kw4">const</span> tstring &amp;outfile_name<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; token_iterator tokens_begin<span class="br0">&#40;</span><span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; token_iterator tokens_end<span class="br0">&#40;</span><span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; <span class="kw4">void</span> parse_token<span class="br0">&#40;</span><span class="kw4">const</span> token_iterator &amp;token<span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; <span class="kw4">void</span> tokenize_file<span class="br0">&#40;</span><span class="kw4">const</span> tstring &amp;logfile_name<span class="br0">&#41;</span> ;<br />
<span class="br0">&#125;</span>;</div>
<p>(I know that everybody reading this &#8212; except me &#8212; is much too smart to write a stupid class like this. It's just for demonstration purposes.)</p>
<p>Right now, the only way to test this class is to touch the file system twice &#8212; once to read in a test log file, and another time to check the results. In order to unit test private member functions, and check the state of private member variables (more on these below), you've got to resort to some sort of hackery, such as the infamous #ifndef hack:</p>
<div class="dean_ch" style="white-space: wrap;">
class LogParser<br />
<span class="br0">&#123;</span><br />
&#8230;<br />
&nbsp; &nbsp; <span class="kw4">void</span> parse_log<span class="br0">&#40;</span>&#8230;<span class="br0">&#41;</span> ;<br />
<span class="co2">#ifndef TESTING</span><br />
private:<br />
<span class="co2">#endif</span><br />
&#8230;</div>
<p>Yes, there are other ways, but they all require a little too much intimacy with the test code for my taste.</p>
<h3>Private methods and member variables are a code smell</h3>
<p>Having lots of private methods and members often means that you've got another class (or two) dying to break free and live on its own. In the pathological LogParser example above, we really have three functions: we read and tokenize a log file, parse the tokens, then write our results to another file.</p>
<p>Having those private methods is a big hint that this functionality doesn't really belong on our LogParser class.</p>
<p>How about if we decompose this into three classes:</p>
<div class="dean_ch" style="white-space: wrap;">
class LogTokenizer<br />
<span class="br0">&#123;</span><br />
public:<br />
&nbsp; &nbsp; <span class="kw4">typedef</span> list&lt; <span class="kw4">string</span> &gt;::<span class="me2">iterator</span> token_iterator ;</p>
<p>&nbsp; &nbsp; token_iterator tokens_begin<span class="br0">&#40;</span><span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; token_iterator tokens_end<span class="br0">&#40;</span><span class="br0">&#41;</span> ;<br />
&nbsp; &nbsp; <span class="kw4">void</span> tokenize_file<span class="br0">&#40;</span><span class="kw4">const</span> tstring &amp;logfile_name<span class="br0">&#41;</span> ;<br />
private:<br />
&nbsp; &nbsp; list&lt; <span class="kw4">string</span> &gt; m_tokens ;<br />
<span class="br0">&#125;</span>;</p>
<p>class LogWriter<br />
<span class="br0">&#123;</span><br />
public:<br />
&nbsp; &nbsp; <span class="kw4">void</span> write_token<span class="br0">&#40;</span><span class="kw4">const</span> <span class="kw4">string</span> &amp;token, FileWriter &amp;writer<span class="br0">&#41;</span> ;<br />
<span class="br0">&#125;</span>;</p>
<p>class LogParser<br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp; <span class="kw4">typedef</span> list&lt; <span class="kw4">string</span> &gt;::<span class="me2">iterator</span> token_iterator ;<br />
public:<br />
&nbsp; &nbsp; <span class="kw4">void</span> parse_log<span class="br0">&#40;</span><span class="kw4">const</span> tstring &amp;logfile_name,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span class="kw4">const</span> tstring &amp;outfile_name<span class="br0">&#41;</span> ;<br />
private:<br />
&nbsp; &nbsp; <span class="kw4">void</span> parse_token<span class="br0">&#40;</span><span class="kw4">const</span> token_iterator &amp;token<span class="br0">&#41;</span> ;</p>
<p>&nbsp; &nbsp; list&lt; <span class="kw4">string</span> &gt; m_parsed_tokens ;<br />
<span class="br0">&#125;</span>;</div>
<p>Here, we've got three much more focused classes, with much tighter responsibilities. This code is more reusable &#8212; it would be fairly easy to imagine taking that LogTokenizer and applying it in other situations, for example.</p>
<p>Note that the encapsulation is now better, if anything. Users of our LogParser class still don't have to worry about what's under the hood &#8212; and now they won't even be distracted by as many private member declarations when they browse the header file.</p>
<p>It will also be a lot easier to configure our LogParser to take different input and output sources. As one example, we could change LogParser to take a (smart) pointer to a LogTokenizer instance instead of an input filename, and then configure it with different LogTokenizer subclasses &#8212; including a fake tokenizer that doesn't touch the file system for testing purposes.</p>
<p>If I were to continue to refactor this code, I would expect to end up with almost everything public.</p>
<h3>State is evil</h3>
<p>Functional programming teaches that state (in the form of member variables) is evil, because it makes your code more complex and harder to test. No, C++ is not a functional programming language, nor is Java, nor C#, nor Python for that matter. But I think the functional programming style can <a href="http://www.ginstrom.com/scribbles/2007/10/04/classes-considered-overused/">teach us a lot about good programming in these languages</a> as well.</p>
<p>I therefore try to avoid using member variables (which for C++, will probably be <a href="http://www.ginstrom.com/scribbles/2007/09/09/hide-your-privates-but-dont-be-a-prude/">private for reasons touched on here</a>). I generally consider it a problem to have more than about two of them in any given class.</p>
]]></content:encoded>
			<wfw:commentRss>http://ginstrom.com/scribbles/2007/11/12/three-reasons-to-avoid-private-class-members/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How learning Python made me a better C++ programmer</title>
		<link>http://ginstrom.com/scribbles/2007/10/05/learning-python-made-me-a-better-cpp-programmer/</link>
		<comments>http://ginstrom.com/scribbles/2007/10/05/learning-python-made-me-a-better-cpp-programmer/#comments</comments>
		<pubDate>Fri, 05 Oct 2007 05:19:05 +0000</pubDate>
		<dc:creator>Ryan Ginstrom</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.ginstrom.com/scribbles/2007/10/05/learning-python-made-me-a-better-cpp-programmer/</guid>
		<description><![CDATA[This post on the Raganwald blog spurred me to write about something I've been thinking about for a while: how learning Python has made me a better C++ programmer. The short answer is, it convinced me to start using the boost libraries (and the Loki library). I'd seen these libraries before, and thought that they [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://weblog.raganwald.com/2007/10/three-blog-posts-id-love-to-read-and.html">This post on the Raganwald blog</a> spurred me to write about something I've been thinking about for a while: how learning Python has made me a better C++ programmer.</p>
<p>The short answer is, it convinced me to start using the <a href="http://www.boost.org/">boost libraries</a> (and <a href="http://loki-lib.sourceforge.net/">the Loki library</a>). I'd seen these libraries before, and thought that they looked pretty neat, but that most of them looked too esoteric to be really practical.</p>
<p>But that was really a failure of imagination. Learning Python taught me the value of programming at a higher level. Things like using <a href="http://www.boost.org/doc/html/signals.html">boost::signals</a> to break up dependencies;  <a href="http://www.boost.org/libs/bind/bind.html">boost::bind</a> and <a href="http://www.boost.org/doc/html/function.html">boost::function</a> to use functions as first-class objects; <a href="http://www.boost.org/libs/foreach/index.html">boost::foreach</a> to separate iteration from the algorithm; <a href="http://www.boost.org/doc/html/any.html">boost::any</a> for generic data types; and much more.</p>
<p>Kind of ironically, Python also taught me the value of using a <a href="http://en.wikipedia.org/wiki/Functional_programming">functional programming style</a> in C++. I say ironically because Python isn't a functional language (although it supports a functional programming style). It was reading the book <a href="http://gnosis.cx/TPiP/">Text Processing in Python</a> (David Mertz) that showed me the value of this style; then as I got more into <a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD</a>, the value of this style became clearer.</p>
<p>Today, I couldn't imagine not programming at a higher level in C++. My C++ code is now shorter, easier to understand, and has fewer bugs and platform dependencies. But I might have never moved to this new level if Python hadn't shown me the way.</p>
]]></content:encoded>
			<wfw:commentRss>http://ginstrom.com/scribbles/2007/10/05/learning-python-made-me-a-better-cpp-programmer/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Classes considered overused</title>
		<link>http://ginstrom.com/scribbles/2007/10/04/classes-considered-overused/</link>
		<comments>http://ginstrom.com/scribbles/2007/10/04/classes-considered-overused/#comments</comments>
		<pubDate>Thu, 04 Oct 2007 06:11:14 +0000</pubDate>
		<dc:creator>Ryan Ginstrom</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.ginstrom.com/scribbles/2007/10/04/classes-considered-overused/</guid>
		<description><![CDATA[We all love classes. When I write a class, I get a warm and fuzzy feeling, because I know I'm doing OOP. A class represents a bundle of data and behavior. A classic example is a BankAccount class, which maintains a "balance" state and various methods for manipulating and querying the balance. This is a [...]]]></description>
			<content:encoded><![CDATA[<p>We all love classes. When I write a class, I get a warm and fuzzy feeling, because I know I'm doing <a href="http://en.wikipedia.org/wiki/Object-oriented_programming">OOP</a>.</p>
<p>A class represents a bundle of data and behavior. A classic example is a BankAccount class, which maintains a "balance" state and various methods for manipulating and querying the balance.</p>
<p>This is a great concept. It lets us think about our programs at a higher level.</p>
<p><strong>The problem with classes is side effects</strong>. It's a lot harder to test a function when it depends on internal state &#8212; and that's what the "data" part of our <em>data and behavior</em> bundle is. It's harder still when calling the function may twiddle this internal state, which will in turn affect subsequent behavior.</p>
<p>It's easiest to test a function when a given input is guaranteed to produce the same output, no matter when or how many times it's called (i.e. a "<a href="http://en.wikipedia.org/wiki/Pure_function">pure function</a>"). This yields code that's more reliable, more testable, and easier to reuse.</p>
<p>I don't think it's wise to completely forgo classes though, at least in languages like C++ and Python. They make large-scale development a lot easier. But these languages do give us tools for organizing code that the "classes-only" one-trick-pony languages don't &#8212; namespaces in the case of C++, and modules in the case of Python. So we don't have to resort to classes merely to organize related functionality.</p>
<p>Python also gives us functions as first-class objects (and boost does this for us in C++), eliminating another need to use classes: we can pass around functions rather than "command objects". A command object is fine when the command needs to retain state (e.g. for implementing undo/redo), but when a simple function will suffice, use a function.</p>
<p>When I'm developing new functionality, I try to use plain pure functions as much as possible, only using classes when I actually need to wrap state. C++ and Python give us this power, because they don't put us in the class straitjacket.</p>
]]></content:encoded>
			<wfw:commentRss>http://ginstrom.com/scribbles/2007/10/04/classes-considered-overused/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

