<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0' version='2.0'><channel><atom:id>tag:blogger.com,1999:blog-1555225496393038136</atom:id><lastBuildDate>Sun, 06 May 2012 18:10:22 +0000</lastBuildDate><category>linux</category><category>exceptions</category><category>drums</category><category>gateway pattern</category><category>composite pattern</category><category>photography software linux ubuntu editing darktable</category><category>playonlinux</category><category>builder pattern</category><category>php</category><category>code smell</category><category>music drums synthesia playonlinux wine midi ubuntu linux</category><category>patterns</category><category>pci dss</category><category>command pattern</category><category>synthesia</category><category>music</category><category>wine</category><category>midi</category><category>testing</category><category>anti-patterns</category><category>legacy code</category><category>factory patten</category><title>An Accidental Engineer</title><description>Software engineering notes from a developer and code reviewer</description><link>http://blog.bywires.com/</link><managingEditor>noreply@blogger.com (Bob McKee)</managingEditor><generator>Blogger</generator><openSearch:totalResults>15</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-2721450163441010582</guid><pubDate>Sat, 08 Oct 2011 17:37:00 +0000</pubDate><atom:updated>2011-10-08T13:37:51.706-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>photography software linux ubuntu editing darktable</category><title>A quick dive into Darktable</title><description>&lt;p&gt;
&lt;em&gt;Full disclosure: I am not a professional photographer or graphic designer.  100% hobbyist.&lt;/em&gt;
&lt;/p&gt;

&lt;p&gt;
That said, I do try a fair amount of applications for photo editing and use a fair amount of the tools they offer for image manipulation.  Consider my thoughts as coming from the perspective of a hobbyist interested in getting great results (by my standards) with a relatively small investment in learning new software.  I'm also use to working with &lt;a href="http://www.adobe.com/products/photoshoplightroom/"&gt;Adobe Lightroom&lt;/a&gt; and have a Canon Digital Rebel XTi.
&lt;/p&gt;

&lt;p&gt;
Over the past year I've switched from being a lifetime Windows user to an Ubuntu user.  Since the switch I've been desperate for good photo editing/management software.  Previously I'd used Lightroom.  I love love love Lightroom.  I had a few options to continue using Lightroom.  I tried going the Windows virtual machine route but I found its responsiveness to be too slow.  I felt like the dual-boot route was too much effort.  File that complain under First-World Problems.  I like my desktop setup and I don't want to reboot my computer just to use one app.  I'm lazy.
&lt;/p&gt;

&lt;p&gt;
Finally, I like to not spend money.  Free software really appeals me.  This lead me to look for Lightroom alternative that would work with Ubuntu and ideally would be free.
&lt;/p&gt;

&lt;p&gt;
The post isn't about my application selection process but I did try &lt;a href="http://rawstudio.org/"&gt;Rawstudio&lt;/a&gt; and &lt;a href="http://rawtherapee.com/"&gt;RawTherapee&lt;/a&gt; before choosing &lt;a href="http://darktable.sourceforge.net/"&gt;Darktable&lt;/a&gt;.  I will say my preference for Darktable was immediate, though there's a few things to know to dive in and get to the "learning by using" part.
&lt;/p&gt;

&lt;h4&gt;Keyboard shortcuts&lt;/h4&gt;

&lt;p&gt;
I like shortcut keys.  If you also like shortcut keys and are use to Lightroom you'll find that some shortcuts are the same but a lot aren't.  If you want to see what the shortcut keys are and even change then to whatever you like here's how:
&lt;/p&gt;

&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://4.bp.blogspot.com/-If6bYn4vKlc/TpB_DaWouZI/AAAAAAAAAD0/zQay5K5MpzM/s1600/shortcuts.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img alt="How to view and modify shortcut keys in Darktable" border="0" height="255" src="http://4.bp.blogspot.com/-If6bYn4vKlc/TpB_DaWouZI/AAAAAAAAAD0/zQay5K5MpzM/s400/shortcuts.png" width="400" /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;
I also work on a laptop with a touchpad.  You have a lot of zooming control with your scroll wheel, but I don't have one.  Without a scroll wheel you need to rely on Alt+1.  Note, if you hit it twice it zooms in twice.  That is not obvious from just seeing the binding on the shortcuts tab.
&lt;/p&gt;

&lt;h4&gt;Plugins&lt;/h4&gt;

&lt;p&gt;
Each type of adjustment you can do to an image is broken into a plugin.  Select a photo and go into Darkroom mode by hitting D.  At the bottom right there is a "more plugins" button.  Hover over the plugin to find out what the plugin means because the icon does not make it obvious at all.  This process annoys me as it takes a fair amount of time just to know what your options are.  Clicking on a plugin will turn the icon background grey indicating that the plugin has been added the the right panel.  It will be under whatever the plugin's default category is.  Clicking the icon twice will turn the icons background red.  This means the plugin has also been added to the "favorite" category in the right panel.  Click a third time to remove the plugin from the right panel.
&lt;/p&gt;

&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://1.bp.blogspot.com/-FAiPQFCo7eg/TpCFbd4tCQI/AAAAAAAAAD8/nW8EAs_JCXE/s1600/plugins.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img alt="How to activate plugins in Darktable" border="0" height="400" src="http://1.bp.blogspot.com/-FAiPQFCo7eg/TpCFbd4tCQI/AAAAAAAAAD8/nW8EAs_JCXE/s400/plugins.png" width="156" /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;
Generally I use a few plugins and I use them a lot.  My preference was to only add those plugins to the panel and make them all my favorites.  This makes it a lot easier to use without having to keep switching between these kinda of poorly defined categories.
&lt;/p&gt;

&lt;h4&gt;Time to play&lt;/h4&gt;

&lt;p&gt;
With my shortcuts ready and plugins out where I can see this its easy to play around and make that transition from Lightroom to Darktable.  Darktable doesn't have all the feautres and the easy of use that Lightoom has, but its still damn good and its free.  I am extremely excited to see how this application will evolve over the next few years.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-2721450163441010582?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2011/10/quick-dive-into-darktable.html</link><author>noreply@blogger.com (Bob McKee)</author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/-If6bYn4vKlc/TpB_DaWouZI/AAAAAAAAAD0/zQay5K5MpzM/s72-c/shortcuts.png' height='72' width='72'/><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-3535505380826939458</guid><pubDate>Tue, 09 Aug 2011 13:15:00 +0000</pubDate><atom:updated>2011-09-03T14:39:32.947-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>pci dss</category><category domain='http://www.blogger.com/atom/ns#'>patterns</category><category domain='http://www.blogger.com/atom/ns#'>builder pattern</category><category domain='http://www.blogger.com/atom/ns#'>factory patten</category><category domain='http://www.blogger.com/atom/ns#'>legacy code</category><title>PCI DSS compliance and spaghetti code, Part 3</title><description>&lt;p&gt;
(Be sure to read &lt;a href="http://blog.bywires.com/2011/02/pci-dss-compliance-and-spaghetti-code.html"&gt;Part 1&lt;/a&gt; and &lt;a href="http://blog.bywires.com/2011/08/pci-dss-compliance-and-spaghetti-code.html"&gt;Part 2&lt;/a&gt; first!)
&lt;/p&gt;

&lt;p&gt;
When writing new code I find its a good idea to start at your integration point and then write that client code, whether just by psuedo-coding or writing some test cases.  For my payment gateway code I need code that takes user input, builds a request from that input, sends that request to the payment gateway, and gets a response back so we can act accordingly.
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
$factory = new RequestFactory();

// get sale builder
$builder = $factory-&gt;buildSaleRequest();

// get credit card, so we can set it
$builder-&gt;withCreditCard() 
    -&gt;setCardType($_POST['cardType'])
    -&gt;setCardNumber($_POST['cardNumber'])
    -&gt;setExpirationDate($_POST['expirationDate']);

// get address, so we can set it
$builder-&gt;withBillingAddress()
    -&gt;setCity($_POST['city'])
    -&gt;setState($_POST['state']);

// send request to payment gateway
$response = $builder-&gt;execute();
&lt;/pre&gt;

&lt;p&gt;
This seems pretty simple.  I have objects to accept my user input which execute the request and get the response.  Marvellous.  Under the hood its slightly less simple if you aren't particularly familiar with the &lt;a href="http://en.wikipedia.org/wiki/Factory_method_pattern"&gt;Factory pattern&lt;/a&gt;, &lt;a href="http://en.wikipedia.org/wiki/Builder_pattern"&gt;Builder pattern&lt;/a&gt;, &lt;a href="http://martinfowler.com/eaaCatalog/gateway.html"&gt;Gateway pattern&lt;/a&gt;, &lt;a href="http://en.wikipedia.org/wiki/Composite_pattern"&gt;Composite pattern&lt;/a&gt;, and &lt;a href="http://en.wikipedia.org/wiki/Visitor_pattern"&gt;Visitor pattern&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
Today I'll start at the surface with our &lt;a href="http://en.wikipedia.org/wiki/Creational_pattern"&gt;creational patterns&lt;/a&gt; being used here, the Factory and Builder pattern.
&lt;/p&gt;

&lt;h4&gt;Factory pattern&lt;/h4&gt;

&lt;p&gt;
&lt;a href="http://en.wikipedia.org/wiki/Factory_method_pattern"&gt;Factories&lt;/a&gt;, like all other creational patterns, create new objects.  At first they are often understood as a way to make its consumer get different &lt;em&gt;types&lt;/em&gt; of object, which is correct, but people fail to see that they are places to return differently configured objects (potentially of the same type) as well.  Factories are &lt;em&gt;the&lt;/em&gt; place to stowaway configuration information.  In Factories the configuration can be centralized, rather than forcing the consumer code to have to repeat configuration each time.  For example:
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
class CarFactory {
    public function create() {
        $car = new Car();
        if($this-&gt;config-&gt;useElectricCars()) {
            $car-&gt;setEngine(new ElectricEngine());
        } else {
            $car-&gt;setEngine(new EnvironmentDestroyingBeastEngine());
        }
        return $car;
    }
}
&lt;/pre&gt;

&lt;p&gt;
We encapsulate the querying of the "config" object into this Factory method so we don't need to have other parts of the system be aware of this "config" or aware of any configuration of this object at all.
&lt;/p&gt;

&lt;p&gt;
In the case of the payment gateway RequestFactory, we'll be grabbing the payment gateway credentials, which get used in each request, and passing them onto the Request object that gets returned for consumption.  This way other code need not worry about where those come from.  We've made that decision and we've encapsulated it in a Factory.
&lt;/p&gt;

&lt;h4&gt;Builder pattern&lt;/h4&gt;

&lt;p&gt;
Most people I've seen learning about the &lt;a href="http://en.wikipedia.org/wiki/Builder_pattern"&gt;Builder pattern&lt;/a&gt; don't really get it for a while.  This was true for myself as well.  We know what it is basically - a class with a bunch of methods you can call to configure an object and then a method to return the newly created and configured object - but don't know when to use it.  A quick look at the pattern summary talks about varying complex creation processes.  Yea, it can do that, but you have good reason to create those Builders even if you need only one implementation now.
&lt;/p&gt;

&lt;p&gt;
Here are a few indicators to help you know when its time to use a Builder.
&lt;/p&gt;

&lt;h5&gt;Indicator #1: Wiring together collaborators in application code&lt;/h5&gt;

&lt;p&gt;
Are you doing this in your application code?  You've written a library to create cars and car parts and everywhere you use this library you're repeating this process...
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
$carPartFactory = new CarPartFactory();
$carFactory = new CarFactory();

$car = $carFactory-&gt;create();

$car-&gt;setEngine($carPartFactory-&gt;createElectricEngine())
    -&gt;setWheels($carPartFactory-&gt;createGoodYearTires(4))
    -&gt;setStereo($carPartFactory-&gt;createBadAssStereo());
&lt;/pre&gt;

&lt;p&gt;    
You're creating more than one factory to wire together collaborators.  Its Builder time, bitches.
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
$carBuilder = new CarBuilder();

$car = $carBuilder-&gt;addElectricEngine()
                  -&gt;addGoodYearTires(4)
                  -&gt;addBadAssStereo()
                  -&gt;build();
&lt;/pre&gt;

&lt;p&gt;
Its easier to use, less duplication, easier to read, &lt;em&gt;and&lt;/em&gt; if you ever need to vary that creation process its already in place.
&lt;/p&gt;

&lt;h5&gt;Indicator #2: Factory method with optional parameters&lt;/h5&gt;

&lt;p&gt;
Optional parameters are terrible.  I think thats a whole post al by itself.  For now, if you find yourself doing this...
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
public function create($first, $last, $middle = '', $prefix = '', $suffix = '')
&lt;/pre&gt;

&lt;p&gt;
...do this instead...
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
$builder-&gt;first($first)
        -&gt;last($last)
        -&gt;middle($middle);
&lt;/pre&gt;

&lt;h5&gt;Builders in Builders&lt;/h5&gt;

&lt;p&gt;
Final note of the day on Builders.  Object chaining can make usage pretty easy.  We get use to returning $this in each method.  Sometimes though we want the Builder to return another Builder which can configure its collaborator.  In this case we return the Builder instead of $this, but its also good to have a method naming convention to let developers know instinctively which they'll get back.
&lt;/p&gt;

&lt;p&gt;
Personally, and I think I picked this up from a book though I can't remember which one, I use "set" or "add", whichever reads best, when I'll be returning $this, and "with" when I'll be returning another Builder.  Sometimes I might even have a "set/add" method and a "with" method for configuring the same option, where the "set/add" just uses default settings and the "with" method lets you dig in, but only if you want to.
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
// using "add"
$builder-&gt;addGoodYearTires();

// using "with"
$builder-&gt;withGoodYearTires() // returns TireBuilder
        -&gt;setFancyRims()      // call TireBuilder methods
        -&gt;setSnowTires();

class CarBuilder {
    public function withGoodYearTires() {
        // keep reference to builder so we can get its "product" 
        // and add it to the Car we're building
        $this-&gt;_tireBuilder = new TireBuilder();
        return $this-&gt;_tireBuilder;
    }
}
&lt;/pre&gt;

&lt;p&gt;
Stay tuned for Part 4...
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-3535505380826939458?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2011/08/pci-dss-compliance-and-spaghetti-code_4387.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-2349366543549687169</guid><pubDate>Tue, 02 Aug 2011 13:00:00 +0000</pubDate><atom:updated>2011-08-09T10:40:43.111-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>music drums synthesia playonlinux wine midi ubuntu linux</category><category domain='http://www.blogger.com/atom/ns#'>linux</category><category domain='http://www.blogger.com/atom/ns#'>playonlinux</category><category domain='http://www.blogger.com/atom/ns#'>midi</category><category domain='http://www.blogger.com/atom/ns#'>music</category><category domain='http://www.blogger.com/atom/ns#'>wine</category><category domain='http://www.blogger.com/atom/ns#'>drums</category><category domain='http://www.blogger.com/atom/ns#'>synthesia</category><title>Guitar Hero-like scrolling music on Ubuntu</title><description>&lt;p&gt;
This year I began to learn to play the drums.  Its been fun but I am not the most dedicated student.  Its a hobby and I slack off a lot, but I really would like to get better.
&lt;/p&gt;

&lt;p&gt;
I first got interested in the drums when I tried them out on Guitar Hero.  It was fun playing with friends and you could play for hours without thinking about it.  You'd see yourself getting better and more comfortable.  You'd notice what got tired or sore after playing for 3 hours so you'd adjust or do some Google-ing and find out how &lt;em&gt;real&lt;/em&gt; drummers do it.
&lt;/p&gt;

&lt;p&gt;
Guitar Hero certainly doesn't have the capacity to teach you like a human teacher could.  It doesn't how the technique you play with, and that's a biggy.  On the other hand, real teachers cost money and scheduled time, which at this point in my life is more than I want to give.  Over the weekend I set out on a hunt for something like Guitar Hero with a few extra requirements.
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Work with a Alesis DM6 electric drum kit&lt;/li&gt;
&lt;li&gt;Runs on Ubuntu&lt;/li&gt;
&lt;li&gt;Can load songs of a format which can be easily found for free online (ex. MIDI)&lt;/li&gt;
&lt;li&gt;Scrolls music vertically (like Guitar Hero)&lt;/li&gt;
&lt;li&gt;Rates your ability to play with the song (like Guitar Hero)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
(Note: I realize some electric kits can be connected to Guitar Hero directly but mine cannot.  It has a USB-out, not MIDI-out.)
&lt;/p&gt;

&lt;h4&gt;Synthesia via PlayOnLinux&lt;/h4&gt;

&lt;p&gt;
My search brought me through a graveyard of abandoned projects but eventually I found &lt;a href="http://synthesiagame.com/"&gt;Synthesia&lt;/a&gt;.  Synthesia, as advertised, is &lt;em&gt;almost&lt;/em&gt; what I want.  Its actually made for learning/practicing piano, but it works off MIDI tracks, so theoretically it can work with other instruments as well.
&lt;/p&gt;

&lt;p&gt;
Synthesia does not have an official Linux version.  There is a forked Linux version, &lt;a href="http://sourceforge.net/projects/linthesia/"&gt;Linthesia&lt;/a&gt;, but it doesn't have a 64-bit version and &lt;a href="http://www.synthesiagame.com/wiki/Linux_version"&gt;Synthesia's wiki noted it was old and missing features&lt;/a&gt;.  For a while I dug through discussion forums talking about how they managed to get Synthesia to work with &lt;a href="http://www.winehq.org/"&gt;Wine&lt;/a&gt;, but experiences seemed to vary and honestly I didn't want to dig in that deep.
&lt;/p&gt;

&lt;p&gt;
Luckily I ended up stumbling upon the &lt;a href="http://www.playonlinux.com/"&gt;PlayOnLinux&lt;/a&gt; which, just by chance, &lt;a href="http://www.playonlinux.com/en/commentaires-925.html"&gt;added support for Synthesia two weeks ago&lt;/a&gt;.  PlayOnLinux is a tool which quickly configures Wine for many Windows games and applications.  I followed the Natty &lt;a href="http://www.playonlinux.com/en/download.html"&gt;installation instructions&lt;/a&gt; and got PlayOnLinux installed without any issue.  I then followed &lt;a href="http://www.playonlinux.com/en/manual.html"&gt;these instructions&lt;/a&gt; to install a PlayOnLinux application, in this case Synthesia.  Lastly, I tweaked the Wine settings through PlayOnLinux to have Synthesia run in "windowed" mode by following &lt;a href="http://www.synthesiagame.com/wiki/Resources_Manual#Linux_version"&gt;these instructions&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
From here Synthesia worked immediately with my wife's MIDI keyboard.  Some articles suggest installing &lt;a href="http://timidity.sourceforge.net/"&gt;Timidity&lt;/a&gt;, which may be necessary in some use cases but not for mine.  I simply had the keyboard input set to the MIDI keyboard, and the output also set to the MIDI keyboard.  I had installed Timidity but it didn't seem to be necessary and it crashed once for me so I removed it.
&lt;/p&gt;

&lt;h4&gt;Is that it for drumming with Synthesia?&lt;/h4&gt;

&lt;p&gt;
No.
&lt;/p&gt;

&lt;p&gt;
This is where I've left off.  Synthesia registers my drum hits and can output to my drum kit.  I tried downloading MIDI files with percussion tracks and tried playing a long.  None of my hits seemed to match the drums Synthesia wanted me to hit.  I believe this is a MIDI note mapping mismatch.  For example, my snare drum produces note 38, says &lt;a href="http://alsamodular.sourceforge.net/"&gt;QMidiRoute&lt;/a&gt;.  I suspect the MIDI track I was playing to did not have the snare drum sound as being note 38.  Overall I'm not really familiar with MIDI at all so this could be a completely ignorant assessment but for now its what I'm working on.  When/If I find a good solution I will post it.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-2349366543549687169?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2011/08/guitar-hero-like-scrolling-music-on_02.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-57053576826187398</guid><pubDate>Mon, 01 Aug 2011 13:19:00 +0000</pubDate><atom:updated>2011-09-03T14:29:35.948-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>pci dss</category><category domain='http://www.blogger.com/atom/ns#'>gateway pattern</category><category domain='http://www.blogger.com/atom/ns#'>patterns</category><category domain='http://www.blogger.com/atom/ns#'>composite pattern</category><category domain='http://www.blogger.com/atom/ns#'>legacy code</category><title>PCI DSS compliance and spaghetti code, Part 2</title><description>&lt;p&gt;
(Be sure to read &lt;a href="http://blog.bywires.com/2011/02/pci-dss-compliance-and-spaghetti-code.html"&gt;Part 1&lt;/a&gt; first!)
&lt;/p&gt;

&lt;p&gt;
The first iteration of my &lt;a href="http://en.wikipedia.org/wiki/Command_pattern"&gt;Command objects&lt;/a&gt; could continue to use our existing &lt;a href="http://en.wikipedia.org/wiki/Payment_gateway"&gt;payment gateway&lt;/a&gt; code, but this would not be acceptable by the end of this project.  This old payment gateway code relied heavily on &lt;a href="http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/"&gt;global state&lt;/a&gt; to get configuration options and it executed database queries.  If that were allowed the database servers which our CDE web server accessed would also be subject to audit.  On top of that this code was poorly structured and lacked much of the functionality needed to complete the project.
&lt;/p&gt;

&lt;p&gt;
Completely replacing a fairly large chunk of code is often a bad choice, but we had a mound of reasons for making the move.
&lt;/p&gt;

&lt;h4&gt;Structuring payment gateway code&lt;/h4&gt;

&lt;p&gt;
I worked on this project in parallel with one other teammate, Xiao.  While I was tearing through legacy code and building command objects Xiao, wrote all of the new payment gateway code I'm about to describe.  I helped him with up-front architecture consulting, code review throughout the development process, and some pieces of refactoring.
&lt;/p&gt;

&lt;p&gt;
Each payment gateway we needed to support had a name-value-pair API (&lt;a href="https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&amp;content_ID=developer/e_howto_api_NVPAPIBasics"&gt;such as PayPal's&lt;/a&gt;) or an XML API (&lt;a href="http://www.authorize.net/support/ARB_guide.pdf"&gt;such as Authorize.net's&lt;/a&gt;).  The data used to create each request was usually a combination of several complex objects: merchant account information, name information, addresses, "payment profile" information, etc.  These objects created a &lt;a href="http://en.wikipedia.org/wiki/Composite_pattern"&gt;Composite pattern&lt;/a&gt;.  We used a &lt;a href="http://en.wikipedia.org/wiki/Visitor_pattern"&gt;Visitor pattern&lt;/a&gt; to descend into the Composite and build our final object in the format in which it would be send to the payment gateway.
&lt;/p&gt;

&lt;p&gt;
This might seem counterintuitive because the structure we area creating didn't match their API structure at all.  For example, an API that used name-value pairs might include an address.  This address wouldn't be a separate structure that, as a whole, is part of our name-value pairs.  The address parts (city, state, zip, etc) would be individually mixed up with name, credit card number, expiration date, and so on, because the name-value pair structure is completely flat.
&lt;/p&gt;

&lt;p&gt;
The benefit to having a composite structure with strong typing is that it makes it impossible to make an invalid request.  Each structure, like the address, has a set of fields you can define.  Every place an address can be added, its specified by type.  Passing an object of the wrong type causes an error instantly - do not pass GO, do not collect $200.  This kind of defensiveness seems pretty important for a system as critical as this one (one that receives money).
&lt;/p&gt;

&lt;p&gt;
Continue to &lt;a href="http://blog.bywires.com/2011/08/pci-dss-compliance-and-spaghetti-code_4387.html"&gt;Part 3&lt;/a&gt;!
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-57053576826187398?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2011/08/pci-dss-compliance-and-spaghetti-code_01.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-8572287193148360270</guid><pubDate>Thu, 10 Feb 2011 22:43:00 +0000</pubDate><atom:updated>2011-09-03T14:29:49.526-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>pci dss</category><category domain='http://www.blogger.com/atom/ns#'>patterns</category><category domain='http://www.blogger.com/atom/ns#'>command pattern</category><category domain='http://www.blogger.com/atom/ns#'>legacy code</category><title>PCI DSS compliance and spaghetti code, Part 1</title><description>&lt;p&gt;
Anyone taking a substantial amount of credit card payments will eventually stumble onto the &lt;a href="http://en.wikipedia.org/wiki/Payment_Card_Industry_Data_Security_Standard"&gt;Payment Card Industry Data Security Standard (PCI DSS)&lt;/a&gt;.   Meeting this standard likely adds significant complexity to your application, comes at fairly great expense, and will leave your developers and sysadmins with at least a few head-scratching moments where as they ask themselves "Why do I have to do this?  It has nothing to do with security."  The project I'm working on has been audited, but the final paperwork is not in yet.  Things look good, but pass or fail, there's still plenty to learn from the experience already.
&lt;/p&gt;

&lt;h4&gt;Minimizing the PCI DSS burden&lt;/h4&gt;

&lt;p&gt;
My employer's web application has a fundraising module which needed to become PCI DSS compliant.  There are many things we considered when deciding how to modify our fundraising module.  Here are a few of the larger concerns:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Hardware which handles credit card numbers is subject to audit (these systems combined are called the Cardholder Data Environment, or CDE)&lt;/li&gt;
&lt;li&gt;CDE hardware changes must be documented&lt;/li&gt;
&lt;li&gt;CDE code changes are subject to audit&lt;/li&gt;
&lt;li&gt;CDE code changes must go through a documented security-focused peer review&lt;/li&gt;
&lt;li&gt;Quality testing must be documented for all CDE code changes&lt;/li&gt;
&lt;li&gt;There are restrictions on who is permitted to deploy CDE code&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
As you can see, maintenance to a CDE has lots of extra overhead.  It didn't make sense to add that to overhead anything other than our fundraising module so we decided to separate it from the rest of our application code as well as serving it from its own cluster of web servers.  This solution also reduces the attack surface area of this sensitive part of the application.  
&lt;/p&gt;

&lt;p&gt;
We would obvious have to make some changes that would cost us this extra overhead but we realized we could keep that cost low by reducing the need for change within the CDE code.  To do this we tried to keep the CDE code... well... as dumb as possible.  Our application has many customizable types of fundraising forms used in various workflows, but we don't want the CDE code to know about that.  That stuff is complicated.  It changes, grows, and has a higher bug potential than something smaller and simpler.  All that complexity should continue to live within our original application which the CDE code can communication with via a simple API.  This sounds great, but how do we rip our application in two?
&lt;/p&gt;

&lt;h4&gt;Plotting the course&lt;/h4&gt;

&lt;p&gt;
Segmenting our application this way had huge implications for our existing fundraising code.  The fundraising code had feature after feature piled on over 5 or 6 years.  The user workflow stumbles through a 5000-line top-down PHP file of spaghetti code.  Eventually other "helper" functions and classes might output to browser, redirect, or charge a credit card and then terminated the request with an exit() call.  Eww!  This code was so complex that it was hard to get a good idea of what all of it did.  Without structure or comments it was unreadable and there was no test coverage.
&lt;/p&gt;

&lt;p&gt;
When I first approached this problem I looked at in a very linear way.  This is roughly how I saw the workflow for a basic fundraising page with all valid data submitted and no credit card processor errors:
&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;User opens fundraising page on web server (not a CDE web server)&lt;/li&gt;
&lt;li&gt;User submits form which posts data to CDE web server&lt;/li&gt;
&lt;li&gt;CDE code pulls out credit card number and other sensitive data and validates it&lt;/li&gt;
&lt;li&gt;CDE passes the validation results and non-sensitive data to a validate function on the web server API&lt;/li&gt;
&lt;li&gt;Web server validates the rest of the posted data using some validation extracted from the spaghetti code&lt;/li&gt;
&lt;li&gt;Validation passes so some other extracted code decides to return a "sale command" to the CDE (see &lt;a href="http://en.wikipedia.org/wiki/Command_pattern"&gt;Command Pattern&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;CDE executes the command&lt;/li&gt;
&lt;li&gt;CDE calls web server API telling it the transaction was successful&lt;/li&gt;
&lt;li&gt;Web server uses some extracted code to determine if the user is to be shown a "thank you" message or redirected to a "thank you" page (each of which could be different depending on the workflow the user was executing)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
All this code extraction was going to be a real pain.  The validation and form building was tightly coupled using an old Pear library called &lt;a href="http://pear.php.net/package/HTML_QuickForm"&gt;QuickForm&lt;/a&gt;.  The various user workflows were tangled together and extremely overcomplicated.  Making a few huge tears in the middle of the application seemed high-risk given our relatively short timeline.
&lt;/p&gt;

&lt;h4&gt;A-ha!&lt;/h4&gt;

&lt;p&gt;
I soon realized this wasn't necessary.  I didn't need to do all this extraction.  I didn't need to rip this thing apart with a few huge, dangerous tears.  What I needed to do was encapsulate those end points which triggered the output of data to the user's browser, a user redirect, or charging a user's credit card.  
&lt;/p&gt;

&lt;p&gt;
These encapsulated end points form Command classes which can be serialized and returned to the CDE in an API response.  These commands are simple.  Its not important &lt;em&gt;what kind&lt;/em&gt; of page you are outputting, &lt;em&gt;what kind&lt;/em&gt; of page you're redirecting to, or &lt;em&gt;what kind&lt;/em&gt; of fundraising charge you're doing.  The CDE code doesn't need to know.  The CDE code just know how to handle certain sensitive fields, perform a credit card transaction, and execute these generic commands.  All other decision making is delegated to the web server API.
&lt;/p&gt;

&lt;p&gt;
For our first iteration I created these command classes and took all that structureless top-down spaghetti code and tossed it into a single class method (we'll call this class a Controller).  I extracted global variable usage so their values could be passed in through the Controller's constructor.  I also extracted the validation of the sensitive data and had it run outside the Controller with its results injected into the Controller (as would eventually happen with the validation running on the CDE web server).  I used several legacy code refactoring methods described in one of my favorite programming books, &lt;a hre="http://amzn.com/0131177052"&gt;Working Effectively with Legacy Code&lt;/a&gt;.  These changes produced something I could release immediately.
&lt;/p&gt;

&lt;p&gt;
Continue to &lt;a href="http://blog.bywires.com/2011/08/pci-dss-compliance-and-spaghetti-code.html"&gt;Part 2&lt;/a&gt;!
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-8572287193148360270?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2011/02/pci-dss-compliance-and-spaghetti-code_10.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-2809926609814920215</guid><pubDate>Tue, 31 Aug 2010 03:38:00 +0000</pubDate><atom:updated>2011-08-09T10:40:43.111-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>exceptions</category><title>Exceptions as part of "regular" control flow</title><description>&lt;p&gt;
I've heard this rule a lot: "Never use exception for control flow."  Its an interesting statement to parse.  We know what an exception is, but the definition of control flow is a little fuzzy, so lets clarify things a bit.
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
In computer science, control flow (or alternatively, flow of control) refers to the order in which the individual statements, instructions, or function calls of an imperative or a declarative program are executed or evaluated.
&lt;/p&gt;
&lt;cite&gt;&lt;a href="http://en.wikipedia.org/wiki/Control_flow"&gt;http://en.wikipedia.org/wiki/Control_flow&lt;/a&gt;&lt;/cite&gt;
&lt;/blockquote&gt;

&lt;p&gt;
Immediately I'm confused.  Is it possible to use an exception and not effect control flow?  Nope.  Exceptions &lt;em&gt;are&lt;/em&gt; a means of controlling flow.  Sometimes people making this point specify that its "normal" or "regular" control flow.  "Normal" and "regular" are delightfully relative and unhelpful.  Normal?  Compared to what?  What they're trying to get at is that they don't believe exceptions should be used unless there is an application error.
&lt;/p&gt;

&lt;p&gt;
This seems odd considering that business layer classes aren't necessarily made for only one code path or even one application and therefore lack context to determine the exceptionality of the condition.  I touch on this a bunch in my &lt;a href="/2010/08/exceptions-vs-null.html"&gt;Exceptions vs Null&lt;/a&gt; article.
&lt;/p&gt;

&lt;p&gt;
There are lots of "crazy" things you can do with exceptions and if you're interested in seeing more check out &lt;a href="http://c2.com/cgi/wiki?DontUseExceptionsForFlowControl"&gt;this article&lt;/a&gt; on &lt;a href="http://c2.com/"&gt;c2.com&lt;/a&gt;.  Here I will only be discussing three usages I found particularly interesting.
&lt;/p&gt;

&lt;h4&gt; Exceptions as return values&lt;/h4&gt;

&lt;p&gt;
This example comes from &lt;a href="http://c2.com/"&gt;c2.com&lt;/a&gt;.  I think even people who have never thought deeply about exception usage would never dream up this code.  Still, I believe this might be the perfect example of what people are talking about when they say not to use exceptions for control flow.
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
void search( TreeNode node, Object data ) throws ResultException {
    if (node.data.equals( data ))
        throw new ResultException( node );
    else {
        search( node.leftChild, data );
        search( node.rightChild, data );
    }
}
&lt;/pre&gt;

&lt;p&gt;
Get it now?  As a starting point I think we can all agree that this it batty.  Its a search algorithm that throws an exception upon &lt;em&gt;success&lt;/em&gt;.  Really?  The article correctly points out that this is a violation of the &lt;a href="http://c2.com/cgi/wiki?PrincipleOfLeastAstonishment"&gt;Principle of Least Astonishment&lt;/a&gt;.  I know this code make me feel violated.
&lt;/p&gt;

&lt;h4&gt;Exceptions as commands to the caller&lt;/h4&gt;

&lt;pre name="code" class="brush: php"&gt;
} catch(MyService_Exception_CouldNotBeReached $e) {
    throw new MyOtherService_Exception_Retry("Couldn't reach my service, retry!");
}
&lt;/pre&gt;

&lt;p&gt;
This exception seems to be commanding the caller to retry something.  Like the previous example, this also breaks the &lt;a href="http://c2.com/cgi/wiki?PrincipleOfLeastAstonishment"&gt;Principle of Least Astonishment&lt;/a&gt;.  In order to benefit from the full functionality of the method you need to be setup to catch exception commands that it throws and follow out some other action to continue.  This is a application-agnostic service making application-specific decisions (whether or not to retry).  No thank you.
&lt;/p&gt;

&lt;h4&gt;Exceptions as loop termination conditions&lt;/h4&gt;

&lt;p&gt;
&lt;a href="http://c2.com/"&gt;c2.com&lt;/a&gt; offers us another gem, and I don't mean that negatively.  
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
try {
    for (int i = 0; /*wot no test?*/ ; i++)
        array[i]++;
} catch (ArrayIndexOutOfBoundsException e) {}
&lt;/pre&gt;

&lt;p&gt;
The first thing when I thought when I saw this was "What about things like Python's StopIteration?"  One line later its mentioned.  Yay!  This article may be reading my mind.  I do wonder if the fact that StopIteration exist in &lt;a href="http://docs.python.org/library/exceptions.html#exceptions.StopIteration"&gt;Python&lt;/a&gt;, &lt;a href="http://books.google.com/books?id=jcUbTcr5XWwC&amp;pg=PA138&amp;lpg=PA138&amp;dq=stopiteration+in+ruby&amp;source=bl&amp;ots=fHIjsb4sdD&amp;sig=6TYYoWQX9zw-un9WPZMa4qk-UrA&amp;hl=en&amp;ei=1-N6TOefCIaKlwfT7bSzCg&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=8&amp;ved=0CDsQ6AEwBw#v=onepage&amp;q=stopiteration%20in%20ruby&amp;f=false"&gt;Ruby&lt;/a&gt;, and &lt;a href="https://developer.mozilla.org/en/JavaScript/Guide/Iterators_and_Generators"&gt;Javascript&lt;/a&gt; now might start to carve away at &lt;a href="http://www.blogger.com/2010/08/exceptions-vs-null.html"&gt;exception/null failure/absence debate&lt;/a&gt;.  I'd like to know more about the decision making that went into the the design of feature but so far have failed to find any discussions on the matter.
&lt;/p&gt;

&lt;p&gt;
All that said, I'm not sure how I feel about the name - "stop" iteration.  Sounds like the service commanding its caller. If I were to use a exception-terminated loop I'd prefer to explicitly specify the exception type rather than using a language generic exception with a name that is a command.  Maybe something like this (which I would not be surprised to find already exists somewhere):
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
until(RecordNotFoundException $e) {
    print $recordSet-&gt;getNext()-&gt;getLabel() . "\n";
}
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-2809926609814920215?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2010/08/exceptions-as-part-of-control-flow.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-7325892999115037252</guid><pubDate>Wed, 25 Aug 2010 03:10:00 +0000</pubDate><atom:updated>2011-08-09T10:40:43.112-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>anti-patterns</category><category domain='http://www.blogger.com/atom/ns#'>exceptions</category><title>Categorizing exceptions: Subtypes vs Error codes</title><description>&lt;p&gt;
Today's problematic pattern:  Catching a single, usually per-package, exception and then using an associated error code in a conditional statement to determine what else to do.  I've seen several colleague programmers do it and they never seemed to think about doing it any other way.  Its an oddly unconscious decision.
&lt;/p&gt;

&lt;p&gt;
Consider the following code:
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
try {
    $http-&gt;get('/~bob');
    // do something
} catch (Http_Exception $e) {
    if($e-&gt;getCode() == 404) {
        // do something else
    }
}
&lt;/pre&gt;

&lt;p&gt;
When you use things like well-established HTTP status codes this almost seems reasonable.  It gets a little weirder when you're talking about some internal code defined in some package no one knows anything about.  Take this bank account withdrawal example:
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
try {
    $customerBankAccount-&gt;withdraw(100);
} catch (CustomerBankAccount_Exception $e) {
    if($e-&gt;getCode() == 123) {
        // 123 means they overcharged their account, SHIT!
    }
}
&lt;/pre&gt;

&lt;p&gt;
My problem with this is that we're using two tools for a single purpose.  What is the purpose of an Exception subtype, Http_Exception or CustomerBankAccount_Exception, in these examples?  Exception type categorization.  What is the purpose of an exception code in these examples?  Exception type categorization.  Why are we categorizing the same exception using two different systems?  Additionally, why would caller code be left to interpret magic numbers like 404 or some other constant value a programmer in your office came up with?
&lt;/p&gt;

&lt;p&gt;
It can get worse.  People create their own custom exception error codes with pre-specified ranges like code 100 to 200 are set aside for account balance errors and 200 to 300 are for "the bank spent all your money" -related errors.  Once again, can't exception subtypes be used for this?  The ranges are essentially more API for a developer to remember.
&lt;/p&gt;

&lt;p&gt;
Better example time - GO!
&lt;/p&gt;

&lt;p&gt;
This is more descriptive...
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
} catch (Http_Exception_NotFound $e) {
&lt;/pre&gt;

&lt;p&gt;
Sure, we all know what a 404 is anyway, but what about a 402 or a 203 or a 912 (Glenn Beck Logic Not Found)?  If you're writing this code you're gonna need to figure out what you want to catch.  The next guy reading through it probably doesn't want to figure it out and he'd appreciate it if was just looking at some plain English exception class names.
&lt;/p&gt;

&lt;p&gt;
If you want to catch all those 4xx-class exceptions why not...
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
} catch (Http_Exception_ClientError $e) {
&lt;/pre&gt;

&lt;p&gt;
(The official category of 4xx errors is "Client Error")
&lt;/p&gt;

&lt;p&gt;
I bet a lot of developers see this kind of problem and say "OH SHIT OH SHIT OH SHIT!!! I need to write a one line class with no body at all for like 20 exceptions, that's like 20 lines... OH SHIT OH SHIT OH SHIT!!!"  I never quite get that.  They would rather spend the time writing catch-blocks with if-blocks inside them that each duplicate some evaluation on a magic error code.  It won't take very long for that try/catch/if/else boilerplate nonsense to make those 20 lines of exception definition code look mighty appealing.
&lt;/p&gt;

&lt;h4&gt;Look what I found!&lt;/h4&gt;

&lt;p&gt;
During my research for this post I stumbled upon discussions in many programming language communities about this idea that error codes can be used for exception message translations.  "That sounds interesting," I thought.  I've never considered that use before but as I read through a plan proposed to the &lt;a href="http://framework.zend.com/"&gt;Zend Framework&lt;/a&gt; I quickly began to dismiss the notion.
&lt;/p&gt;

&lt;p&gt;
&lt;a href="http://framework.zend.com/wiki/pages/viewpage.action?pageId=22134"&gt;Thoroughly enjoy this proposal.&lt;/a&gt;
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
Currently, exceptions can only be handled on a per-class basis, or possibly by string comparison against the message.
&lt;/p&gt;

&lt;p&gt;
Instead, we propose that exception codes be used throughout the framework, using a 4-byte hexadecimal format.
&lt;/p&gt;

&lt;p&gt;
This has at least four obvious benefits.
&lt;/p&gt;

&lt;p&gt;
First, it's now possible to distinguish exceptions based on the type of error instead of only by class. This allows users to handle them intelligently.
&lt;/p&gt;

&lt;p&gt;
Second, codes let us do some interesting things with exception handling. Users would now be able to call a method such as:
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
if ($e-&gt;stringTooShort()) { 
    ... 
} 
if ($e-&gt;stringTooShort()) { ... }
&lt;/pre&gt;

&lt;p&gt;
thereby making exception special-casing easy.
&lt;/p&gt;

&lt;p&gt;
Third, this gives us the ability to translate error messages using Zend_Translate (loaded only when an exception occurs) and using separate translation files (for example, .mo format). Not all developers speak English; those that do generally prefer to see exception messages in their native language.
&lt;/p&gt;
&lt;cite&gt;&lt;a href="http://framework.zend.com/wiki/pages/viewpage.action?pageId=22134"&gt;http://framework.zend.com/wiki/pages/viewpage.action?pageId=22134&lt;/a&gt;&lt;/cite&gt;
&lt;/blockquote&gt;

&lt;p&gt;
Who cares about point 4, I'm already gagging.  Even the language irks me a bit.  Just being able to do something doesn't make it "beneficial".  A magical genie could come and grant me my one wish; the ability to shit dead baby seagulls.  Its certainly something I couldn't do before, but is it beneficial?  Maybe.  I really hate baby seagulls.
&lt;/p&gt;

&lt;p&gt;
I don't think I have to re-explain my feelings on Point 1 and 2, but whats the deal with lucky number 3?  Oh, number 3.  If you checked out the article you probably saw that each package in the whole framework has its own error code range preallocated.  Its like preemptive namespacing for codes.  No, it IS namespacing for codes.  Yes, there's already a way to namespace exceptions; the same way we namespace any other class.
&lt;/p&gt;

&lt;p&gt;
If the goal is to be able to translate any exception then we can't really do that with this approach.  Other packages using the same error-code-to-string mapping scheme could overlap in code ranges, so we're at least going to have to catch each different base exception type for each package that has its own defined error code ranges.  Then we're going to have to somehow map those to different translation files.
&lt;/p&gt;

&lt;p&gt;
I'm not saying its necessarily easier to just map class names to exceptions, but I can't imagine it being harder.  This new approach doesn't seem to be solving any problems and its creating a few new ones.
&lt;/p&gt;

&lt;p&gt;
The proposal has tons of user comments.  Some people pushed back.  One user asked why PHP's Exception class took an error code in its constructor at all (a very good question).  One of the proposal's authors answered:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
The error code parameter is intended to be used exactly how we're using it: differentiating exceptions within exception "namespaces" (classes).
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;
Sigh.
&lt;/p&gt;

&lt;p&gt;
Finally, translations are for presentation.  Are these presentation layer exceptions?  No sir, sadly they are not.   We're prepping our business layer exceptions with some data that is meaningless everywhere except the presentation layer assuming the presentation layer knows how to interpret the codes in the first place.
&lt;/p&gt;

&lt;p&gt;
I don't know how to end this.  I'd like to be shown something that throws my conclusions on its head, but from my reading thus far, I'm not seeing it.  Feedback welcome.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-7325892999115037252?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2010/08/categorizing-exceptions-subtypes-vs.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-6635815833546671937</guid><pubDate>Tue, 24 Aug 2010 19:41:00 +0000</pubDate><atom:updated>2011-08-09T10:40:43.112-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>anti-patterns</category><category domain='http://www.blogger.com/atom/ns#'>exceptions</category><title>Exceptions vs Null</title><description>&lt;p&gt;
Plenty of developers agree that returning mixed-type results is not a good practice.  It leads to conditional statements wherever the method returning the result is used.  Everbody agrees thats bad, and then Null walks in, and we're not sure anymore.
&lt;/p&gt;

&lt;p&gt;
Null is suppose to be magical value which can passed as any type of object and represent "no object".  Usually methods return Null when the thing we want to get is absent, and that absence is considered normal for our particular application.  Maybe the caller asked for a row that doesn't exist in a table or the next line of a file when you've already reached the end.
&lt;/p&gt;

&lt;p&gt;
If the method you are calling may return Null then you must (almost?) always check for Null.  Isn't this why we dislike mixed-type return values?  This is only the beginning of the problem with Null.
&lt;/p&gt;

&lt;p&gt;
Personally, I've chosen this rule: "In OOP never return Null and instead always use exceptions".
&lt;/p&gt;

&lt;h4&gt;Absence vs Failure&lt;/h4&gt;

&lt;p&gt;
Those whom I disagree with seem to draw the line at "absence versus failure".  They interpret the absence of something as being unexceptional and return Null.  The failure to be able to do something within a method call is seen as being exceptional so they throw an exception (or maybe they return some other magic value because they think they're mother-fuckin' David Blane, and by that I mean talentless and insignificant).
&lt;/p&gt;

&lt;p&gt;
This excitingly-named article - &lt;a href="http://barelyenough.org/blog/2007/11/when-to-use-exceptions/"&gt;When To Use Exceptions&lt;/a&gt; - asks one question that seems rather compelling and butts heads with the "absence versus failure" rule:
&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;"Who exactly are [library programmers] to decide that not finding [something] is a non-exceptional event for my application?"&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;
I like everything about that statement including the touch of anger.  Business layer classes, or libraries, shouldn't be making application layer decisions.  Its like a business layer class triggering a fatal error rather than throwing an exception.  I determine whats a fatal error, not the tools I'm using to build with.  I always separate my application layer from my business layer, but until recently never considered determining exceptional conditions as part of that division.
&lt;/p&gt;

&lt;p&gt;
Suppose we had a web app for managing blog entries.  The app chooses a search-engine-friendly /english-words-dashed-together/ URL for the blog post based on the blog post title you entered.  This gives us two obvious times were we want to lookup URLs:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We want to use the URL in a new blog post but need to make sure its not already in use (absence is not exceptional)&lt;/li&gt;
&lt;li&gt;A blog post URL has been requested and we need to find the blog post and serve it (absence is exceptional)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Both of these scenarios could call upon the same method - $blogPostGateway-&gt;getPostByUrl($url).  The exceptionality of this scenario depends on the context within the application, yet, as a business class, this gateway knows (or should know) nothing about the application which it lives in.
&lt;/p&gt;

&lt;p&gt;
This does not mean that a method call lacks any context.  There are still post-conditions for the method even absent an application context.  A method call's post-condition is that it returns a value of a pre-specified type.  If an object of the proper type cannot be returned because of absent data then we have an exceptional case.  We don't need a new tool, Null, to sit in place of that object because we already have a tool to say "I failed!" - an exception.
&lt;/p&gt;

&lt;h4&gt;Null = repetition&lt;/h4&gt;

&lt;p&gt;
Suppose $blogPostGateway-&gt;getPostByUrl($url) does return Null.  Now the caller is left to interpret these magic values.  Should callers be left to duplicate those conditionals everywhere?  That's not good design.
&lt;/p&gt;

&lt;p&gt;
Preferably the "absence scenario" here would be handled on the blog post gateway in a method like $blogPostGateway-&gt;blogPostExists($url) which returns a boolean.  No Null.  No new exceptions necessary.  This decision not to use Null also forces the developer to make the right choice and write these extra methods which check for existence.
&lt;/p&gt;

&lt;h4&gt;Whats the difference, really?&lt;/h4&gt;

&lt;p&gt;
This issue is seen by some as a matter of style.  Exceptions with try/catch blocks seen as being identical to Nulls with if/else blocks.  Is there a difference?  I think so the previously mentioned points are huge, but there are functional differences as well.
&lt;/p&gt;

&lt;p&gt;
Exceptions can be handled immediately, eventually, or allowed to go uncaught and &lt;a href="http://www.martinfowler.com/ieeeSoftware/failFast.pdf"&gt;fail fast&lt;/a&gt;.  Null values may not cause problem until much later in a program's execution.  That means cryptic error messages and more tracing to get back to where the Null originated.
&lt;/p&gt;

&lt;h4&gt;Is there anyone else who knows a lot about Null that doesn't like Null?&lt;/h4&gt;

&lt;p&gt;
It seems the &lt;a href="http://qconlondon.com/london-2009/presentation/Null+References:+The+Billion+Dollar+Mistake"&gt;guy who invented it&lt;/a&gt; calls it his &lt;a href="http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare"&gt;"Billion Dollar Mistake"&lt;/a&gt;.
&lt;/p&gt;

&lt;h4&gt;Summary&lt;/h4&gt;

&lt;p&gt;
Don't use Null. Don't.  Do not.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-6635815833546671937?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2010/08/exceptions-vs-null_24.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-2212043715490147806</guid><pubDate>Thu, 29 Jul 2010 23:56:00 +0000</pubDate><atom:updated>2011-08-09T10:40:43.112-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>testing</category><category domain='http://www.blogger.com/atom/ns#'>php</category><title>Testing with string objects in PHP</title><description>&lt;p&gt;
As shown in the last post there are benefits to instantiating the class under test in setUp().  With objects its simple to create them and maintain reference to them so you can change them, but what about things like strings?  Unlike in many other modern languages, strings are not objects in PHP.  They are not passed by reference.  The good news is while strings are not objects, objects can be stings.
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
class String {
    public function set($str) {
        $this-&gt;_str = $str;
    }
    public function __toString() {
        return $this-&gt;_str;
    }
}
&lt;/pre&gt;

&lt;p&gt;
This class can be used as a string.  It can work in PHP's string functions and any other place a string is desired.  So pass this to the class you're testing and then change it later.  It works all the same.
&lt;/p&gt;

&lt;p&gt;
Its important to note that if you are using these in your test setUp() that you can't do work using that string object during the construction process of the class under test.  Initially this slipped my mind as its part of my standard practices.  I believe you should &lt;a href="http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/"&gt;never do any work in your constructor at all&lt;/a&gt;.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-2212043715490147806?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2010/07/testing-with-string-objects-in-php_29.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-1434499734907419114</guid><pubDate>Thu, 29 Jul 2010 23:10:00 +0000</pubDate><atom:updated>2011-08-09T10:40:43.112-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>testing</category><title>Durable, readable tests</title><description>&lt;p&gt;
Anyone who has written tests is familiar with our friend the setUp() fixture method.  We use setUp() to do all that work that's common across all our tests.  It can be used to reduce repetition within our tests, making them simpler, and more readable.  Unfortunately testing can get a little more complicated when you need to sense behavior through a dependency.  
&lt;/p&gt;

&lt;p&gt;
Take this class below which decides which developer is on-call using a &lt;a href="http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern"&gt;Chain of Responsibility pattern&lt;/a&gt;.
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
class DeveloperOnCall_Bob implements DeveloperOnCall {
    public function getOnCallDeveloper() {
        if($this-&gt;_date-&gt;inRange('2010-07-19', '2010-07-26')) {
            return 'Bob';
        }
        return $this-&gt;_nextLinkInChain-&gt;getOnCallDeveloper();
    }
}
&lt;/pre&gt;

&lt;p&gt;
A lot of people would just load their test methods with mock object declarations and probably end up with something like this:
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
class DeveloperOnCall_BobTest extends TestCase {
    public function testShouldReturnBobWhenHeIsOnCall() {
        $date = new Date('2010-07-21'); // date in range!
        $nextLinkInChain = $this-&gt;getMock('DeveloperOnCall ', 
            array('getDeveloperOnCall'));
        $nextLinkInChain-&gt;expects($this-&gt;never())
            -&gt;method('getDeveloperOnCall');
        $actual = $this-&gt;_getClassUnderTest($date, 
            $nextLinkInChain)-&gt;getDeveloperOnCall();
        $this-&gt;assertEquals('Bob', $actual, 
            'Bob should be on call!');
    }

    public function testShouldNotReturnBobWhenHeIsOnNotCall() {
        $date = new Date('2010-07-30'); // date not in range!
        $nextLinkInChain = $this-&gt;getMock('DeveloperOnCall ', 
            array('getDeveloperOnCall'));
        $nextLinkInChain-&gt;expects($this-&gt;once())
            -&gt;method('getDeveloperOnCall');
        $actual = $this-&gt;_getClassUnderTest($date, 
            $nextLinkInChain)-&gt;getDeveloperOnCall();
    }
    
    private function _getClassUnderTest(Date $date, 
        DeveloperOnCall $nextLinkInChain) {

        return new DeveloperOnCall_Bob($date, $nextLinkInChain);
    }
}
&lt;/pre&gt;

&lt;p&gt;
How good is this test?  Lots of setup in those test methods.  A bit hard to read.  The two tests are very similar yet given this design its very hard to reuse that  similar code.  If the way those dependencies work changes (as they often do during development) both these tests break and need to be fixed separately.
&lt;/p&gt;

&lt;p&gt;
There is another way though.  Lets configure our dependencies somewhat lazily.   Consider this alternative:
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
class DeveloperOnCall_BobTest extends TestCase {
    public function setUp() {
        $this-&gt;_date =  $this-&gt;getMock('Date', array('inRange')),
        $this-&gt;_nextLinkInChain = $this-&gt;getMock('DeveloperOnCall', 
            array('getDeveloperOnCall')); 

        $this-&gt;_classUnderTest = new DeveloperOnCall_Bob(
            $this-&gt;_date,
            $this-&gt;_nextLinkInChain
        );
    }

    public function testShouldReturnBobWhenHeIsOnCall() {
        $this-&gt;whenDateIs($this-&gt;duringBobsOnCallTime())
            -&gt;theNextLinkShould($this-&gt;neverBeCalled())
            -&gt;andTheDeveloperOnCallShouldBe('Bob');
    }
    
    public function testShouldNotReturnBobWhenHeIsOnNotCall() {
        $this-&gt;whenDateIs($this-&gt;notDuringBobsOnCallTime())
            -&gt;theNextLinkShould($this-&gt;beCalledOnce())
            -&gt;andTheDeveloperOnCallShouldBe('Adam');
    }

    private function whenDateIs($inRange) {
        $this-&gt;_date-&gt;expects($this-&gt;any())
            -&gt;method('inRange')
            -&gt;will($this-&gt;returnValue($inRange));
        return $this;
    }

    private duringBobsOnCallTime() {
        return true;
    }

    private notDuringBobsOnCallTime() {
        return false;
    }

    private function theNextLinkShould($expects) {
        $this-&gt;_nextLinkInChain-&gt;expects($expects)
            -&gt;method('getDeveloperOnCall')
            -&gt;will($this-&gt;returnValue('Adam'));
        return $this;
    }

    private neverBeCalled() {
        return $this-&gt;never();
    }

    private beCalledOnce() {
        return $this-&gt;once();
    }

    private function andTheDeveloperOnCallShouldBe($dev) {
        $this-&gt;assertEquals(
            $dev, 
            $this-&gt;_classUnderTest-&gt;getDeveloperOnCall(),
            "Wrong developer is on call!"
        );
    }
}
&lt;/pre&gt;

&lt;p&gt;
This last example may be a but longer than the previous but it seems almost like comparing paragraphs and bullet points in terms of readability.  This test is extremely expressive.  It is clear and to the point.  A person who has never worked with this library can easily see the author's intent.  
&lt;/p&gt;

&lt;p&gt;
Finally, if the dependencies change the code that mocks those dependencies is  only in setUp() and private methods so the test methods themselves will not need to change.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-1434499734907419114?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2010/07/durable-readable-tests_29.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-2624811972667717413</guid><pubDate>Thu, 22 Jul 2010 21:28:00 +0000</pubDate><atom:updated>2011-08-09T10:40:43.112-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>testing</category><category domain='http://www.blogger.com/atom/ns#'>php</category><category domain='http://www.blogger.com/atom/ns#'>legacy code</category><title>Faking PHP functions</title><description>&lt;p&gt;
Usually when I want to fake some kind of functionality provided by PHP, I create a new library that maps all that crazy API stuff baked into PHP to something that makes more sense. Maybe it even uses exceptions rather than -1/0/false/null. Holy shit. I almost never write something that did a straight pass-through - no parameter changes, method signature identical to the underlying function. I'd find myself spending time and thinking a lot about this library I was building. So PHP does it “wrong”, what does “right” look like? This can be a time-consuming exercise, but these kinds of libraries can get reused a lot. Writing tests for what you've done can be a problem as well. One of these problems is the inspiration for this post.
&lt;/p&gt;

&lt;p&gt;
Here's a dumbed-down version of some code I was writing for a MySQL class (Yes, I'm actually writing one of those... in 2010... really!):
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
class Mysql {
    public function execute($query) {
        $result = mysql_query($query);
        if($result === false) {
            if(mysql_errno() === self::LOST_CONNECTION) {
                throw new MysqlLostConnectionException();
            } else {
                throw new MysqlException();
            }
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;
How do I get mysql_errno() to return the code for a lost connection? I should write a class to wrap this MySQL functionality... oh wait... I am. I needed something much simpler. Enter "THE SIMPLEST CLASS EVER!!!"...
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
class PHP_Functions {
    public function __call($phpFunction, $args) {
        return call_user_func_array($phpFunction, $args);
    }
}
&lt;/pre&gt;

&lt;p&gt;
Now we can rewrite the other code by taking the PHP_Functions object in the constructor of our MySQL class and modify two other lines...
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
class Mysql {
    public function execute($query) {
        $result = $this-&gt;_phpFunctions-&gt;mysql_query($query);
        if($result === false) {
            if($this-&gt;_phpFunctions-&gt;mysql_errno() ===
self::LOST_CONNECTION) {
                throw new MysqlLostConnectionException();
            } else {
                throw new MysqlException();
            }
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;
In our tests its now easy to mimic these MySQL error conditions. We just have to mock our PHP_Functions object.
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
/**
 * @expectedException MysqlLostConnectionException
 */
public function testShouldThrowLostConnectionException() {
    $phpFunctions = $this-&gt;getMock('PHP_Functions',
array('mysql_query', 'mysql_errno'));
    $phpFunctions-&gt;expects($this-&gt;any())
        -&gt;method('mysql_query')
        -&gt;will($this-&gt;returnValue(false));
    $phpFunctions-&gt;expects($this-&gt;any())
        -&gt;method('mysql_errno')
        -&gt;will($this-&gt;returnValue(Mysql::LOST_CONNECTION));

    $mysql = new Mysql($phpFunctions);
    $mysql-&gt;execute('SELECT 1');
}
&lt;/pre&gt;

&lt;p&gt;
Generally speaking, if someone shows me a magic method like __call() I find myself unable to reach their heart through their throat but I keep trying. My arms are big and their throats are small. It just doesn't work... I keep “breaking” these people. Anyways, I'm not a fan. I haven't found them to be the least bit useful except for adapting some legacy code (like I am sort of doing in my example) and maybe making a  &lt;a href='http://en.wikipedia.org/wiki/Decorator_pattern'&gt;Decorator&lt;/a&gt; base class if working with code with no type hints (I don't like those systems either).
&lt;/p&gt;

&lt;p&gt;
There are other options in this case if you find yourself more upset about magic methods than I am. You can move calls to the MySQL functions to protected methods and override them in testing to provide mock functionality. I use this trick a lot when getting legacy code under test (&lt;a href='http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052'&gt;See Working Effectively with Legacy Code. Excellent book.&lt;/a&gt;). Write a class like below. Then, for your tests, subclass this, override the methods to provide mock functionality, then run the test on the subclass you created.
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
class Mysql {
    public function execute($query) {
        $result = $this-&gt;_mysql_query($query);
        if($result === false) {
            if($this-&gt;_mysql_errno() === self::LOST_CONNECTION) {
                throw new MysqlLostConnectionException();
            } else {
                throw new MysqlException();
            }
        }
    }

    protected function _mysql_query($query) {
        return mysql_query($query);
    }

    protected function _mysql_errno() {
        return mysql_errno(); 
   }
}
&lt;/pre&gt;

&lt;p&gt;
I had several cases where I needed to mock consecutive calls so it just seemed like &lt;a href="http://www.phpunit.de/"&gt;PHPUnit&lt;/a&gt; was ready to go with that, so I opted for that route. Either approach would work well.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-2624811972667717413?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2010/07/faking-php-functions_22.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-762812627751855040</guid><pubDate>Wed, 21 Jul 2010 12:46:00 +0000</pubDate><atom:updated>2011-08-09T10:40:43.112-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>code smell</category><category domain='http://www.blogger.com/atom/ns#'>anti-patterns</category><title>Code smell: Too many private methods</title><description>&lt;p&gt;
I mentioned this in my last post so I figured I'd add some examples to clarify.  Consider the following code:
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
class Cache {
    public function set($key, $data) {
        if($this-&gt;_useMemcache()) {
            $this-&gt;_setInMemcache($key, $data);
        } elseif($this-&gt;_useFilesystem()) {
            $this-&gt;_setInFilesystem($key, $data);
        } else {
            $this-&gt;_setInMemory($key, $data);
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;
Its part of a class that would be used for caching data.  If you had a view of all the methods on this class there would be groups of similar methods:  those with "memcache" in the name, "filesystem" in the name, and "memory" in the name.  On any given operation when one "memcache" method would be used other "memcache" methods are used with it.  The same would be true for the "filesystem" and "memory" methods.
&lt;/p&gt;

&lt;p&gt;
If this class were around for a while eventually you'd find yourself saying "Damn, I want to reuse this functionality for writing to memcache, but I don't want the whole Cache system."
&lt;/p&gt;

&lt;p&gt;
If this class was built without tests and you ended up with the task to add them you'd be saying "Holy fucking shit of shit, this is fuckin hard to test" in a Lewis Black voice as you wildly shook from side to side.  This is your Minnesota winter (google it).
&lt;/p&gt;

&lt;p&gt;
What we really want is separate classes for caching in memcache, the filesystem, and in memory.  You could probably wire these together using a &lt;a href="http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern"&gt;Chain of Responsibility patttern&lt;/a&gt;.  The Chain of Responsibility essentially lets you create a series of fallbacks.
&lt;/p&gt;

&lt;p&gt;
Client: "I need to cache this data."&lt;br /&gt;
Memcache: "I don't want to cache this data but I know someone who might.  Do you want to cache this data?"&lt;br /&gt;
Filesystem: "I'm watching my show, fuck off.  Memory, get the fuck in here?  Cache this for me."&lt;br /&gt;
Memory: "I have no feeling of self-worth and will grow up to be an unsuccessful empty shell of a man, so I may as well comply.  OK, filesystem, I'll cache it."
&lt;/p&gt;

&lt;p&gt;
Anyways, once you understand the &lt;a href="http://en.wikipedia.org/wiki/Single_responsibility_principle"&gt;Single Responsibility Principle&lt;/a&gt; you'd never write this Cache class in the first place.  Its obviously flawed.  Clear as day.  Sometime you don't find out until you're already coding though.
&lt;/p&gt;

&lt;h4&gt;The less obvious case&lt;/h4&gt;

&lt;p&gt;
About a year and a half ago I was writing a class that could read and write language translations from a excel file.  The class was going to be used to import it into a database or export what was in the database into a spreadsheet.  I already had an interface I used to access translations from other sources so I started implementing it.  I used a 3rd-party library, &lt;a href="http://phpexcel.codeplex.com/"&gt;PHPExcel&lt;/a&gt;, for traversing the grid, reading, and writing.
&lt;/p&gt;

&lt;p&gt;
I was learning PHPExcel's API as I went.  We also had  somewhat complex schema that the spreadsheet needed to fit.  There could be a variable number of columns depending on how many languages were translated, and any number of rows because new strings were always being added or removed.
&lt;/p&gt;

&lt;p&gt;
I got it working but was left with lots of private methods that did what I needed to conveniently on the spreadsheet.  I had a good tool to work with (PHPExcel) but I needed more.  I should have had a class which used PHPExcel but traversed the data in the way I needed.
&lt;/p&gt;

&lt;p&gt;
Since then our translation files have grown and we found that PHPExcel is a memory hog.  Exporting a few hundred (maybe up to a thousand) rows takes several minutes.  I've profiled the code and the problem is PHPExcel (FWIW, I hear there are some newer features in later versions that may fix this).  Unfortunately, if we wanted to replace PHPExcel with a faster library we have to tear apart the class I wrote because its all cooked in there, hiding complexities in private methods.
&lt;/p&gt;

&lt;p&gt;
Had I separated my concerns properly replacing the underlying Excel reader/writer would be simply a matter of writing a new class with the interface needed to work with my translation importer/exporter class.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-762812627751855040?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2010/07/code-smell-too-many-private-methods_21.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-4328604447476358396</guid><pubDate>Tue, 20 Jul 2010 21:43:00 +0000</pubDate><atom:updated>2011-08-09T10:40:43.113-04:00</atom:updated><title>Private visibility in open-source</title><description>&lt;p&gt;
The statement in question: &lt;a href="http://twitter.com/mtabini/status/18867470296"&gt;"Private has absolutely no useful role in open-source code."&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
There's already lots of drawn out discussion about this so I'll keep it short.
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Lots of private methods are bad, but not because of OSS.  Its a code smell that usually means too many responsibilities (thereby violating the &lt;a href="http://en.wikipedia.org/wiki/Single_responsibility_principle"&gt;Single Responsibility Principle&lt;/a&gt;).  If you don't believe me look at the classes in your code base with the most private methods - ugly right?&lt;/li&gt;
&lt;li&gt;Private methods are a good way to keep methods short by dividing up work into small well-described chunks. These well-described methods and can be used in place of more heavy-weight documentation in some, but certainly not all, cases.  I haven't seen any large scale project with perfect documentation, so its important that the code speaks to you.  Self-describing code won't degrade like documentation.  (Excellent examples of this in the book &lt;a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882"&gt;Clean Code&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;Code that relies on the internals of 3rd-party code is fragile.  If the package author changes the internal implementation of a class that you depend on then your shit is going to break.  Technically speaking, of course.  If you want to extend code for other OSS projects use inheritance or a form of delegate to use the underlying package without having to modify it or depend on its internals.&lt;/li&gt;
&lt;li&gt;Plenty of successful programming languages do no have private methods.  It can be done.  It just requires discipline and technical expertise.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
At the end of the day its almost a silly point.  Public or private, when talking about these internal-use-only methods programmers should avoid mucking with them.  What are you trying to get at anyways?  If its something significant it should be extracted into a new class which is in turn made a dependency of the original.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-4328604447476358396?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2010/07/private-visibility-in-open-source_20.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-4712060911326077873</guid><pubDate>Tue, 20 Jul 2010 12:44:00 +0000</pubDate><atom:updated>2011-08-09T10:40:43.113-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>patterns</category><category domain='http://www.blogger.com/atom/ns#'>anti-patterns</category><title>Why I'll never recommend  the "Universal constructor" pattern</title><description>&lt;p&gt;
I read the &lt;a href="http://www.planet-php.net/"&gt;PlanetPHP&lt;/a&gt; feed every day and honestly it usually leaves me scratching my head a bit.  Recently I saw a post referencing the &lt;a href="http://solarphp.com/manual/appendix-standards.constructor"&gt;"universal constructor" pattern&lt;/a&gt; in the PHP framework, &lt;a href="http://solarphp.com/"&gt;Solar&lt;/a&gt;.  I hadn't heard this pattern name before but I've seen the code a million times looking through other people's code (and maybe even my own 3+ years ago).  The people who use it generally think its the best thing ever.  It solves that way-too-many parameters problem.  In my experience, however, it almost always indicates poor design elsewhere.
&lt;/p&gt;

&lt;p&gt;
The pattern is simple.  Constructors take only one parameter ever.  That one parameter contains a hash of option/setting pairs (configuration).  Here's an example of where you might see something like this...
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
$userImporter = new UserImporter(array(
    'enable_deduping' =&gt; true,
    'email_admin_on_failure' =&gt; true,
    'import_batch_size' =&gt; 1000
));
&lt;/pre&gt;

&lt;p&gt;
Code that uses this pattern is notorious for breaking the &lt;a href="http://en.wikipedia.org/wiki/Single_responsibility_principle"&gt;Single Responsibility Principle&lt;/a&gt;.  Breaking this principle leads to tightly coupled, hard-to-test code.  Its fairly obvious problem to catch when you think about it.  If someone showed you a class with a constructor that had maybe a few required parameters then 10 optional ones you'd probably run for the hills.
&lt;/p&gt;

&lt;p&gt;
My example class apparently reads some sort of importable data structure, knows how to interact with the data's destination, dedupes users, breaks work into batches, sends alert emails, and probably nailed Jesus to the cross.
&lt;/p&gt;

&lt;p&gt;
This approach appears to solve one problem: it gets rid of that long optional parameter list which leads to code like so...
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
class UserImport {
    public function __construct($enableDeduping = true, $enableEmailOnFailure = false, $batchSize = 1000) {
        // ...
    }
}

$userImport = new UserImport(
    true,  // default
    false, // default
    2000   // custom setting!
);
&lt;/pre&gt;

&lt;p&gt;
You're repeating defaults all over the place to get to that last optional value.  You can never remember which parameter it is without looking.  Is batch size the 5th or 7th param???  Guess I'll go read the code AGAIN.
&lt;/p&gt;

&lt;p&gt;
We can fix this with a better API.  Unfortunately the the UserImport example I am giving fails at this point.  These parameters shouldn't live together because there are too many responsibilities that correspond to.  Here a slightly modified example that might be a scenario where you'd actually use setters for your optional parameters.
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
class UserImport {
    public function __construct(Framework_DatabaseConnection $databaseConnection) {
        $this-&gt;_databaseConnection = $databaseConnection;
        
        // implements logger interface but does not write logs or actually do anything else.  this is my default logger value.
        $this-&gt;_logger = new Framework_Logger_Null(); 
    }
    
    public function setLogger(Framework_Logger $logger) {
        $this-&gt;_logger = $logger;
    }
}
&lt;/pre&gt;

&lt;p&gt;
In this case rather than having an optional logger in the constructor with  default value I just set the object's logger to the default, a &lt;a href="http://en.wikipedia.org/wiki/Null_Object_pattern"&gt;null object&lt;/a&gt; called Framework_Logger_Null.  If you want to supply a real logger just use out setLogger setter method.
&lt;/p&gt;

&lt;p&gt;
In summary, constructors take required parameters.  Setters take optional parameters.
&lt;/p&gt;

&lt;p&gt;
Next, don't think of using types here.  Can't be done.  You're writing all your validation in PHP.  You could write a base class for that functionality and waste the one chance of inheritance PHP gives you on that.  You could couple your class to some validation library you instantiate statically (using "new") or using static method calls.  Granted you're on the hook here for scalar types anyways in PHP since it does not offer types for integers, strings, and booleans for example.
&lt;/p&gt;

&lt;p&gt;
In a project like Solar you probably always have good documentation that's kept up-to-date, but for your home-grown PHP project that almost never the case.  These things over time always end up with new configuration options added making them even more complex and the documentation more out-of-date.  What I am getting to is - how do you know what options are available?  Manual documentation works but decays over time.  Auto-generated documentation isn't going to help you.  Users could just read the implementation of your class to figure it out (I see this way too much).  Essentially you are hiding how to use your class.  This is true both when you are using these configuration hashes in the constructor and also a method parameter.
&lt;/p&gt;

&lt;p&gt;
The easy way to expose the functionality your classes offer is by exposing that functionality through the public API.
&lt;/p&gt;

&lt;p&gt;
Lastly, although this is on a required symptom of this pattern, I almost never see &lt;a href="http://en.wikipedia.org/wiki/Dependency_injection"&gt;dependency injection&lt;/a&gt; used with this pattern.  People don't want to mix simple configuration settings with dependency management because this pattern is suppose to be all about convenience, and how convenient is it to instantiate all kinds of dependency objects when you're creating this object in some client code?  Not very.  The general solution Universal-constructor people use is to just instantiate dependencies right in the same class, thereby tightly coupling it to those implementations.  There are better ways to handle dependency management but thats another post for another day.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-4712060911326077873?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2010/07/why-i-never-recommend-constructor.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-1555225496393038136.post-3333469092911947706</guid><pubDate>Tue, 20 Jul 2010 02:33:00 +0000</pubDate><atom:updated>2011-08-09T10:40:43.113-04:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>patterns</category><category domain='http://www.blogger.com/atom/ns#'>anti-patterns</category><title>Configurable return types kill puppies</title><description>&lt;p&gt;
Here's some code you could see using &lt;a href="http://phplens.com/lens/adodb/docs-adodb.htm"&gt;PHP's Adodb&lt;/a&gt; library.  The library isn't the point but its demonstrates a pattern I see a fair amount.
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
$oldFetchMode = $conn-&gt;setFetchMode(ADODB_FETCH_ASSOC);
$recordSet = $conn-&gt;execute("SELECT * FROM table");
$objectThatDoesWork-&gt;work($recordSet);
$conn-&gt;setFetchMode($oldFetchMode);
&lt;/pre&gt;

&lt;p&gt;
To me this is a multi-fail.
&lt;/p&gt;

&lt;ol&gt;

&lt;li&gt;If an exception is thrown before the fetch mode is reset it doesn't get reset unless you catch it.  That can add up to a lot of boiler-plate try/catch blocks.&lt;/li&gt;

&lt;li&gt;If the next call to execute() doesn't set the fetch mode first in order to guarantee you get the return type you expect bad things can happen.  I've seen plenty of code that doesn't explicitly set the fetch mode every time and it works... until it doesn't.  Code somewhere else in your system changes the fetch mode.  The error is coming from code that source control tells you hasn't changed recently.  Your tests prove to you that the code works.  Your query logs show you that the query you expected to be run was actually run.  It sends you in the wrong direction every time.&lt;/li&gt;

&lt;li&gt;Setting the fetch mode every time with this long method and verbose constant adds a bunch of boilerplate.&lt;/li&gt;

&lt;li&gt;$objectThatDoesWork-&gt;work() should also have its first parameter be typed or you'll only know something went wrong when it tries to access that first row the wrong way rather than failing immediately.  I'd prefer it to &lt;a href="http://martinfowler.com/ieeeSoftware/failFast.pdf"&gt;fail fast (pdf)&lt;/a&gt;.&lt;/li&gt;

&lt;/ol&gt;

&lt;p&gt;
At first glance it could look flexible and convinient.  You don't need to set the fetch mode ever in theory.  You can just use the default, and that's pretty simple right?  I'd be happy to rip this method out and pretend it never existed, but it does and its scaring the kids.
&lt;/p&gt;

&lt;p&gt;
Luckily, there is actually a easy enough solution to this problem.  Take a look at this rewrite.
&lt;/p&gt;

&lt;pre name="code" class="brush: php"&gt;
$recordSetFactory = $conn-&gt;execute("SELECT * FROM table");
$objectThatDoesWork-&gt;work($recordSetFactory-&gt;asAssoc());
&lt;/pre&gt;

&lt;p&gt;
$recordSetFactory has the underlying record set resource stored privately.  
$recordSetFactory object might have different ways to access the data such as asAssoc(), which would return an iterator where the current row is returned as an associative array.  It could have another that returns an iterator which returns row data with numeric indexes (asList() maybe).  There are plenty of ways to access this data conveniently.
&lt;/p&gt;

&lt;p&gt;
Best of all that configuration is explicitly requested every time.  Its used and it gets thrown away when the object's lifecycle ends.  Done and done.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1555225496393038136-3333469092911947706?l=blog.bywires.com' alt='' /&gt;&lt;/div&gt;</description><link>http://blog.bywires.com/2010/07/configurable-return-types-kill-puppies.html</link><author>noreply@blogger.com (Bob McKee)</author><thr:total>0</thr:total></item></channel></rss>
