Software design, PHP and technologyhttps://createopen.com//
Mon, 23 Nov 2015 17:47:51 +0000Mon, 23 Nov 2015 17:47:51 +0000Jekyll v2.4.0Test Driven Development training course notes<p>A couple of weeks ago <a href="https://twitter.com/tweetingsherry">Chris</a> and I went on a TDD course from <a href="http://www.codemanship.co.uk/tdd.html">Codemanship</a>.</p>
<p>This post is an expansion of some of my notes from the course. As always, suggestions and corrects are welcome (especially as <a href="https://github.com/dave1010/dave1010.github.io">pull requests</a>).</p>
<h2>Schools of TDD</h2>
<p>There are 2 main schools of TDD: Classic style and London style.</p>
<p>Testing is either about collaborations (mock objects), or tests about outcomes (assertions &amp; stubs) - not both. Details of an interaction between collaborators often implies the outcome, so you need to be careful about mixing these.</p>
<h3>Classic style</h3>
<p>Classic style is also known as Chicago or Detroit style and is described best by Beck&#39;s &quot;Test-Driven Development&quot;. This focuses on algorithms and triangulation.</p>
<p>First you start with the simplest test case, then gradually generalize the algorithm by adding more tests. This leads to Classic style being great for evolving algorithms. As the code is refactored, new objects are created.</p>
<h3>London style</h3>
<p>London style is also known as Mockist style. It&#39;s best described by Freeman &amp; Pryce&#39;s &quot;Growing Object Oriented Software Guided By Tests&quot; book (the GOOS book). This focuses on how objects talk to each other.</p>
<p>London style is great for evolving complex systems - as this leads to a design where objects pass messages to each other.</p>
<h2>The TDD cycle</h2>
<h3>Writing tests (red)</h3>
<p>Keep tests as close as possible to the code they&#39;re testing. Keep them in the same package and in the same namespace. Commits that change the behaviour of an object should also contain commits that update the tests. Organise tests to reflect organisation of model code.</p>
<p>Test and model code should be in separate classes but test double classes belong with test code.</p>
<p>Choose test names carefully: they should be self explanatory. Keep tests small. The larger the test is, the more work is required to make it pass. If more work is required to pass a test then the system is in the &quot;red&quot; state for longer.</p>
<p>Start with an assertion, as this is the most important thing, then work backwards to get the object behaviour. Tests should only be asking 1 question, so they have only 1 reason to fail.</p>
<p>When a test fails then it should be obvious what goes wrong. This means the process shouldn&#39;t die or fail to late. The test failure message should point to the exact place where code would need changing to fix it. You should <em>always</em> confirm that the test fails meaningfully first.</p>
<p>Isolate tests so they run independently. One failing test should not break any other test. Tests should be able to be ran in individual processes if required.</p>
<h3>Passing tests (green)</h3>
<p>Code should become more generalized gradually, as it is passing more tests. Don&#39;t generalize on a solution too early.</p>
<p>Practice TDD &quot;as if you mean it&quot;. This means you cannot add more than the simplest code required to pass a test - even if a more generalized solution is obvious.</p>
<h3>Refactoring</h3>
<p>TDD is unsustainable without refactoring. Refactoring must be done continually during the process. Refactoring is unsafe without (passing) tests. Don&#39;t be tempted to refactor if there are any failing tests.</p>
<p>Duplicate code is a <em>clue</em> to an opportunity for abstraction.</p>
<p>Maintain your tests - keep them green. Test code should be refactored too, though they should be more DAMP (Descriptive And Meaningful Phrases) than DRY (Don&#39;t repeat yourself).</p>
<p>Refactoring is mostly about redistributing responsibilities. It is critical for the right object to be responsible for the right behaviour. Once the responsibilities are in the right place, code and behaviour is much easier to test and change.</p>
<h2>Testing</h2>
<p>You&#39;ve finished development of a specific object when there are no more failing tests possible. Once you get to this point it is no longer TDD as it is not driving development. This activity is called &quot;testing&quot; and can be a legitimate thing to do!</p>
<h2>Test doubles</h2>
<p>For an intro to test doubles, have a look at <a href="http://createopen.com/design/php/2014/10/30/designing-through-mocking.html">my notes</a> on Konstantin Kudryashov&#39;s talk &quot;Design how your objects talk through mocking&quot;.</p>
<p>Don&#39;t mix up mocks and stubs. Using both at the same time leads to complexity and tests that are hard to maintain.</p>
<h3>Stubs</h3>
<p>Stubs are for testing data and are used to provide the system under test with the right input.</p>
<p>For example to test an import script, a CSV file stub may always return preset data when its data is queried.</p>
<h3>Mocks (or spies)</h3>
<p>Mocks are for testing interactions between objects. They record interactions between objects and verify methods are called as expected.</p>
<p>For example, an import script should call the method <code>persist()</code> on a mock repository, passing in an entity.</p>
<p>Mocks shouldn&#39;t be overused as it means the implementation will be tied to the test. Mocks for static methods should be avoided. Mocks also shouldn&#39;t be used to make legacy code easier to test: the more you do it, the more it will bake in bad design.</p>
<h2>Good Object Oriented design</h2>
<p>A good object oriented design passes the tests in the simplest way possible. The right objects are doing the right work and objects collaborate where they need to.</p>
<p>You can help model OO design by using a Class Responsibility Collaborator (CRC) model. This is creating a set of index cards with the class name and 2 columns:</p>
<ul>
<li>its responsibilities: what it does (behavior) and what it knows</li>
<li>its collaborators: other classes that it interacts with to fulfill its responsibilities</li>
</ul>
<p>When thge CRC model is complete, you can start writing tests for the object that isn&#39;t told what to do by anything else.</p>
<p>Objects should only perform actions with what they explicitly know about. Objects shouldn&#39;t have to ask for data from other objects. This is basically the <a href="http://en.wikipedia.org/wiki/Law_of_Demeter">Law of Demeter</a>. This means objects should not leak data when not needed. This helps an interface stay narrow.</p>
Tue, 28 Apr 2015 20:15:54 +0000https://createopen.com//tdd/design/2015/04/28/tdd-notes.html
https://createopen.com//tdd/design/2015/04/28/tdd-notes.htmltdddesignBalancing Technical Debt and Clean Code talk at the BCS<p>Last week I gave a <a href="http://www.dorset.bcs.org/events/base-balancing-technical-debt">talk at BCS Dorset</a> about technical debt:</p>
<blockquote>
<p>Balancing technical debt and getting things done is one of the hardest problems we have. When should we write beautiful, elegant, clean code and when should we just hammer away blindly at the keyboard until it&#39;s done? This talk goes in to why this balance is so difficult and covers everything from estimations to refactoring and testing, with a focus on real world web apps.</p>
</blockquote>
<p>This talk was at the BCS (The British Computing Society), so was a bit different from talking at developer user groups (where I&#39;ve spoken before). It&#39;s always interesting giving more subjective talks based more on experience learned than more technical talks that are either right or wrong. The best bit was the Q&amp;A, where there was lots of discussion with other people&#39;s experience of technical debt and architecture in startups, digital agencies and enterprises.</p>
<p>I&#39;ve included the slides below but most of them are visual cues rather than bullet points of information.</p>
<p><iframe src="//www.slideshare.net/slideshow/embed_code/44010632" width="425" height="355" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="border:1px solid #CCC; border-width:1px; margin-bottom:5px; max-width: 100%;" allowfullscreen> </iframe> <div style="margin-bottom:5px"> <strong> <a href="//www.slideshare.net/dave1010uk/balancing-technical-debt-and-clean-code" title="Balancing Technical Debt and Clean Code" target="_blank">Balancing Technical Debt and Clean Code</a> </strong></div></p>
Thu, 05 Feb 2015 07:14:07 +0000https://createopen.com//talk/technical-debt/2015/02/05/balancing-technical-debt.html
https://createopen.com//talk/technical-debt/2015/02/05/balancing-technical-debt.htmltalktechnical-debtHTTP messaging PSR-7 update<p>This is a quick update to my <a href="http://createopen.com/design/php/2014/12/15/psr-7.html">original blog post criticizing mutability in PSR-7</a>.</p>
<p>The original blog post got a fair few tweets and traction on Reddit. More importantly, <a href="https://twitter.com/mwop">Matthew Weier O&#39;Phinney</a>, the lead author of PSR-7, read it and took time to <a href="http://createopen.com/design/php/2014/12/15/psr-7.html#comment-1788691985">respond</a> with valid feedback on mutability vs immutability.</p>
<p>Before I got the chance to respond to Matthew, he <a href="https://groups.google.com/forum/#!msg/php-fig/9gK8vX8iYZ8/5PZ9rx8UvXYJ">posted</a> on the PHP-FIG mailing list mentioning that he&#39;d tried implementing an immutable version of the PSR in <a href="https://github.com/weierophinney/http/tree/feature/immutability">phly/http</a> and it worked really well! </p>
<p>Immutability is (almost) always the best way to design interfaces. I&#39;m please I (and others like <a href="https://twitter.com/everzet">@everzet</a> on Twitter) managed to nudge the PSR in that direction.</p>
<p>The current version of the <a href="https://github.com/php-fig/fig-standards/blob/master/proposed/http-message.md">draft PSR-7 spec</a> is now immutable at it looks like the final version will be too.</p>
<p>Finally, huge thanks to Matthew for not only responding to my feedback but also giving immutability a shot and even defending it on the PHP-FIG mailing list!</p>
Wed, 04 Feb 2015 08:14:07 +0000https://createopen.com//design/php/frameworks/2015/02/04/psr-7-update.html
https://createopen.com//design/php/frameworks/2015/02/04/psr-7-update.htmldesignphpframeworksTraits with interfaces<p>In PHP, Traits can&#39;t implement interfaces. They can, however, include abstract methods. These methods then need to be implemented by the concrete class that implements the trait. This allows a trait to provide some boilerplate implementation that depends on an concrete implementation. This isn&#39;t always a good idea (it&#39;s verging on violating the <a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency Inversion Principle</a> but it&#39;s better than a trait attempting to use a method that has no contract.</p>
<p>Example:</p>
<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp">&lt;?php</span>
<span class="k">trait</span> <span class="nx">LoggerTrait</span>
<span class="p">{</span>
<span class="k">abstract</span> <span class="k">public</span> <span class="k">function</span> <span class="nf">log</span><span class="p">(</span><span class="nv">$level</span><span class="p">,</span> <span class="nv">$message</span><span class="p">,</span> <span class="k">array</span> <span class="nv">$context</span> <span class="o">=</span> <span class="k">array</span><span class="p">());</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">error</span><span class="p">(</span><span class="nv">$message</span><span class="p">,</span> <span class="k">array</span> <span class="nv">$context</span> <span class="o">=</span> <span class="k">array</span><span class="p">())</span>
<span class="p">{</span>
<span class="nv">$this</span><span class="o">-&gt;</span><span class="na">log</span><span class="p">(</span><span class="nx">LogLevel</span><span class="o">::</span><span class="na">ERROR</span><span class="p">,</span> <span class="nv">$message</span><span class="p">,</span> <span class="nv">$context</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></div>
Mon, 15 Dec 2014 21:14:07 +0000https://createopen.com//design/php/2014/12/15/trait-tip.html
https://createopen.com//design/php/2014/12/15/trait-tip.htmldesignphpThoughts on PSR-7<p>PSR-7 contains interfaces for HTTP messages. These are like Symfony Kernel&#39;s Request and Response interfaces. Having these new interfaces would be great for the PHP community but there&#39;s a couple of issues with their current state that I&#39;m not happy with.</p>
<p>One of PSR-7&#39;s goals is &quot;Keep the interfaces as minimal as possible&quot;. I think the current interfaces are not minimal enough.</p>
<h2>Immutability</h2>
<p>Immutability is awesome. It mitigates a whole range of bugs like temporal coupling and can provide thread safety (yes, PHP has threads). Immutability means when an object is created then you can&#39;t modify it. This often reflects real world semantics. For example, you can find out what breed a dog is but you can&#39;t set the breed of a dog (unless you can modify its DNA).</p>
<p>The original PHP DateTime object was mutable but we now have DateTimeImmutable too. Using DateTimeImmutable instead of DateTime makes it much easier to avoid bugs. You need to learn how DateTimeImmutable works differently to DateTime but once you have then the immutability makes code simpler and isn&#39;t difficult to use.</p>
<p>Many of the HTTP messages in PSR-7 have forced mutability. Having mutability as part of the interfaces means every implementation needs to support mutability, otherwise they will start breaking the Liskov Substitution Principle.</p>
<p>Arguments for mutability are that it makes code easier to write. Easy does not mean simple. Developers can learn how to do something that is relatively difficult but an interface that leads to complex design cannot be simplified without. Any difficulty can also be encapsulated at different levels, for example, a request builder.</p>
<p>Mutability also pushes developers towards inheritance to add layers of behaviour. This means you get a long depth-of-inheritance, which is inflexible (eg diamond problem) and very hard to maintain. Immutability pushes developers towards composition (eg via decorators), which is much more flexible and easier to test.</p>
<p>Note: HTTP implementations in projects like ruby and node are mutable. These are obviously successful but that doesn&#39;t mean they&#39;re correct. Mutability is definitely an option but I think immutability is better. </p>
<p>The argument for mutable objects so they can be iteratively build is moot. A mutable RequestBuilder can be used to create an immutable request. Request implementations could even provide mutability as an extra layer if they wanted. </p>
<h2>Being too strict to the spec</h2>
<p>I wasn&#39;t sure about this but I think it&#39;s worth mentioning. It&#39;s not something that&#39;s wrong per se, but could lead to issues. PSR-7 follows the spec very well. It also assumes that all other clients and servers will follow the spec perfectly. </p>
<p>The HTTP spec says that</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">Cache-Control: no-cache
Cache-Control: private
</code></pre></div>
<p>is the same as</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">Cache-Control: no-cache, private
</code></pre></div>
<p>If a request comes in like the former, then should it be transformed into the latter by PHP when proxying the request? What about requests with different case header names? The HTTP spec is explicit in these cases and it makes sense in 99% of cases for PSR-7 to follow this. </p>
<h2>Splitting client and server message interfaces</h2>
<p>As it currently stands, IncomingRequestInterface and OutgoingRequestInterface are separate interfaces, yet they both represent an HTTP request and have the same API. This seems to be due to mutability, so if the request was immutable then perhaps they could be combined.</p>
<h2>Writing and reading from StreamableInterface</h2>
<p>This partly comes down to immutability but is also to do with the Interface Segregation Principle.</p>
<p>A stream can be writable and/or readable. You can&#39;t ask for an interface you can read, nor can you ask for an interface you can write to. In effect, the stream&#39;s API can vary. You can call write() on a read-only stream and it will return false. Having a ReadableStreamInterface and a WritableStreamInterface would allow more flexibility and simpler code. Streams can always implement both interfaces. </p>
Mon, 15 Dec 2014 21:14:07 +0000https://createopen.com//design/php/2014/12/15/psr-7.html
https://createopen.com//design/php/2014/12/15/psr-7.htmldesignphpSingletons: bad. Shared resources in a DIC: good.<h2>Singletons</h2>
<p>The Singleton pattern is when you can only instantiate 1 instance of a class. Realistically the only way to do this in PHP is by controlling object lifetime inside the object itself globally. This is bad as it uses global state (and is why Singleton is often considered an anti pattern).</p>
<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp">&lt;?php</span>
<span class="k">trait</span> <span class="nx">Singleton</span> <span class="p">{</span>
<span class="k">public</span> <span class="k">static</span> <span class="k">function</span> <span class="nf">getInstance</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">static</span> <span class="nv">$instance</span> <span class="o">=</span> <span class="k">null</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="k">null</span> <span class="o">===</span> <span class="nv">$instance</span><span class="p">)</span> <span class="p">{</span>
<span class="nv">$instance</span> <span class="o">=</span> <span class="k">new</span> <span class="k">static</span><span class="p">();</span>
<span class="p">}</span>
<span class="k">return</span> <span class="nv">$instance</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></div>
<h2>Shared resources and services</h2>
<p>Another object (eg a DI container) can decide to only return a single instance of a class if it wants to. It does this by creating it the first time (usually lazily, the first time it is created, rather than ASAP) then sharing that resource by storing it as state in the container.</p>
<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">Container</span> <span class="p">{</span>
<span class="k">private</span> <span class="nv">$instances</span> <span class="o">=</span> <span class="p">[];</span>
<span class="k">private</span> <span class="nv">$factories</span> <span class="o">=</span> <span class="p">[];</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">share</span><span class="p">(</span><span class="nv">$name</span><span class="p">,</span> <span class="nx">Callable</span> <span class="nv">$factory</span><span class="p">)</span>
<span class="p">{</span>
<span class="nv">$this</span><span class="o">-&gt;</span><span class="na">factories</span><span class="p">[</span><span class="nv">$name</span><span class="p">]</span> <span class="o">=</span> <span class="nv">$factory</span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">get</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nb">isset</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">instances</span><span class="p">[</span><span class="nv">$name</span><span class="p">]))</span> <span class="p">{</span>
<span class="nv">$factory</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">factories</span><span class="p">[</span><span class="nv">$name</span><span class="p">];</span>
<span class="nv">$this</span><span class="o">-&gt;</span><span class="na">instances</span><span class="p">[</span><span class="nv">$name</span><span class="p">]</span> <span class="o">=</span> <span class="nv">$factory</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">instances</span><span class="p">[</span><span class="nv">$name</span><span class="p">];</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></div>
<h2>The similarities</h2>
<p>Both patterns reduce the amount of instance creation. This reduces memory usage and time cost. This is especially useful when dealing with external resources (such as file and databases).</p>
<h2>The difference</h2>
<p>Often people confuse the Singleton pattern with a container sharing a resource. You can pretty much guarantee that using a Singleton is a bad idea. Sharing resources, however, is often a good idea.</p>
<p>The difference between the Singleton pattern and a shared resource in a DIC is that the Singleton&#39;s state is global but the DIC&#39;s shared resource is stored in the DIC. The latter is not considered an anti pattern as the DIC is just like any object you can instantiate or mock.</p>
Mon, 15 Dec 2014 07:44:07 +0000https://createopen.com//design/php/solid/2014/12/15/shared-resources-vs-singletons.html
https://createopen.com//design/php/solid/2014/12/15/shared-resources-vs-singletons.htmldesignphpsolidShould I use global variables?<p>Someone <a href="http://www.reddit.com/r/PHP/comments/2lct7y/question_do_you_use_globals_or_not/">posted a question</a> about using global variables on <a href="http://www.reddit.com/r/PHP">r/php</a>, which I answered. Copied here for posterity.</p>
<p>Using global state is technical debt. This means you&#39;re trading off short term wins (mostly writing less boiler plate code) with long term losses. If you get good at writing clean, SOLID code then any short term win from a shortcut is pretty much removed. There are lots of things that influence whether taking on technical debt is a good idea or not (including non-technical reasons), so the only correct answer is &quot;it depends&quot;. </p>
<p>In my experience: <strong>taking on this form of technical debt is virtually never worth it</strong>.</p>
<p>With a global variable you&#39;re doing something like this:</p>
<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">Foo</span> <span class="p">{</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">()</span>
<span class="p">{</span>
<span class="nv">$this</span><span class="o">-&gt;</span><span class="na">db</span> <span class="o">=</span> <span class="nv">$GLOBALS</span><span class="p">[</span><span class="s1">&#39;db&#39;</span><span class="p">];</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="nv">$foo</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Foo</span><span class="p">;</span></code></pre></div>
<p>In this case, <code>$foo</code> has a hidden dependency on <code>$GLOBALS[&#39;db&#39;]</code>. That means from the outside, Foo is much harder to use, test, refactor and extend. Without refactoring, your code will rot whenever you add new features.</p>
<p>Injecting your dependencies into <code>Foo</code> gives you the ability to decouple <code>Foo</code> from its dependencies. This makes testing and refactoring much easier. This can be done in 1 of 2 ways. Injecting a service locator is the first way to decoupling <code>Foo</code>.</p>
<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">Foo</span> <span class="p">{</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nx">ServiceLocator</span> <span class="nv">$serviceLocator</span><span class="p">)</span>
<span class="p">{</span>
<span class="nv">$this</span><span class="o">-&gt;</span><span class="na">db</span> <span class="o">=</span> <span class="nv">$serviceLocator</span><span class="o">-&gt;</span><span class="na">getDb</span><span class="p">();</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">new</span> <span class="nx">Foo</span><span class="p">(</span><span class="nv">$serviceLocator</span><span class="p">);</span></code></pre></div>
<p>A service locator gives you separation between <code>Foo</code>&#39;s dependency on the DB abstraction and the actual DB implementation. The service locator still keeps the dependency hidden inside <code>Foo</code> though, which means <code>Foo</code> is still quite hard to refactor. In fact, if your <code>$serviceLocator</code> itself is in the global scope, it&#39;s almost the same as injecting <code>$GLOBALS</code> into <code>Foo</code> (which isn&#39;t great):</p>
<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">Foo</span> <span class="p">{</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="k">array</span> <span class="o">&amp;</span><span class="nv">$globals</span><span class="p">)</span>
<span class="p">{</span>
<span class="nv">$this</span><span class="o">-&gt;</span><span class="na">db</span> <span class="o">=</span> <span class="nv">$globals</span><span class="p">[</span><span class="s1">&#39;db&#39;</span><span class="p">];</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">new</span> <span class="nx">Foo</span><span class="p">(</span><span class="nv">$GLOBALS</span><span class="p">);</span></code></pre></div>
<p>The best thing to do is to inject the actual dependencies into <code>Foo</code>. This means you can follow the <a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency Inversion Principle</a> (the D in <a href="http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29">SOLID</a>).</p>
<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">Foo</span> <span class="p">{</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nx">Connection</span> <span class="nv">$db</span><span class="p">)</span>
<span class="p">{</span>
<span class="nv">$this</span><span class="o">-&gt;</span><span class="na">db</span> <span class="o">=</span> <span class="nv">$db</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">new</span> <span class="nx">Foo</span><span class="p">(</span><span class="nv">$db</span><span class="p">);</span></code></pre></div>
<p>If by doing this you&#39;re thinking &quot;hey, that means I have to inject $db into hundreds of places&quot; then your code is already relying on dependencies all over the places. This means you should (to speed up development and improve quality in the long term) refactor classes that depend on the dependencies to define clear responsibilities (the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">S in SOLID</a>).</p>
<p>Note: as with all cases with technical debt vs clean code, there is a trade off. In general, your future self will thank you for doing it correctly early on.</p>
Tue, 04 Nov 2014 22:44:07 +0000https://createopen.com//design/php/solid/2014/11/04/should-i-use-globals.html
https://createopen.com//design/php/solid/2014/11/04/should-i-use-globals.htmldesignphpsolidNotes on designing through mocking<p>My notes on Everzet&#39;s talk &quot;Design how your objects talk through mocking&quot; at PHPNW14</p>
<ul>
<li>Everzet&#39;s <a href="http://www.slideshare.net/everzet/design-how-your-objects-talk-through-mocking">Original slide deck</a></li>
<li>Code sample here are using <a href="https://github.com/phpspec/prophecy">Prophecy</a> to create test doubles</li>
</ul>
<h1>Different test doubles: Mocks, stubs, spies, dummies and fakes</h1>
<h2>Dummy</h2>
<ul>
<li>Don&#39;t care about. Passed around for typehinting.</li>
<li>No behaviour</li>
</ul>
<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">Foo</span> <span class="p">{</span> <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nx">Dummy</span> <span class="nv">$dummy</span><span class="p">)</span> <span class="p">{}</span> <span class="p">}</span>
<span class="k">new</span> <span class="nx">Foo</span><span class="p">((</span><span class="k">new</span> <span class="nx">\Prophecy\Prophet</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">prophesize</span><span class="p">(</span><span class="nx">Dumnmy</span><span class="o">::</span><span class="na">class</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">reveal</span><span class="p">());</span></code></pre></div>
<h2>Stub</h2>
<ul>
<li>Has (basic) behaviour but no expectations (i.e. injects input into SUT but never handles output)</li>
<li>Dummy that you call a method on</li>
<li>Promises it will always return the same thing (<code>willReturn()</code>)</li>
<li>Doesn&#39;t have to be called</li>
</ul>
<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp">&lt;?php</span>
<span class="k">function</span> <span class="nf">baz</span><span class="p">(</span><span class="nx">Stub</span> <span class="nv">$stub</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nv">$stub</span><span class="o">-&gt;</span><span class="na">foo</span><span class="p">(</span><span class="mi">123</span><span class="p">)</span> <span class="o">===</span> <span class="s1">&#39;bar&#39;</span><span class="p">;}</span>
<span class="nv">$stub</span> <span class="o">=</span> <span class="p">(</span><span class="k">new</span> <span class="nx">\Prophecy\Prophet</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">prophesize</span><span class="p">(</span><span class="nx">Stub</span><span class="o">::</span><span class="na">class</span><span class="p">);</span>
<span class="nv">$stub</span><span class="o">-&gt;</span><span class="na">foo</span><span class="p">(</span><span class="mi">123</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">wilLReturn</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">);</span>
<span class="nx">baz</span><span class="p">(</span><span class="nv">$stub</span><span class="o">-&gt;</span><span class="na">reveal</span><span class="p">());</span></code></pre></div>
<h2>Mock</h2>
<ul>
<li>Define predictions (<code>shouldBeCalled()</code>), not promises</li>
<li>Verifies input from SUT</li>
</ul>
<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp">&lt;?php</span>
<span class="k">function</span> <span class="nf">foo</span><span class="p">(</span><span class="nx">Mock</span> <span class="nv">$mock</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$mock</span><span class="o">-&gt;</span><span class="na">bar</span><span class="p">(</span><span class="mi">123</span><span class="p">);</span> <span class="p">}</span>
<span class="nv">$prophet</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">\Prophecy\Prophet</span><span class="p">;</span>
<span class="nv">$mock</span> <span class="o">=</span> <span class="nv">$prophet</span><span class="o">-&gt;</span><span class="na">prophesize</span><span class="p">(</span><span class="nx">Mock</span><span class="o">::</span><span class="na">class</span><span class="p">);</span>
<span class="nv">$mock</span><span class="o">-&gt;</span><span class="na">bar</span><span class="p">(</span><span class="mi">123</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">shouldBeCalled</span><span class="p">();</span>
<span class="nx">foo</span><span class="p">(</span><span class="nv">$mock</span><span class="o">-&gt;</span><span class="na">reveal</span><span class="p">());</span>
<span class="nv">$prophet</span><span class="o">-&gt;</span><span class="na">checkPredictions</span><span class="p">();</span></code></pre></div>
<h2>Spy</h2>
<ul>
<li>Records behaviour</li>
<li>Assertions happen aftwerwards (<code>shouldHaveBeenCalled()</code>)</li>
</ul>
<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp">&lt;?php</span>
<span class="k">function</span> <span class="nf">foo</span><span class="p">(</span><span class="nx">Spy</span> <span class="nv">$spy</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$spy</span><span class="o">-&gt;</span><span class="na">bar</span><span class="p">(</span><span class="mi">123</span><span class="p">);</span> <span class="p">}</span>
<span class="nv">$spy</span> <span class="o">=</span> <span class="p">(</span><span class="k">new</span> <span class="nx">\Prophecy\Prophet</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">prophesize</span><span class="p">(</span><span class="nx">Spy</span><span class="o">::</span><span class="na">class</span><span class="p">);</span>
<span class="nx">foo</span><span class="p">(</span><span class="nv">$spy</span><span class="o">-&gt;</span><span class="na">reveal</span><span class="p">());</span>
<span class="nv">$spy</span><span class="o">-&gt;</span><span class="na">bar</span><span class="p">(</span><span class="mi">123</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">shouldHaveBeenCalled</span><span class="p">();</span></code></pre></div>
<h2>Fake</h2>
<ul>
<li>Return data depending on input</li>
<li>Used to simplify a dependency. E.g. web service, DB, repository</li>
<li>Used to isolate SUT</li>
</ul>
<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp">&lt;?php</span>
<span class="k">interface</span> <span class="nx">WebServiceInterface</span> <span class="p">{</span> <span class="k">public</span> <span class="k">function</span> <span class="nf">strtoupper</span><span class="p">(</span><span class="nv">$data</span><span class="p">);</span> <span class="p">}</span>
<span class="k">class</span> <span class="nc">RealWebService</span> <span class="k">implements</span> <span class="nx">WebServiceInterface</span> <span class="p">{</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">strtoupper</span><span class="p">(</span><span class="nv">$data</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nb">file_get_contents</span><span class="p">(</span><span class="s1">&#39;api.com/strtoupper/&#39;</span><span class="o">.</span><span class="nv">$data</span><span class="p">);</span> <span class="p">}</span>
<span class="p">}</span>
<span class="k">class</span> <span class="nc">FakeWebService</span> <span class="k">implements</span> <span class="nx">WebServiceInterface</span> <span class="p">{</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">strtoupper</span><span class="p">(</span><span class="nv">$data</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nb">strtoupper</span><span class="p">(</span><span class="nv">$data</span><span class="p">);</span> <span class="p">}</span>
<span class="p">}</span></code></pre></div>
<h1>How mocking helps you follow SOLID principles</h1>
<ul>
<li>lots of mocks means <em>SRP</em> violation. Don&#39;t fake parts of objects: decouple them</li>
<li>Duplication in tests means <em>OCP</em> violation</li>
<li>Refused bequest: when you call a method that you didn&#39;t expect and there&#39;s an interface that covers the method. Means drivers are incompatible.</li>
<li><em>LSP</em>: if objects implement the same interface then they should have the same behaviour. To fix, make a new interface and an adaptor</li>
<li><em>ISP</em> violation. Don&#39;t force objects to have methods that aren&#39;t in a test. If a test doesn&#39;t use a whole interface then split the interface</li>
<li><em>DIP</em>. Don&#39;t mock things you don&#39;t own. Don&#39;t test code you don&#39;t own, that&#39;s an integration test.</li>
</ul>
<h1>Testing outcomes vs testing communication between objects</h1>
<ul>
<li>Exposing outcomes vs exposing communications. Both. Tests usually expose outcomes but communication is important too.</li>
<li>Exposing outcomes forces you to create meaningless getters just for tests</li>
<li>Test outcomes when just 1 object. Test communication when multiple.</li>
<li>Exposing communication creates more objects</li>
<li>Don&#39;t use mocks for isolation, that&#39;s not what they&#39;re for (that&#39;s fakes)</li>
<li>Messaging is more important than state</li>
</ul>
<h2>Summary</h2>
<ul>
<li>TDD based on communication fixes SOLID violations before they happen</li>
</ul>
Thu, 30 Oct 2014 21:44:07 +0000https://createopen.com//design/php/2014/10/30/designing-through-mocking.html
https://createopen.com//design/php/2014/10/30/designing-through-mocking.htmldesignphpStrace<p>Quick strace command that I use all the time to see what files a process is opening:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">strace -f &lt;command&gt; 2&gt;&amp;1 | grep ^open
</code></pre></div>
<p>Really useful to see what config files something is reading (and the order) or to see what PHP (or similar) files are being included.</p>
<p>There’s normally other ways to do this (eg using a debugger) but sending strace’s stderr to stdout and piping through grep is useful in so many cases it’s become a command I use every day or 2.</p>
Sat, 01 Feb 2014 12:24:07 +0000https://createopen.com//linux/2014/02/01/strace.html
https://createopen.com//linux/2014/02/01/strace.htmllinuxConway’s Game of Life in Canvas<p>I haven’t done much with <a href="https://developer.mozilla.org/en-US/docs/HTML/Canvas/Tutorial">Canvas</a>, so I thought I’d experiment by making <a href="http://en.wikipedia.org/wiki/Conway_game">Conway’s Game of Life</a> with a little JavaScript. Conway’s Game of Life is based on a grid of cells, which are either alive or dead. It has 4 simple rules rules:</p>
<ol>
<li>Any live cell with fewer than two live neighbours dies, as if caused by under-population.</li>
<li>Any live cell with two or three live neighbours lives on to the next generation.</li>
<li>Any live cell with more than three live neighbours dies, as if by overcrowding.</li>
<li>Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction</li>
</ol>
<p>These simple rules allow anything to be created. For example:</p>
<p><img src="http://upload.wikimedia.org/wikipedia/commons/e/e5/Gospers_glider_gun.gif" alt="Gliders"></p>
<p>Gliders in Conway’s Game of Life (from Wikipedia)</p>
<p>You can see the code on <a href="https://github.com/dave1010/conway-canvas/blob/master/conway.js">GitHub</a>. It’s very basic but works OK and isn’t too bad for a couple of hours whilst watching TV (it may eat up your CPU a little, sorry). Pull requests, ideas and suggestions welcome.</p>
<p>You can see it in action in the header of this blog. If you move your mouse over it then it will leave a trail of blocks. Clicking on the canvas will add lots of random cells.</p>
Sun, 27 Jan 2013 18:14:07 +0000https://createopen.com//javascript/2013/01/27/conway.html
https://createopen.com//javascript/2013/01/27/conway.htmljavascript