<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kamil Talanda on Medium]]></title>
        <description><![CDATA[Stories by Kamil Talanda on Medium]]></description>
        <link>https://medium.com/@ktalanda?source=rss-ef661ac6aed8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m791o06Ii7AwB-3SZOv_Yg.png</url>
            <title>Stories by Kamil Talanda on Medium</title>
            <link>https://medium.com/@ktalanda?source=rss-ef661ac6aed8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 22:18:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ktalanda/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Quality Assurance by Unit testing — TDD in action on Android.]]></title>
            <link>https://medium.com/@ktalanda/quality-assurance-by-unit-testing-tdd-in-action-on-android-2299359477e6?source=rss-ef661ac6aed8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2299359477e6</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Kamil Talanda]]></dc:creator>
            <pubDate>Sun, 21 Jan 2018 03:29:50 GMT</pubDate>
            <atom:updated>2018-01-21T03:29:50.032Z</atom:updated>
            <content:encoded><![CDATA[<p>This post has been created to share my thoughts on testing, with all whom it may concern including future myself.</p><blockquote>All software you write will be tested — if not by you and your team, then by the eventual users — so you might as well plan on testing it thoroughly.</blockquote><blockquote>―<strong> Andrew Hunt, </strong>The Pragmatic Programmer: From Journeyman to Master</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*x8xq5Ycm3QXZhBJR2xkhvA.png" /></figure><h3><strong>Unit definition.</strong></h3><p>Everything we will talk about in this post will be related to Unit Testing, so lets start by defining what the unit is. This term is not objective and people argue what it really means.</p><p>I consider an unit as the smallest piece of code which could be composed with others to create something bigger in the spirit of Divide and Conquer. With that in mind, it is a simple set of instructions, most likely a function, which has clear input and output, or it clearly describes the side effects it is going to cause.</p><p>Following this logic, by unit testing I understand checking all paths, this small chunk of code could produce. Anything beyond I consider as integration test, which also play very important role in the software development, but won’t be topic of this post. Unit testing, according to the Testing Pyramid should be the base of the application and should have the largest coverage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*P-BauNMC6CPPdzSOnxZz8A.png" /><figcaption>Test Pyramid by Martin Fowler <a href="https://martinfowler.com/bliki/TestPyramid.html">https://martinfowler.com/bliki/TestPyramid.html</a>.</figcaption></figure><p>By unit testing we can minimise the number of possible paths that has to be considered. If we have 3 base functions and each has 3 paths to test, the cartesian product will be <strong>3 x 3 x 3 = 27</strong>. If we unit test each one separately we have <strong>3 + 3 + 3 = 9</strong> paths to test, plus some small integration tests between them.</p><h3><strong>Architectural concerns.</strong></h3><p>Second important thing in testing is to make the code… testable. It requires <strong>S</strong>ingle responsibility, being <strong>O</strong>pen-close, <strong>L</strong>iskov substitutive, <strong>I</strong>nterface segregated, inverted in terms of <strong>D</strong>ependencies, so shortly to have clear, decoupled architecture.</p><p>Although, defining a skeleton of the architecture to follow at the beginning is a good idea, it is better not to be closed with the initial diagrams and develop the structure as we go. To ensure the code is testable we could follow TDD, which with some level of caution will drive your architecture to be decoupled and to follow <strong>SOLID</strong> principles.</p><h3>TDD sample on Android</h3><p>To show TDD approach in action I have created a sample project <a href="https://github.com/ktalanda/tic-tac-toe">tic-tac-toe</a>, which is stored on github and can be followed by checking out to particular tags. The solution is heavily inspired by the book Test-Driven Java Development written by Viktor Farcic and‎ Alex Garcia. We will focus on testing the logic, not the view so we will be using only JUnit and Mockito.</p><p>Tic-Tac-Toe is a very simple game, which probably everybody has played as a child. To check out the rules visit <a href="https://en.wikipedia.org/wiki/Tic-tac-toe">https://en.wikipedia.org/wiki/Tic-tac-toe</a>.</p><p>While writing the software we will follow RED-GREEN-REFACTOR flow. First writing some tests, then fixing the code to fulfil that test and refactor if we find it necessary.</p><h4>Init</h4><p>To begin with the project, clone the repository and checkout to the init tag.</p><pre>git clone <a href="https://github.com/ktalanda/tic-tac-toe">https://github.com/ktalanda/tic-tac-toe</a>;<br>git checkout init;</pre><p>At this stage basic MVP structure has been created. Since MVP pattern is not the topic of this post I will assume the reader is familiar with the pattern.</p><p>The state of the game is stored inside of MainPresenter in gameBoardState. It uses FieldType models to represent the state of particular field on game board. gameBoardState is a two-dimension collection representing all fields on game board. MainPresenter provides reloadGameBoard function, which takes new game board state as a parameter, updates current state and reloads the view. Even though MainPresenter was developed in TDD style, tests are in MainPresenterTest class, I will not describe the process, because much more interesting from TDD point of view will be developing the logic behind the game. Following picture shows how application looks like at this stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*kVJUwoltQVam5I9Pyz_9dQ.jpeg" /><figcaption>Application at init tag.</figcaption></figure><p>To run tests you can either do that from Android Studio or by running ./gradlew test. When tests are completed you can see the report under /app/build/reports/tests/testDebugUnitTest, to access it just open index.html in your favourite browser and you will see something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gTB4_bZlplG6zUnwWC37Ow.png" /><figcaption>Test Report at init tag.</figcaption></figure><p>Now, when we have the skeleton of the application already set up, lets define the rules of the game so we can start our TDD journey.</p><ol><li><strong><em>Player swap:</em></strong> There are two players X and O. They have one click per round. Once one player marks a field, control goes to the other.</li><li><strong><em>Field choosing:</em></strong> Player can put his/her sign on the field.</li><li><strong><em>No field overriding</em>:</strong> Players cannot put his/her sign on already taken field.</li><li><strong><em>Win conditions</em>:</strong> When three fields in the same row, column or diagonal are marked by the same player, this player wins. If there are no more empty fields and nobody won it is a draw.</li></ol><p>So having those constrains we can get into implementing the features in TDD style.</p><h4>Player swap</h4><p>First before we start we should allow the user to click the field. We can do it by adding following line to OnCreate method in the Activity.</p><pre>gameBoard.setOnItemClickListener <strong>{ </strong>_, _, position, _ <strong>-&gt; </strong>presenter.clickField(position) <strong>}</strong></pre><p>The action is delegated to clickField method in the Presenter.</p><pre>fun clickField(position: Int) {<br>}</pre><p>Method has no implementation and it is where we begin to write tests in MainPresenterTest. Using Divide and Conquer concept lets separate responsibilities of this function into its own pure functions.</p><p>First responsibility is to change the player.</p><pre>@Test<br>fun givenX_whenNextPlayer_thenReturnO() {<br>    val actual = presenter.nextPlayer(FieldType.X)<br>    Assert.assertEquals(FieldType.O, actual)<br>}</pre><p>Once we have test in place we are in RED state. The simplest implementation to fulfil it would be.</p><pre>fun nextPlayer(player: FieldType) : FieldType = FieldType.X</pre><p>This is how we ended up in GREEN state. This implementation is highly incomplete though, lets get back to RED by adding more constraints.</p><pre>@Test<br>fun givenO_whenNextPlayer_thenReturnX() {<br>    val actual = presenter.nextPlayer(FieldType.O)<br>    Assert.assertEquals(FieldType.X, actual)<br>}</pre><p>To get back to GREEN we need to modify nextPlayer implementation.</p><pre>fun nextPlayer(player: FieldType) : FieldType =<br>    when (player) {<br>        FieldType.O -&gt; FieldType.X<br>        else -&gt; FieldType.X<br>    }</pre><p>We’re almost there just the last test.</p><pre>@Test<br>fun givenNone_whenNextPlayer_thenReturnX() {<br>    val actual = presenter.nextPlayer(FieldType.NONE)<br>    Assert.assertEquals(FieldType.X, actual)<br>}</pre><p>And slight modification to the code</p><pre>fun nextPlayer(player: FieldType) : FieldType =<br>    when (player) {<br>        FieldType.X -&gt; FieldType.O<br>        else -&gt; FieldType.X<br>    }</pre><p>So implementation of the method seem to be completed, now we can get into REFACTOR state before we repeat the loop. Changing the code is perfectly safe because everything is covered by tests, but refactoring the tests is a bit tricky. We have to be very careful doing it.</p><p>In our example lets group all tests according to the method nextPlayer into one method. It would look as following.</p><pre>@Test<br>fun givenNone_whenNextPlayer_thenReturnX() {<br>    Assert.assertEquals(<br>      &quot;X should be next after NONE&quot;, <br>      FieldType.X, presenter.nextPlayer(FieldType.NONE))<br>    Assert.assertEquals(<br>      &quot;O should be next after X&quot;, <br>      FieldType.O, presenter.nextPlayer(FieldType.X))<br>    Assert.assertEquals(<br>      &quot;X should be next after O&quot;, <br>      FieldType.X, presenter.nextPlayer(FieldType.O))<br>}</pre><p>And that’s it, we can be sure that nextPlayer will change the player to the right one.</p><p>So once the nextPlayer method is ready lets use it in clickField.</p><pre>@Test<br>fun whenClickField_thenChangePlayer() {<br>    presenter.currentPlayerState = FieldType.X<br>    presenter.clickField(0)<br>    Assert.assertEquals(FieldType.O, presenter.currentPlayerState)<br>}</pre><p>And solution to this would be as simple as following.</p><pre>fun clickField(position: Int) {<br>    currentPlayerState = nextPlayer(currentPlayerState)<br>}</pre><p>So we have completed the first requirement. In the <a href="https://github.com/ktalanda/tic-tac-toe">tic-tac-toe</a> project this stage is marked by next-player tag.</p><pre>git checkout next-player</pre><h4>Field choosing</h4><p>Now when we have the right player, lets allow to actually play by putting a sign on the board. Lets begin with test for clickField. It puts our code into RED state.</p><pre>@Test<br>fun givenValidPosition_whenClickField_thenUpdateGameBoardState() {<br>    presenter.currentPlayerState = FieldType.X</pre><pre>    presenter.clickField(1)<br>    presenter.clickField(3)</pre><pre>    Assert.assertTrue(<br>      presenter.gameBoardState[0].<em>contentEquals</em>(<br>        <em>arrayOf</em>(FieldType.NONE, FieldType.X, FieldType.NONE)))<br>    Assert.assertTrue(<br>      presenter.gameBoardState[1].<em>contentEquals</em>(<br>        <em>arrayOf</em>(FieldType.O, FieldType.NONE, FieldType.NONE)))<br>    Assert.assertTrue(<br>      presenter.gameBoardState[2].<em>contentEquals</em>(<br>        <em>arrayOf</em>(FieldType.NONE, FieldType.NONE, FieldType.NONE)))<br>}</pre><p>The solution for this code could be as follow.</p><pre>fun clickField(position: Int) {<br>    currentPlayerState = nextPlayer(currentPlayerState)<br><br>    gameBoardState[position/3][position%3] = currentPlayerState<br>}</pre><p>Lets refactor.</p><pre>fun clickField(position: Int) {<br>    val clickedColumn = position / 3<br>    val clickedRow = position % 3<br>    gameBoardState[clickedColumn][clickedRow] = currentPlayerState</pre><pre>    currentPlayerState = nextPlayer(currentPlayerState)<br>}</pre><p>This completes the happy path of the requirement. Lets cover the error case.</p><pre>@Test(expected = ArrayIndexOutOfBoundsException::class)<br>fun givenToBigInvalidPosition_whenClickField_thenThrowsException() {<br>    presenter.clickField(9)<br>}</pre><p>This test passes without any changes in the code. In classical TDD we should remove this test, but test could be treated as specification and throwing an exception could be mentioned in it.</p><p>Last thing to complete this task is to reload the view representation of the game board.</p><pre>@Test<br>fun whenClickField_thenReloadsGameboardOnView() {<br>    presenter.clickField(1)<br>    <em>verify</em>(viewMock, <em>times</em>(1)).reloadGameBoard(<em>any</em>())<br>}</pre><p>This could be done by the following code.</p><pre>fun clickField(position: Int) {<br>    val clickedColumn = position / 3<br>    val clickedRow = position % 3<br>    gameBoardState[clickedColumn][clickedRow] = currentPlayerState<br>    reloadGameBoard(gameBoardState)<br><br>    currentPlayerState = nextPlayer(currentPlayerState)<br>}</pre><h4><strong>No field overriding</strong></h4><p>Next requirement says that when one user marks a field with his sign this field cannot be chosen again.</p><p>Lets write the first test to put code into RED state.</p><pre>@Test<br>fun givenTakenField_whenClickField_thenDoesnotOverride() {<br>    presenter.currentPlayerState = FieldType.X<br>    presenter.gameBoardState =<br>      <em>arrayOf</em>(<br>        <em>arrayOf</em>(FieldType.X, FieldType.O, FieldType.O),<br>        <em>arrayOf</em>(FieldType.O, FieldType.NONE, FieldType.NONE),<br>        <em>arrayOf</em>(FieldType.X, FieldType.NONE, FieldType.NONE)<br>      )<br>    presenter.clickField(1)<br>    Assert.assertEquals(FieldType.O, presenter.gameBoardState[0][1])<br>}</pre><p>The solution could be as follow.</p><pre>fun clickField(position: Int) {<br>  val clickedColumn = position / 3<br>  val clickedRow = position % 3<br>  <strong>if (gameBoardState[clickedColumn][clickedRow] == FieldType.NONE) {<br>    gameBoardState[clickedColumn][clickedRow] = currentPlayerState<br>  }</strong><br>  reloadGameBoard(gameBoardState)<br>  currentPlayerState = nextPlayer(currentPlayerState)<br>}</pre><p>Now when we are in GREEN state we can either REFACTOR or write next test. Since at this point there is nothing really to refactor we go for another test.</p><pre>@Test<br>fun givenTakenField_whenClickField_thenDoesnotChangePlayer() {<br>    presenter.currentPlayerState = FieldType.X<br>    presenter.gameBoardState = <em>arrayOf</em>(<br>      <em>arrayOf</em>(FieldType.X, FieldType.O, FieldType.O),<br>      <em>arrayOf</em>(FieldType.O, FieldType.NONE, FieldType.NONE),<br>      <em>arrayOf</em>(FieldType.X, FieldType.NONE, FieldType.NONE)<br>    )<br>    presenter.clickField(1)<br>    Assert.assertEquals(FieldType.X, presenter.currentPlayerState)<br>}</pre><p>And the solution.</p><pre>fun clickField(position: Int) {<br>  val clickedColumn = position / 3<br>  val clickedRow = position % 3<br><br>  <strong>if (gameBoardState[clickedColumn][clickedRow] != FieldType.NONE) { <br>        return<br>  }</strong><br>  gameBoardState[clickedColumn][clickedRow] = currentPlayerState<br>  reloadGameBoard(gameBoardState)<br>  currentPlayerState = nextPlayer(currentPlayerState)<br>}</pre><p>This stage of the project is marked by field-overriding tag.</p><pre>git checkout field-overriding</pre><h4>Win conditions.</h4><p>The last thing to do from feature perspective will be to define the conditions when the game ends.</p><p>First end condition is that one of the players has three of his/her signs in the row.</p><pre>@Test<br>fun givenThreeSameInRow_whenGetWinner_thenReturnsWinner() {<br>    val gameBoardStateFake = <em>arrayOf</em>(<br>      <em>arrayOf</em>(FieldType.X, FieldType.X, FieldType.X),<br>      <em>arrayOf</em>(FieldType.O, FieldType.NONE, FieldType.NONE),<br>      <em>arrayOf</em>(FieldType.X, FieldType.NONE, FieldType.NONE)<br>    )<br>    <br>    Assert.assertEquals(<br>      &quot;X should win if it occupies all 3 fields in first row.&quot;, <br>      FieldType.X, presenter.checkWinner(gameBoardStateFake))<br>}</pre><p>Getting back to GREEN is very simple.</p><pre>fun checkWinner(gameBoardState: Array&lt;Array&lt;FieldType&gt;&gt;): FieldType = FieldType.X</pre><p>But this is far from the right solution so we need to get back to RED by writing next test.</p><pre>val gameBoardStateOWinFake = <em>arrayOf</em>(<br>    <em>arrayOf</em>(FieldType.NONE, FieldType.X, FieldType.X),<br>    <em>arrayOf</em>(FieldType.O, FieldType.O, FieldType.O),<br>    <em>arrayOf</em>(FieldType.X, FieldType.NONE, FieldType.NONE)<br>)<br><br>Assert.assertEquals(<br>    &quot;O should win if it occupies all 3 fields in second row.&quot;,<br>    FieldType.O, presenter.checkWinner(gameBoardStateOWinFake))</pre><p>To fulfil that requirement we need to iterate over collection to check the win condition.</p><pre>fun checkWinner(gameBoardState: Array&lt;Array&lt;FieldType&gt;&gt;): FieldType {<br>  if (gameBoardState.<em>any</em>{it.<em>filter</em>{it == FieldType.X}.size == 3 }) {    <br>    return FieldType.X <br>  } <br>  return FieldType.O<br>}</pre><p>Tests pass but this solution means that every time when X does not win whatever else O wins. This is not true because O to win has to meet the same requirements. Lets write the test though.</p><pre>@Test<br>fun givenNoWinner_whenGetWinner_thenReturnsNone() {<br>    val gameBoardStateNoneWinFake = <em>arrayOf</em>(<br>      <em>arrayOf</em>(FieldType.NONE, FieldType.X, FieldType.X),<br>      <em>arrayOf</em>(FieldType.O, FieldType.NONE, FieldType.NONE),<br>      <em>arrayOf</em>(FieldType.X, FieldType.NONE, FieldType.NONE)<br>    )<br>    Assert.assertEquals(<br>      &quot;NONE should win if no winning conditions are met.&quot;,<br>      FieldType.NONE,   <br>      presenter.checkWinner(gameBoardStateNoneWinFake))<br>}</pre><p>And solution to that is as following.</p><pre>fun checkWinner(gameBoardState: Array&lt;Array&lt;FieldType&gt;&gt;): FieldType {<br>  if (gameBoardState.<em>any</em><strong>{it</strong>.<em>filter</em><strong>{it </strong>== FieldType.X<strong>}</strong>.size == 3<strong>}</strong>) {   <br>    return FieldType.X<br>  } <br>  if (gameBoardState.<em>any</em><strong>{it</strong>.<em>filter</em><strong>{it </strong>== FieldType.O<strong>}</strong>.size == 3<strong>}</strong>) {<br>    return FieldType.O <br>  }<br>  return FieldType.NONE<br>}</pre><p>The other way to win is to have the same signs in whole column.</p><pre>@Test<br>fun givenThreeSameInColumn_whenGetWinner_thenReturnsWinner() {<br>    val gameBoardStateXWinFake = <em>arrayOf</em>(<br>      <em>arrayOf</em>(FieldType.X, FieldType.O, FieldType.X),<br>      <em>arrayOf</em>(FieldType.X, FieldType.NONE, FieldType.NONE),<br>      <em>arrayOf</em>(FieldType.X, FieldType.NONE, FieldType.NONE)<br>    )<br>    Assert.assertEquals(<br>      &quot;X should win if it occupies all 3 fields in first column.&quot;,<br>      FieldType.X, presenter.checkWinner(gameBoardStateXWinFake))<br><br>    val gameBoardStateOWinFake = <em>arrayOf</em>(<br>      <em>arrayOf</em>(FieldType.NONE, FieldType.O, FieldType.X),<br>      <em>arrayOf</em>(FieldType.O, FieldType.O, FieldType.X),<br>      <em>arrayOf</em>(FieldType.X, FieldType.O, FieldType.NONE)<br>    )<br><br>    Assert.assertEquals(<br>      &quot;O should win if it occupies all 3 fields in second column.&quot;,<br>      FieldType.O, presenter.checkWinner(gameBoardStateOWinFake))<br>}</pre><p>Here is the very simple brute-force solution.</p><pre>for (j in 0 <em>until </em>gameBoardState.size) {<br>    if (gameBoardState[0][j] == gameBoardState[1][j]<br>            &amp;&amp; gameBoardState[1][j] == gameBoardState[2][j]<br>            &amp;&amp; gameBoardState[0][j] == FieldType.X) {<br>        return FieldType.X<br>    }<br>    if (gameBoardState[0][j] == gameBoardState[1][j]<br>            &amp;&amp; gameBoardState[1][j] == gameBoardState[2][j]<br>            &amp;&amp; gameBoardState[0][j] == FieldType.O) {<br>        return FieldType.O<br>    }<br>}</pre><p>The last win condition is to have same signs on any diagonal.</p><pre>@Test<br>fun givenThreeSameInDiagonal_whenGetWinner_thenReturnsWinner() {<br>    val gameBoardStateXWinFake = <em>arrayOf</em>(<br>      <em>arrayOf</em>(FieldType.X, FieldType.O, FieldType.X),<br>      <em>arrayOf</em>(FieldType.X, FieldType.X, FieldType.NONE),<br>      <em>arrayOf</em>(FieldType.O, FieldType.NONE, FieldType.X)<br>    )<br>    Assert.assertEquals(<br>      &quot;X should win if it occupies all 3 fields in diagonal.&quot;,<br>            FieldType.X,  <br>            presenter.checkWinner(gameBoardStateXWinFake)<br>    )<br><br>    val gameBoardStateOWinFake = <em>arrayOf</em>(<br>      <em>arrayOf</em>(FieldType.NONE, FieldType.O, FieldType.O),<br>      <em>arrayOf</em>(FieldType.O, FieldType.O, FieldType.X),<br>      <em>arrayOf</em>(FieldType.O, FieldType.O, FieldType.NONE)<br>    )<br>    Assert.assertEquals(<br>      &quot;O should win if it occupies all 3 fields in diagonal.&quot;,<br>            FieldType.O,<br>            presenter.checkWinner(gameBoardStateOWinFake)<br>    )<br>}</pre><p>And the simplest brute-force solution.</p><pre>if ((gameBoardState[0][0] == gameBoardState[1][1]<br>            &amp;&amp; gameBoardState[1][1] == gameBoardState[2][2]<br>        || gameBoardState[0][2] == gameBoardState[1][1]<br>            &amp;&amp; gameBoardState[1][1] == gameBoardState[2][0]<br>    ) <br>    &amp;&amp; gameBoardState[1][1] == FieldType.X)<br>    return FieldType.X<br>if ((gameBoardState[0][0] == gameBoardState[1][1]<br>            &amp;&amp; gameBoardState[1][1] == gameBoardState[2][2]<br>        || gameBoardState[0][2] == gameBoardState[1][1]<br>            &amp;&amp; gameBoardState[1][1] == gameBoardState[2][0]<br>    ) <br>    &amp;&amp; gameBoardState[1][1] == FieldType.O)<br>    return FieldType.O</pre><p>The checkWinner method doesn’t look good so this is time for REFACTOR. So this function can be easily splited.</p><pre>fun checkWinner(<br>  gameBoardState: Array&lt;Array&lt;FieldType&gt;&gt;): FieldType {<br>    if (isWinner(FieldType.X, gameBoardState)) return FieldType.X<br>    if (isWinner(FieldType.O, gameBoardState)) return FieldType.O<br><br>    return FieldType.NONE<br>}<br><br>private fun isWinner(<br>    type: FieldType, <br>    gameBoardState: Array&lt;Array&lt;FieldType&gt;&gt;): Boolean =<br>        isWinnerInRow(type, gameBoardState)<br>                || isWinnerInColumn(type, gameBoardState)<br>                || isWinnerInDiagonal(type, gameBoardState)</pre><pre>private fun isWinnerInRow(<br>    type: FieldType, <br>    gameBoardState: Array&lt;Array&lt;FieldType&gt;&gt;<br>): Boolean =<br>    gameBoardState.<em>any </em><strong>{ it</strong>.<em>filter </em><strong>{ it </strong>== type <strong>}</strong>.size == 3 <strong>}</strong></pre><pre>private fun isWinnerInColumn(<br>    type: FieldType, <br>    gameBoardState: Array&lt;Array&lt;FieldType&gt;&gt;): Boolean =<br>      (0 <em>until </em>gameBoardState.size).<em>any </em><strong>{<br>          </strong>gameBoardState[0][<strong>it</strong>] == gameBoardState[1][<strong>it</strong>]<br>            &amp;&amp; gameBoardState[1][<strong>it</strong>] == gameBoardState[2][<strong>it</strong>]<br>            &amp;&amp; gameBoardState[0][<strong>it</strong>] == type<br>        <strong>}</strong></pre><pre>private fun isWinnerInDiagonal(<br>    type: FieldType, <br>    gameBoardState: Array&lt;Array&lt;FieldType&gt;&gt;): Boolean =<br>        (gameBoardState[0][0] == gameBoardState[1][1] &amp;&amp;   <br>         gameBoardState[1][1] == gameBoardState[2][2]<br>             || gameBoardState[0][2] == gameBoardState[1][1] <br>             &amp;&amp; gameBoardState[1][1] == gameBoardState[2][0])<br>         &amp;&amp; gameBoardState[1][1] == type</pre><p>Every time we make any change we run the tests, if they pass it means all works as before so we can continue. Code is a bit cleaner now. It could be further refactored, to note brute-force in isWinnerInColumn and isWinnerInDiagonal, we could move functions around to not keep the domain logic in the presenter and probably few more things could come into picture if we further analyse the code, but we will stop here. Functionality is there, fully tested and working fine. In spirit of <a href="https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it">YAGNI</a> (You ain’t gonna need it) lets do not over-engineer the simple task.</p><p>There is one problem with the code though which we can’t leave. When we reload game board, the value in cleanGameBoard changes… This is clearly a bug. Let’s run regression test first.</p><pre>@Test<br>fun whenReloadPlayground_thenCleanGameBoardShouldNotChange() {<br>  presenter.reloadGameBoard(<br>    <em>arrayOf</em>(<br>      <em>arrayOf</em>(FieldType.X, FieldType.X, FieldType.O),<br>      <em>arrayOf</em>(FieldType.O, FieldType.NONE, FieldType.NONE),<br>      <em>arrayOf</em>(FieldType.X, FieldType.NONE, FieldType.NONE)<br>    )<br>  )<br>  Assert.assertTrue(presenter.cleanGameBoard[0].<em>contentEquals</em>(<br>    <em>arrayOf</em>(FieldType.NONE, FieldType.NONE, FieldType.NONE)))<br>  Assert.assertTrue(presenter.cleanGameBoard[1].<em>contentEquals</em>(<br>    <em>arrayOf</em>(FieldType.NONE, FieldType.NONE, FieldType.NONE)))<br>  Assert.assertTrue(presenter.cleanGameBoard[2].<em>contentEquals</em>(<br>    <em>arrayOf</em>(FieldType.NONE, FieldType.NONE, FieldType.NONE)))<br>}</pre><p>This is something we missed at the beginning and is connected to data types in Kotlin. Array is a mutable data structure, so when we do gameBoardState = cleanGameBoard in init we assign references. Any time gameBoardState changes, so cleanGameBoard does. To fix that lets change our data structure to be immutable. This functionality is provided by List. It will involve some deeper change across tests and the code. But thanks to that we will be able to compare values instead of doing <em>contentEquals.</em></p><p>After changing all arrays to lists there is one problem, which blocks our code from compiling.</p><p>Since gameBoardState is immutable now gameBoardState[clickedColumn][clickedRow] = currentPlayerState is not allowed anymore. To fix this problem we replace this by following code.</p><pre>private fun getUpdatedGameBoardState(<br>  column: Int,<br>  row: Int,<br>  type: FieldType,<br>  gameBoardState: List&lt;List&lt;FieldType&gt;&gt;): List&lt;List&lt;FieldType&gt;&gt; {<br>    val gameBoardStateArray =<br>      gameBoardState.<em>toTypedArray</em>().<em>map </em><strong>{ it</strong>.<em>toTypedArray</em>() <strong>}<br>    </strong>gameBoardStateArray[column][row] = type<br>    return gameBoardStateArray.<em>toList</em>().<em>map </em><strong>{ it</strong>.<em>toList</em>() <strong>}<br></strong>}</pre><p>This is the price we have to pay for immutability. In exchange of cleaner flow sometimes we need to do a bit more work to get things done.</p><p>You can checkout to this code by tag immutability.</p><pre>git checkout immutability</pre><p>Application is almost ready. Now we need to use the logic on views to let the users communicate with it. To get completed code checkout to finish tag.</p><pre>git checkout finish</pre><h3>Summary</h3><p>There is a common misunderstanding between <strong>Q</strong>uality <strong>A</strong>ssurance and <strong>Q</strong>uality <strong>C</strong>hecking in the industry.To truly assure the quality we have to embed it into the project and add it as we go, not by checking once all is ready.</p><p>TDD is not only about testing. The author of the concept — Kent Beck is even saying that test coverage is only the side effect of it and the main purpose of Test Driven Development is to create clean code that works. This is only one way to achieve this goal, in my opinion the easiest.</p><p>Another important motive to use TDD is something that Kent Beck calls managing fear during programming. It makes us being less tentative, communicate more and search for immediate feedback.</p><p>If you are sure that your code is high quality, easy to maintain and extend without TDD probably you don’t need that, but it is hard to judge yourself.</p><blockquote>I’m not a great programmer. I’m just a good programmer with great habits.<br>― <strong>Martin Fowler</strong>, Refactoring: Improving the Design of Existing Code</blockquote><p>So if you do not consider yourself as a genius it is better to build good habits, not to trust only your intuition.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2299359477e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android state management with Redux.]]></title>
            <link>https://medium.com/@ktalanda/android-state-management-with-redux-a1d00123913c?source=rss-ef661ac6aed8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1d00123913c</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Kamil Talanda]]></dc:creator>
            <pubDate>Thu, 07 Sep 2017 12:05:20 GMT</pubDate>
            <atom:updated>2017-09-11T12:07:38.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*42bfEPrbpmvZ4-_Zteyq_Q.png" /></figure><p>State management in any type of the application is not an easy task. Object Oriented paradigm suggests to keep the current state locally inside of the object which owns it, but personally I don’t think it is the best idea. Having the state in various locations makes the application harder to reason about and can cause hard to follow bugs. Here comes Redux with it’s Store and unidirectional data flow.</p><p>The solution described below can be reviewed on Github: <a href="https://github.com/ktalanda/MaroubraScanner/tree/master/redux">https://github.com/ktalanda/MaroubraScanner/tree/master/redux</a></p><p>The sample application using this approach is on Google Play: <a href="https://play.google.com/store/apps/details?id=pl.k2net.ktalanda.maroubrascanner">https://play.google.com/store/apps/details?id=pl.k2net.ktalanda.maroubrascanner</a></p><p>The library is inspired by and based on JS redux implementation: <a href="https://github.com/reactjs/redux">https://github.com/reactjs/redux</a></p><p><strong>State aware app architecture.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*1u7XeAbxZPx9fug4dzptjQ.png" /><figcaption>Diagram 1. State aware app architecture.</figcaption></figure><p>Every well designed application has two places where the state actually matters and where it should be stored. On the diagram above it is Data Access and Presentation. Domain should only pass the data, processing it on the way according to the Business Rules.</p><p>Generally the purpose of most of the apps is to allow the user interact with the data. On the diagram Data Access interacts with all types of the IO devices such as Database, File System, Network. Presentation represent all the interactions with the User Interface. Following this separation we can think of two basic scenarios.</p><ul><li>Data is accessed on Data Access, processed in Domain and presented to the User in Presentation.</li><li>User Interacts with the application in the Presentation, modifies data which has to be processed in Domain and the result mutates state in the Data Access.</li></ul><p>In this article I want to focus on the Presentation Layer. I found Redux pattern to be ideal to solve state management problem in this part of the application.</p><p><strong>Redux pattern in Presentation Layer of the Android app.</strong></p><p>Library is based on unidirectional data flow. All the Visual State of the application lives in the Store and only way to change it is via Actions. No direct mutations are allowed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Nuy4ipDGmZVoWxau4_M51g.png" /><figcaption>Diagram 2. Redux pattern.</figcaption></figure><p><strong>Store</strong> — Singleton object accessible from any part of the Presentation Layer. <a href="https://github.com/ktalanda/ReduxAndroid/blob/master/redux/src/main/java/pl/k2net/ktalanda/redux/Store.kt">[link]</a></p><p>It contains following elements.</p><ul><li><strong>State</strong> — each View is represented by separated ViewModel. All ViewModels are stored in the State. State is an immutable object which can be accessed from any part of the Presentation Layer.</li><li><strong>Reducer</strong>—responsible for the State changes, which are triggered by dispatched Actions.</li><li><strong>Dispatcher</strong> — responsible for receiving the Actions and passing the to the reduced.</li><li><strong>Subject</strong> — Rx interface of the Store. It allows Presenter to react on any State changes. Every Presenter subscribes to it to receive the update events.</li></ul><p><strong>Presenter</strong>— coordinates the data flow in Presentation Layer. It doesn’t contain any local state, but via update method binds ViewModels from the Store to the View. It communicates with Domain via interfaces. <a href="https://github.com/ktalanda/ReduxAndroid/blob/master/redux/src/main/java/pl/k2net/ktalanda/redux/Presenter.kt">[link]</a></p><p><strong>View</strong> — user interface of the application provided by the Android framework. Could be Activity, Fragment or CustomView.</p><p>Flow of any update is very restricted and by following few simple rules, we can make our app much easier to reason about.</p><ul><li>Presenter requests/receives data from the Domain. This could be triggered by the View (user/Android framework interaction) or by push notification from the Domain.</li><li>Presenter dispatches Action which contains the State change.</li><li>Store receives the Action and reduces (changes)State.</li><li>Store produces the update message and passes it to all subscribed Presenters.</li><li>Every Presenter calls update method, which causes change to the View based on new State.</li></ul><p><strong>Following redux pattern gives us many advantages.</strong></p><ul><li>Since the State is only in one place, we can <strong>access</strong> it from anywhere. We don’t have to worry about passing the objects back and forth.</li><li>Because all Presentation Layer access the same State we get out of the box <strong>communication between View elements</strong>. If an Action is dispatched and it causes the State change, an event is triggered and all Presenters update the connected Views.</li><li>We don’t have to worry about <strong>configuration changes</strong>, because we do not store any data inside of Android specific objects like Activity.</li><li>It makes it easy to implement <strong>Undo</strong> functionality. We can simply remember previous State and get back in history if undo action is triggered.</li><li>It makes the application easier to <strong>Unit Test</strong>. Because state is not stored locally around we can make most of the functions pure.</li><li><strong>Logs</strong> are very clear because every state change in the Presentation Layer is triggered by an Action. Simply logging previous State, Action and new State gives as very good information what, when and why happened.</li></ul><p>The main disadvantage of this approach is that for anything we do, we have to create a new Action and follow described above flow. For very small applications, which are not supposed to be maintained long time it could be to strict and could add unnecessary overhead. But this is the price we pay for clarity and maintainability. Everybody has to answer himself if it is worth effort in his individual case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1d00123913c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I don’t like debugging.]]></title>
            <link>https://medium.com/@ktalanda/why-i-dont-like-debugging-c8e63ba76e3f?source=rss-ef661ac6aed8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8e63ba76e3f</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Kamil Talanda]]></dc:creator>
            <pubDate>Sat, 12 Aug 2017 04:49:43 GMT</pubDate>
            <atom:updated>2017-08-12T04:49:43.266Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern IDE’s like Android Studio give us great tools to debug our code. It’s extremely easy to put a breakpoint and check what is going on in our app. Even though it seems very useful I find it bad practice and harmful in new apps development.</p><ol><li><strong>State management</strong> — Since we debug to check current state of our application it means that probably our components are stateful. Stateful components are usually a sign of bad design. It is harder to test stateful objects and functions. If we put effort to make our functions pure and keep the state of the application in limited locations it is much easier to test and get into TDD.</li><li><strong>Better logs</strong> — If you don’t debug logs are much more important and to reason about the app you probably will need to make your models loggable. Those logs can be used later to find out about dataflow both locally and in QA if you catch those logs into some external system.</li><li><strong>IDE independent</strong> — Putting breakpoints, stopping in the place and checking the state is a part of IDE, so if you want to do this you have to run the code from inside of IDE. Personally I prefer to not be tangled to environment and if I want to make some code in vim and build and run it from command line I want to do this.</li><li><strong>Asynchronous</strong> — If you run some code in multithread environment and/or do some asynchronous operations, by stopping your code in one place you can have totally different behaviour than while simply running the code. So it is easy to miss some race conditions and connected problems.</li></ol><p>The only place where I think we have a good reason to debug the code heavily is legacy code without tests. But we don’t want to write legacy code from day one, right?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8e63ba76e3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>