Last week: Prime Factors
First, I closely followed the steps in the PowerPoint slides, except that I wrote a plain function instead of a class with static method, since this is PHP, not Java:
namespace PrimeFactors; function generate($n) { $primes = []; for ($candidate = 2; $n > 1; $candidate++) { for (;$n % $candidate == 0; $n /= $candidate) { $primes[] = $candidate; } } return $primes; }
The next time, I tried an object oriented approach (obviously, putting the function into a class does not make it object oriented) and also used yield
to get rid of the temporary variable $primes
.
class Number { private $n; public function __construct(int $n) { $this->n = $n; } public function primeFactors() : array { return iterator_to_array($this->primeFactorsGenerator($this->n)); } private function primeFactorsGenerator(int $n) : Generator { for ($candidate = 2; $n > 1; $candidate++) { for (; $n % $candidate == 0; $n /= $candidate) { yield $candidate; } } } }
I used this Kata to finally try out Behat. These are the first scenarios in my feature file:
Feature: Generate In order to calculate prime factors As a user of the library I want to retrieve the prime factors for a given number Scenario: Calculate prime factors of two Given I want to find all the prime factors for "2" When I calculate the prime factors Then I should be informed that the prime factors are "2" Scenario: Calculate prime factors of three Given I want to find all the prime factors for "3" When I calculate the prime factors Then I should be informed that the prime factors are "3" Scenario: Calculate prime factors of four Given I want to find all the prime factors for "4" When I calculate the prime factors Then I should be informed that the prime factors are "2,2"
I found this Gherkins syntax quite verbose for such a low level test, and it’s probably not made for that anyway. I understand Behat as a framework to write specifications on a business level that can be translated into tests.
“Calculate prime factors” is not a typical end user requirement, but well, it was still a good one to get started with Behat. The PhpStorm integration is also decent. I am looking forward to do more with it.
Fourth Kata: Word Wrap
Word Wrap was described by Uncle Bob in the “Craftsman” series. Read it in story form here: http://thecleancoder.blogspot.de/2010/10/craftsman-62-dark-path.html
“Yeah, it’s a simple problem to understand, but it’s oddly difficult to solve. The basic premise is really simple. You write a class called Wrapper, that has a single static function named wrap that takes two arguments, a string, and a column number. The function returns the string, but with line breaks inserted at just the right places to make sure that no line is longer than the column number. You try to break lines at word boundaries.”
My personal goals this week
- Get more familiar with Behat