<?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 Katerina on Medium]]></title>
        <description><![CDATA[Stories by Katerina on Medium]]></description>
        <link>https://medium.com/@katerinaCodes?source=rss-19ac9a6e729f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5aDOGr_hwSD0asgcN7bw4Q.jpeg</url>
            <title>Stories by Katerina on Medium</title>
            <link>https://medium.com/@katerinaCodes?source=rss-19ac9a6e729f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:41:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@katerinaCodes/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[How to test a route in Spark Java]]></title>
            <link>https://medium.com/@katerinaCodes/how-to-test-a-route-in-spark-java-437462a4479b?source=rss-19ac9a6e729f------2</link>
            <guid isPermaLink="false">https://medium.com/p/437462a4479b</guid>
            <category><![CDATA[spark-java]]></category>
            <category><![CDATA[web-apps]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Katerina]]></dc:creator>
            <pubDate>Thu, 28 Jun 2018 10:48:41 GMT</pubDate>
            <atom:updated>2018-06-28T11:28:28.463Z</atom:updated>
            <content:encoded><![CDATA[<p>I started the day looking at how I could add some tests to check the behaviour of my web application. I knew I wanted to assert on the response I got back from the server and check a few basic things.</p><p>The first thing I wanted to check which was pretty elementary but still important to test was that the server was responded as I expected to my request. I did this by asserting that the response code sent back was <strong>200</strong>. A server has numerous status codes that is can use in it’s response depending on what the situation is. <strong>200 </strong>means the request has been received and processed successfully.</p><p>Another common status code you may have seen before is <strong>404</strong> which means a client (like Google) was able to connect to a server but couldn’t find what it was looking for.</p><p>As always, with unknown territory, in my case testing a web application, the first test to write was the hardest.</p><p>I did searching for a good testing framework and came across <a href="https://github.com/despegar/spark-test/blob/master/README.md">spark-test</a>. I added the spark-test dependency to my build.gradle and then I was ready to start cooking!</p><pre>version <strong>&#39;1.0-SNAPSHOT&#39;<br><br></strong>apply <strong>plugin</strong>: <strong>&#39;java&#39;<br></strong>apply <strong>plugin</strong>: <strong>&#39;application&#39;<br><br></strong>sourceCompatibility = 1.8<br><br>repositories {<br>  mavenCentral()<br>}<br><br>dependencies {<br>  compile <strong>&#39;com.sparkjava:spark-core:2.2&#39;<br>  </strong>testCompile <strong>group</strong>: <strong>&#39;junit&#39;</strong>, <strong>name</strong>: <strong>&#39;junit&#39;</strong>, <strong>version</strong>: <strong>&#39;4.12&#39;<br>  </strong>testCompile <strong>&#39;com.despegar:spark-test:1.1.8&#39;<br></strong>}</pre><p>Using the template test from spark-test I was able to adapt the code they used to my classes. I defined another class within my WebApplicationTest class and got it to implement SparkApplication interface. This interface requires the definition of an init() method and the method creates a new instance of my WebApplication class and calls its run() method so my application began to run.</p><p>This method is partially where the magic happens as it is where the server is started, a request is made to the my Tic Tac Toe web application and my board is displayed on the webpage.</p><pre><strong>public class </strong>WebApplicationTest {<br><br>  <strong>public static class </strong>WebAppTestSparkApp <strong>implements </strong>SparkApplication {<br>  <strong>public void </strong>init() {<br>    <strong>new </strong>WebApplication().run();<br>  }<br>}<br><br>  @ClassRule<br>  <strong>public static </strong>SparkServer&lt;WebAppTestSparkApp&gt; <em>testServer </em>= <strong>new </strong>SparkServer&lt;&gt;(WebAppTestSparkApp.<strong>class</strong>, 4567);<br><br>  @Test<br>  <strong>public void </strong>serverRespondsSuccessfully() <strong>throws </strong>HttpClientException {<br>    GetMethod request = <em>testServer</em>.get(<strong>&quot;/&quot;</strong>, <strong>false</strong>);<br>    HttpResponse httpResponse = <em>testServer</em>.execute(request);<br>    <em>assertEquals</em>(200, httpResponse.code());<br>  }</pre><p>I then create an instance of the SparkServer class which I assign to the variable testServer. To create this class I give my it my WebAppTestSparkApp and a port number.</p><p>After all of the set up was done, I could get on with writing my actual test which I named ‘serverRespondsSuccessfully’.</p><p>The way this framework works is that I first set up the request in an object of type GetMethod. I aptly assigned this to a variable named ‘request’.</p><p>We use a method to create an object representing the request we want to make. We can then send this request to the app we want to test. Confusingly, this method is called ‘get’ and lives on the SparkServer instance itself. I then give this method the parameters of a route and a boolean. The boolean indicates whether you want to redirect the request. In my case I did not so the boolean is false.</p><p>Once, you have done this you separately have to call a method called execute which also lives on the SparkServer class and give it the parameter of your GetMethod object.</p><p>The execute method uses the request parameter to make a request as if it is was a client to our testServer. This returns a HttpResponse which you can then assert on!</p><p>Phew. This test framework is great because you can make lots of different assertions once you’ve set everything up. When using another framework like Spark, you would just set up and execute the request with the get in one go but in this case it’s a two step process. In spite of this, I am still grateful to be able to use this framework for my tests so thank you spark-test!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=437462a4479b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic Versioning]]></title>
            <link>https://medium.com/@katerinaCodes/semantic-versioning-15aa43c33317?source=rss-19ac9a6e729f------2</link>
            <guid isPermaLink="false">https://medium.com/p/15aa43c33317</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[semantic-versioning]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Katerina]]></dc:creator>
            <pubDate>Fri, 04 May 2018 10:13:20 GMT</pubDate>
            <atom:updated>2018-05-04T10:52:39.517Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Software versioning</strong> is the process of assigning either unique <em>version names</em> or unique <em>version numbers</em> to unique states of <a href="https://en.wikipedia.org/wiki/Computer_software">computer software</a>. — Wikipedia</blockquote><p>Semantic Versioning uses a sequence of three digits each correlating to <strong>Major. Minor. Patch</strong> to detail what kind of change has been made to the software. Each change is graded depending on risk and functionality.</p><p>Changes to software versions a signified with an numeric increase of one to the Major, Minor or Patch number. Semantic Versioning starts at 0.1.0 not 0.0.1. This is because you do not start a new project with a patch, it starts with building a set of features.</p><p><strong>Major —</strong> Changes graded as a major risk encompass anything that can break the software.<strong> </strong>If there has been a major change then it’s important to update to that new version of the software as soon as possible.</p><p>Conventionally, Major changes to a software version will reset the following two Minor and Patch numbers to zero.</p><pre>Before: <strong>v1.2.3</strong><br>After: <strong>v2.0.0</strong></pre><p><strong>Minor</strong> — New features that improve the quality of the software but do not break anything are graded as a medium risk.</p><p>In this case the Minor number is increased and the Patch is reset to zero.</p><pre>Before: <strong>v1.1.1</strong><br>After: <strong>v1.2.0</strong></pre><p><strong>Patch</strong> — Changes such as small bug fixes which do not break the software are graded as a low risk.</p><p>In this instance, only the patch number in incremented by one.</p><pre>Before: <strong>v1.1.0</strong><br>After: <strong>v1.1.1</strong></pre><p>I enjoyed this very thorough description of the semantic versioning format from Tom Preston-Werner which reiterates what I have spoken about above:</p><blockquote>A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor version, and Z is the patch version. Each element MUST increase numerically.</blockquote><blockquote>For instance: <strong>1.9.0 -&gt; 1.10.0 -&gt; 1.11.0.</strong></blockquote><p>Sometimes a different style of formatting in used for releases that are not stable enough to use in practical development:</p><ul><li>0 is used for alpha.</li><li>1 is used for beta.</li><li>2 is used for release.</li><li>3 is used for final release.</li></ul><p>For example, <strong>1.1.0</strong> could be <strong>1.1.0-alpha.1</strong>. If another build is needed, it would become <strong>1.1.0-alpha.2</strong>.</p><p>I have also seen it detailed as 1.0.0.alpha1</p><p>There seems to be some differences in how people choose to do formatting for their semantic versioning. I believe what I have used above to be the most standard type but am open to alternative ways and opinions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15aa43c33317" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Immutable Vs Mutable Objects]]></title>
            <link>https://medium.com/@katerinaCodes/immutable-vs-mutable-objects-d30ea96fb585?source=rss-19ac9a6e729f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d30ea96fb585</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[mutation]]></category>
            <category><![CDATA[immutable-vs-mutable]]></category>
            <category><![CDATA[immutable]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Katerina]]></dc:creator>
            <pubDate>Wed, 11 Apr 2018 10:19:28 GMT</pubDate>
            <atom:updated>2018-04-11T10:19:28.119Z</atom:updated>
            <content:encoded><![CDATA[<p>As a programmer you will often come across the terms Immutable and Mutable. In this blog post, I’m going to go explain what these terms mean and show some examples of an immutable object from my code.</p><h4><strong>A closer look at Immutable and Mutable objects</strong></h4><p>An object whose state cannot be modified once is has been created.</p><p>An example of this in Java would be a constant which is a variable that cannot be changed once you have set it’s value.</p><pre><strong>Java</strong>:</pre><pre>String DOG = &quot;Dog&quot; </pre><p>Weirdly, in Ruby even though you can create constants, they do not strictly behave as constants and are still mutable:</p><pre><strong>Ruby</strong>:</pre><pre>DOG = &quot;Dog&quot;</pre><pre>irb(main):001:0&gt; DOG = &quot;dog&quot;<br>=&gt; &quot;dog&quot;</pre><pre>irb(main):002:0&gt; DOG<br>=&gt; &quot;dog&quot;</pre><pre>irb(main):003:0&gt; DOG = &quot;cat&quot;</pre><pre>(irb):3: warning: already initialized constant DOG<br>(irb):1: warning: previous definition of DOG was here<br>=&gt; &quot;cat&quot;</pre><pre>irb(main):004:0&gt; DOG<br>=&gt; &quot;cat&quot;</pre><p>In the example above, I can reassign the value of the constant DOG and doing so will mutate and therefore change the “constant”. The only thing that happens is that a warning is displayed saying that the previous constant has changed.</p><p>In Java you can also declare variables or classes as <strong>final </strong>which is another way of saying that the object or its values won’t change.</p><pre>public final String dog = &quot;Dog&quot;</pre><p>Ruby has an enumerable method <strong>.freeze </strong>which stops the object being modified and displays an error when you try to modify it using <strong>.concat </strong>or <strong>&lt;&lt; (append)</strong>. This is because both these methods try to mutate the frozen object by appending an additional string to it. There is no way to unfreeze a frozen object so at that point it is truly immutable.</p><pre>irb(main):001:0&gt; dog = &quot;dog&quot;<br>=&gt; &quot;dog&quot;</pre><pre>irb(main):002:0&gt; dog.object_id<br>=&gt; 70310733405180</pre><pre>irb(main):003:0&gt; dog.concat(&quot;!&quot;)<br>=&gt; &quot;dog!&quot;</pre><pre>irb(main):004:0&gt; dog.freeze<br>=&gt; &quot;dog!&quot;</pre><pre>irb(main):005:0&gt; dog.concat(&quot;!!&quot;)<br><strong>Traceback</strong> (most recent call last):<br>3: from /usr/local/bin/irb:11:in `&lt;main&gt;&#39;<br>2: from (irb):5<br>1: from (irb):5:in `concat&#39;<br><strong>FrozenError (can&#39;t modify frozen String)</strong></pre><pre>irb(main):006:0&gt; dog.object_id<br>=&gt; 70310733405180<br></pre><pre><em>// Below, even though I use dog which is frozen, by using &quot;</em><strong><em>+</em></strong><em>&quot;, I <br>// create a new object but as I don&#39;t assign it to a variable this // is lost. When we call dog again it&#39;s still go the original value // and ID it was assigned.</em></pre><pre>irb(main):007:0&gt; dog + &quot;!!&quot;<br>=&gt; &quot;dog!!!&quot;</pre><pre>irb(main):009:0&gt; dog<br>=&gt; &quot;dog!&quot;</pre><pre>irb(main):010:0&gt; dog.object_id<br>=&gt; 70310733405180</pre><p><strong>*</strong>One interesting thing to note is that concatenation or appending is not the same as using the <strong>+</strong> method in Ruby. I was trying to test <strong>.freeze </strong>with adding two strings together and I was able to use it without getting an error message.</p><p>After reading the ruby documentation on what the <strong>+ </strong>method does I realised it creates a new String object containing the previous string which is why no error came up and I was able to use the dog variable in my updated string.</p><p>You can call <strong>.frozen?</strong> on an object that you have used the<strong> .freeze</strong> method on to check its status and whether if an object’s state can be modified or not.</p><pre>irb(main):011:0&gt; dog.frozen?<br>=&gt; true</pre><h3>Immutable state in my own code</h3><p>I built a game of Tic Tac Toe in Java and throughout the codebase I was using the <strong>grid</strong> instance variable that lived on my Board class and manipulating it to update the <strong>grid</strong> or check a value on the <strong>grid</strong>.</p><p>Each time it was a player’s turn to make a move <strong>currentPlayer.playMove(board) </strong>was called.</p><pre><strong>public class </strong>Game {</pre><pre>  public void run() {<br>    <br>    // I have omitted code that&#39;s unnecessary for this example.</pre><pre>    while (gameIsNotOver()) {<br>      ui.askForMove(currentPlayer.getMark(), this.board.grid);<br>      currentPlayer.playMove(board);<br>      displayBoard();<br>      switchPlayer(playerOne, playerTwo);<br>    }<br>  }</pre><pre>}<br></pre><pre><strong>public class </strong>Computer {</pre><pre>  public void playMove(Board board) {<br>    int playerMove = move(board);<br>    board.updateMove(playerMove, mark);<br>  }</pre><pre>  public int move(Board board) {<br>    List&lt;Integer&gt; possibleMoves = board.availableMoves();<br>    return possibleMoves.get(0);<br>  }</pre><pre>}</pre><pre><strong>public class </strong>HumanPlayer {</pre><pre>  public void playMove(Board board) {<br>    int playerMove = getMove(board);<br>    board.updateMove(playerMove, this.mark);<br>  }</pre><pre>  private Integer getMove(Board board) {<br>    String userMove = ui.getMove(board);<br>    return Integer.<em>parseInt</em>(String.<em>valueOf</em>(userMove)) - 1;<br>  }</pre><pre>}</pre><pre><strong>public class </strong>Board {</pre><pre>  public List&lt;Mark&gt; updateMove(int position, Mark mark) {<br>    this.grid.set(position, mark);<br>    return this.grid;    <br>  }</pre><pre>}</pre><p>I wanted to remove the mutable state from the Board class so the way I did this was by creating a new instance of the Board class each time the <strong>grid</strong> was modified then instantiating it with the updated version of the <strong>grid.</strong></p><p>When a new instance of the Board is being created fresh then passed back to the game it means objects don’t interfere with each other’s copies of the Board and the Game class’s version of the board remains consistent. Or, as Roger details in <a href="https://hackernoon.com/5-benefits-of-immutable-objects-worth-considering-for-your-next-project-f98e7e85b6ac">this blog post here</a>, “<strong> If one thread needs a new version or altered version of that object, it must create a new one therefore any other threads will still have the original object</strong>.”</p><p>In the code example above, if there was a mistake and both players made a move on the Board’s grid one after the other using the same state of the <strong>grid</strong>, it’s clear to see how this could end up causing a lot of issues. One player would end up having more than one turn and the rest of the <strong>grid</strong> would be ruined as a result of this. However, as the <strong>playMove()</strong> method allows the player to select a move and update the <strong>grid </strong>in the same method, it somewhat removes this issue.</p><p>Though that was the case, I still wanted to make the Board truly immutable and ensure a the state of an object a player has is guaranteed to be correct.</p><h4><strong>After changes:</strong></h4><pre><strong>public class </strong>Game {</pre><pre>  public void run() {</pre><pre>    // I have omitted code that&#39;s unnecessary for this example.</pre><pre>    while (gameIsNotOver()) {<br>      ui.askForMove(currentPlayer.getMark(), this.board.grid);<br>      board = currentPlayer.playMove(board);<br>      displayBoard();<br>      switchPlayer(playerOne, playerTwo);<br>    }<br>  }<br> <br>}</pre><pre><strong>public class </strong>Computer {</pre><pre>  public Board playMove(Board board) {<br>    int playerMove = move(board);<br>    return board.updateMove(playerMove, mark);<br>  }</pre><pre>}</pre><pre><strong>public class </strong>HumanPlayer {</pre><pre>  public Board playMove(Board board) {<br>    int playerMove = getMove(board);<br>    return board.updateMove(playerMove, this.mark);     <br>  }</pre><pre>}</pre><pre><strong>public class </strong>Board {</pre><pre>  public Board updateMove(int position, Mark mark) {<br>    this.grid.set(position, mark);<br>    return new Board(size, this.grid);     <br>  }</pre><pre>}</pre><p>Instead of returning a updated grid each time a player made a move, I returned a new instance of the Board class and instantiated it with the updated <strong>grid</strong>. This meant the Board was never truly modified as each time it would just be a new Board class with the current state of the <strong>grid.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d30ea96fb585" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conquering Minimax — part 3]]></title>
            <link>https://medium.com/@katerinaCodes/conquering-minimax-part-3-ca28227de529?source=rss-19ac9a6e729f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca28227de529</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[tic-tac-toe]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[minimax]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Katerina]]></dc:creator>
            <pubDate>Thu, 05 Apr 2018 09:06:37 GMT</pubDate>
            <atom:updated>2018-04-05T13:31:27.958Z</atom:updated>
            <content:encoded><![CDATA[<p>After experimenting again with how to store each move and score and looking at Java streams I found <a href="https://www.javabrahman.com/java-8/java-8-finding-maxmin-with-collectors-maxby-minby-methods-tutorial-with-examples/">this code example</a>. As the example used a new class with instance variables for each important value.</p><p>I created a new class called <strong>BestScore</strong> and gave it the instance variables <strong>move</strong> and <strong>score</strong>.</p><pre>public static class BestScore {<br>  private final int move;        <br>  private final int moveScore;<br>  <br>  public BestScore(int move, int moveScore) {<br>    this.move = move;<br>    this.moveScore = moveScore;        <br>  }         </pre><pre>  public int getMoveScore() {<br>    return moveScore;        <br>  }         </pre><pre>  public int getMove() {<br>    return move;        <br>  }</pre><pre>}</pre><p>Each time I looped over a move instead of pushing the current move and its score into a hash, I created a new instance of <strong>BestScore</strong> with the current move and score.</p><pre>private List&lt;BestScore&gt; scores = new ArrayList&lt;&gt;();</pre><pre>  public int findBestMove(Board board, Boolean maximisingPlayer) {<br>    Mark opponentMark = mark == Mark.O ? Mark.X : Mark.O;<br>    if (board.gameIsOver()) {<br>      if (board.playerHasWon(mark)) {<br>        return 1;            <br>      } else if (board.playerHasWon(opponentMark)) {<br>        return -1;<br>      } else if (board.gameIsTied()) {<br>        return 0;             <br>      }        <br>    }         </pre><pre>    if (maximisingPlayer) {            <br>      int bestScore = -10;            <br>      List&lt;Integer&gt; possibleMoves = board.availableMoves();<br>    <br>      for (int move : possibleMoves) {                <br>        board = board.updateMove(move, mark);                <br>        int currentScore = findBestMove(board, false);<br>        bestScore = bestScore &gt; currentScore ? bestScore : currentScore;<br>        board = board.updateMove(move, Mark.EMPTY);<br>        scores.add(new BestScore(move, bestScore));            <br>      }<br>      bestMove = maxMove(scores).getMove();<br>      return maxMove(scores).getMoveScore();        <br>    } else {            <br>      int bestScore = +10;            <br>      List&lt;Integer&gt; possibleMoves = board.availableMoves();<br>  <br>      for (int move : possibleMoves) {                <br>        board = board.updateMove(move, opponentMark);                <br>        int currentScore = findBestMove(board, true);<br>        bestScore = bestScore &lt; currentScore ? bestScore : currentScore;<br>        board = board.updateMove(move, Mark.EMPTY);<br>        scores.add(new bestScore(move, bestScore));            <br>      }           <br>      bestMove = minMove(scores).getMove();            <br>      return minMove(scores).getMoveScore();        <br>    }    <br>  }</pre><p>Each time a new move was played, I add it to the scores array with this line.</p><pre>scores.add(new BestScore(move, bestScore));</pre><p>Instead of sorting the list of scores from largest to smallest, I used the Java Stream methods <strong>max</strong> and <strong>min</strong>. These methods use an instance of Comparator and compare values in a stream to get the maximum or minimum value.</p><pre>public BestScore maxMove(List&lt;BestScore&gt; scores) {<br>  BestScore highestScoringMove = scores.stream()<br>               .max(Comparator.comparing(BestScore::getMoveScore))<br>               .orElse(new BestScore(-1, -1));        <br>  return highestScoringMove;    <br>}</pre><pre>public BestScore minMove(List&lt;BestScore&gt; scores) {        <br>  BestScore lowestScoringMove = scores.stream()<br>                .min(Comparator.comparing(BestScore::getMoveScore))<br>                .orElse(new BestScore(-1, -1));        <br>  return lowestScoringMove;    <br>}</pre><p>I thought this would be my solution and in theory it seemed to answer all of my problems. Though it seemed to work when it choosing the best move for my player in a winning game state, when it had to choose a move to block a player win, it didn’t work.</p><p>I used System.out all of the <strong>findBestMove()</strong> method to try and figure out was was going on. I tried tweaking the method in numerous places to see if it helped me solve the problem and changed the outcome. I was going in circles.</p><p>I’m still not sure 100% why the <strong>min</strong> and <strong>max </strong>methods<strong> </strong>weren’t working in the game flow as they should. I have a theory it’s because when the player type switched to simulate each game state the scores list got populated incorrectly. I stopped at that point to reassess how best to move forward with the code.</p><p>I decided to go back to basics. I needed to figure out what was happening with my code. I needed a better strategy and a series of next steps. Below are the things I tried:</p><ol><li>Identify patterns with regards to where the computer player isn’t playing as it should. For example, it seemed like if the computer played position 3 first then it ended up losing. Whereas, if I played position 3 first then the computer played the correct steps.</li></ol><p>After trying the step above, it didn’t seem like I identified a consistent and helpful pattern, just one of many issues with the algorithm not working as expected.</p><p>2. My next idea was to visit other people’s code and look at pseudocode to see if there were issues within my implementation. Perhaps the maximising and minimising players were not switching as they should or there were other issues that I was overlooking.</p><p>After printing the value of my move in various places in my code I could see that the best move was correct until it was sent to the <strong>minMove</strong> or <strong>maxMove </strong>methods. After coming back from being passed to those methods, it would just return whatever move had been played before.</p><pre>bestMove = minMove(scores).getMove();            <br>return minMove(scores).getMoveScore();</pre><p>The only two things I cared about were the best move and score. If those were being filtered by the If statement then why did I need the <strong>minMove</strong> and <strong>maxMove</strong> methods? I decided to keep it simple and return a list of the move and score.</p><p>I also noticed an if statement in another person’s code that acted like a filter to re-write both <strong>bestMove</strong> and <strong>bestScore</strong> instead of just rewriting just the <strong>bestScore</strong> using the turnery operator.</p><pre><strong>Before:</strong></pre><pre>bestScore = bestScore &lt; currentScore ? bestScore : currentScore;</pre><pre><strong>After:</strong></pre><pre>// This is for the minimising player, for the maximising player the condition is if currentScore is greater than bestScore.</pre><pre>if (currentScore &lt; bestScore) {  <br>  bestScore = currentScore;                    <br>  bestMove = move;                <br>}</pre><p>I used this code in mine to remove the turnery operator and changed the code to return a list of <strong>bestMove</strong> and <strong>bestScore</strong>.</p><pre>if (maximisingPlayer) {            <br>  int bestScore = -10;            <br>  List&lt;Integer&gt; possibleMoves = board.availableMoves();            <br>  for (int move : possibleMoves) {                <br>    board = board.updateMove(move, mark);                <br>    int currentScore = findBestMove(board, false).get(1);<br>    if (currentScore &gt; bestScore) {                    <br>      bestScore = currentScore;                    <br>      bestMove = move;                <br>    }                 <br>    board = board.updateMove(move, Mark.EMPTY);            <br>  }            <br>  return asList(bestMove, bestScore);        <br>} else {            <br>  int bestScore = +10;<br>  List&lt;Integer&gt; possibleMoves = board.availableMoves();            <br>  for (int move : possibleMoves) {<br>    board = board.updateMove(move, opponentMark);                <br>    int currentScore = findBestMove(board, true).get(1);<br>    if (currentScore &lt; bestScore) {                    <br>      bestScore = currentScore;                    <br>      bestMove = move;                <br>    }                 <br>    board = board.updateMove(move, Mark.EMPTY);            <br>  }            <br>  return asList(bestMove, bestScore);        <br>}       </pre><p>This worked perfectly and suddenly I had successfully implemented Minimax!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca28227de529" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conquering Minimax — part 2]]></title>
            <link>https://medium.com/@katerinaCodes/conquering-minimax-part-2-e83ba2154251?source=rss-19ac9a6e729f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e83ba2154251</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tic-tac-toe]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[minimax]]></category>
            <dc:creator><![CDATA[Katerina]]></dc:creator>
            <pubDate>Thu, 05 Apr 2018 09:04:01 GMT</pubDate>
            <atom:updated>2018-04-05T09:12:06.878Z</atom:updated>
            <content:encoded><![CDATA[<p>As I mentioned <a href="https://medium.com/@katerinaCodes/conquering-minimax-part-1-3ed34434e884">in my previous blog post</a> I was implementing a unbeatable computer play in Java Tic Tac Toe.</p><p>I wanted to test my minimax algorithm was working. To do this, I integrated the new UnbeatableComputer class into my game flow.</p><p>Unfortunately, though my tests were green, things were still going awry. Sometimes my unbeatable player would play as I expected and would either win against me or tie. Yet, there were some game states where the computer did not pick the best move, failing to block my winning move. Something was wrong.</p><p>I played the game many times and took notes of some moves the computer didn’t play as it should. It appeared to be the same pattern that tripped the computer player up. I then wrote a test to expose one of these patterns.</p><pre>@Test<br><strong>public void </strong>blocksADifferentWin() {<br>    UnbeatableComputer unbeatableComputer = <strong>new </strong>UnbeatableComputer(<strong><em>O</em></strong>);<br>    Board board = <strong>new </strong>Board(3, <em>asList</em>(<br>            <strong><em>EMPTY</em></strong>, <strong><em>EMPTY</em></strong>, <strong><em>O</em></strong>,<br>            <strong><em>EMPTY</em></strong>, <strong><em>X</em></strong>, <strong><em>X</em></strong>,<br>            <strong><em>EMPTY</em></strong>, <strong><em>EMPTY</em></strong>, <strong><em>EMPTY</em></strong>));<br>    <em>assertThat</em>(unbeatableComputer.findBestMove(board, <strong>true</strong>, -1), <em>is</em>(3));<br>}</pre><p>I realised I was returning the last move played every time but not scoring a move and returning the highest scoring move. This meant the move and played by the “ unbeatable” computer wasn’t always accurate.</p><p>To try and get my game to play in the correct way, I reintroduced the scoring if statement at the start. Whether I had the if statement or not, I needed to keep track of the best scoring game state depending on the move played.</p><p>I created a hash called <strong>bestMoves</strong> and if the current move scored 1 or 0 then I pushed the move as the key and score as the value inside the map.</p><pre><strong>class </strong>UnbeatableComputer <strong>implements </strong>Player {<br>  <strong>private </strong>Mark <strong>mark</strong>;<br>  <strong>public </strong>HashMap <strong>bestMoves</strong>;</pre><pre><strong>  public </strong>UnbeatableComputer(Mark mark) {<br>    <strong>this</strong>.<strong>mark </strong>= mark;<br>    <strong>this</strong>.<strong>bestMoves </strong>= <strong>new </strong>HashMap();<br>  }</pre><pre><strong>  if </strong>(score == 1 || score == 0) {<br><strong>    bestMoves</strong>.put(move, score);<br>  }</pre><p>My plan was to find the highest score in the map and then return the move corresponding to that score.</p><p>I found a way to iterate over the values and find one that matched a given condition. The problem was that the condition was too limiting.</p><p>I created an instance variable called <strong>BestMoves</strong> and pushed the current move and score to it for the keys and values.</p><pre><strong>public int </strong>getBestMove() {<br>  <strong>for </strong>(Map.Entry&lt;Integer, Integer&gt; entry : bestMoves.entrySet()) {<br>    <strong>if </strong>(entry.getValue() == 1) {<br>      <strong>return </strong>entry.getKey();<br>    }<br>  }<br>}</pre><p>I wanted to iterate through the values and find the value equal to 1 or 0. Then I wanted to return the move that corresponded to that score. If the game state produces scores only equal to 0, it wouldn’t meet the condition (entry.getValue() == 1) or return the right move.</p><p>I tried playing with this and adding another condition to return the score if it was equal to 0 but that didn’t help. For example, what if the first score was 0 but the next score was 1? We’d return early at 0 and not get to the second score which means the highest score and corresponding key (move) is not returned.</p><pre><strong>public int </strong>getBestMove() {<br>  <strong>for </strong>(Map.Entry&lt;Integer, Integer&gt; entry : bestMoves.entrySet()) {<br>    <strong>if </strong>(entry.getValue() == 1) {<br>        <strong>return </strong>entry.getKey();<br>    } <strong>else </strong>{<br>        <strong>return </strong>entry.getKey();<br>    }<br>  }<br>}</pre><p>To solve this issue, I needed a way of sorting all the scores from highest to lowest. Once sorted, it would be a simple as returning the first key and that would be the highest scoring move. Unfortunately, Java didn’t want to be kind and I couldn’t find a simple way of both sorting the whole hash by its values.</p><p>There are Ruby enumerable methods that would have made this very simple but Java doesn’t have simplest solutions for this kind of manipulation and it would have involved numerous loops. I decided to work with Java Streams to see if that could help. I expand on this process in <a href="https://medium.com/@katerinaCodes/conquering-minimax-part-3-ca28227de529">part 3 of my blog post</a>.</p><p>The main lesson I learnt was that manipulating hashmaps in Java is a confusing and long process. A simpler data structure would have been easier to work with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e83ba2154251" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conquering Minimax — part 1]]></title>
            <link>https://medium.com/@katerinaCodes/conquering-minimax-part-1-3ed34434e884?source=rss-19ac9a6e729f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ed34434e884</guid>
            <category><![CDATA[zero-sum-game]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[tic-tac-toe]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[minimax]]></category>
            <dc:creator><![CDATA[Katerina]]></dc:creator>
            <pubDate>Thu, 05 Apr 2018 08:39:36 GMT</pubDate>
            <atom:updated>2018-04-05T09:04:34.600Z</atom:updated>
            <content:encoded><![CDATA[<p>When I completed my first Tic Tac Toe in Ruby, I used heuristics inside of an aka a set of rules in one large if Statement to make my computer unbeatable.</p><p>Many of my colleagues who implemented an unbeatable computer player used the Minimax algorithm. I wanted to conquer the unbeatable computer player using that algorithm too. When my mentors gave me a story to implement an unbeatable computer player using Minimax, it was a chance to tackle the challenge head on!</p><p>After looking at the pseudocode, I came up with an initial version of the algorithm. It worked out a score for each end of game state but returned the score (0, -1, +1) and not the move itself.</p><p>I needed to figure out how to get my code to return what I wanted it to.</p><pre><strong>public int </strong>findBestMove(Board board, Boolean maximisingPlayer) {<br>  <strong>int </strong>endOfGameScore = 100;<br>  Mark playerMark = <strong>mark </strong>== Mark.<strong><em>O </em></strong>? Mark.<strong><em>X </em></strong>: Mark.<strong><em>O</em></strong>;<br><br>  <strong>if </strong>(board.gameIsOver()) {<br>     <strong>if </strong>(board.playerHasWon(<strong>mark</strong>)) {<br>          endOfGameScore = 1;<br>     } <strong>else if </strong>(board.playerHasWon(playerMark)) {<br>        endOfGameScore = -1;<br>     } <strong>else if </strong>(board.gameIsTied()) {<br>        endOfGameScore = 0;<br>    }<br>     <strong>return </strong>endOfGameScore;<br> } <strong>else if </strong>(maximisingPlayer) {<br>    <strong>int </strong>bestValue = -10;<br><br>     List&lt;Integer&gt; possibleMoves = board.availableMoves();<br>    <strong>for </strong>(<strong>int </strong>move : possibleMoves) {<br>        board = board.updateMove(move, <strong>mark</strong>);<br>        <strong>int </strong>score = findBestMove(board, <strong>false</strong>);<br>        bestValue = bestValue &gt; score ? bestValue : score;<br>        <strong>int </strong>currentMove = move;<br>        board = board.updateMove(move, Mark.<strong><em>EMPTY</em></strong>);<br>     }<br>     <strong>return </strong>bestValue;<br>  } <strong>else </strong>{<br>     <strong>int </strong>bestValue = +10;<br>     List&lt;Integer&gt; possibleMoves = board.availableMoves();<br>     <strong>for </strong>(<strong>int </strong>move : possibleMoves) {<br>        board = board.updateMove(move, playerMark);<br>        <strong>int </strong>score = findBestMove(board, <strong>true</strong>);<br>        bestValue = bestValue &lt; score ? bestValue : score;<br>        <strong>int </strong>currentMove = move;<br>        board = board.updateMove(move, Mark.<strong><em>EMPTY</em></strong>);<br>     }<br>     <strong>return </strong>bestValue;<br>  }<br>}</pre><p>When the game was over, I was scoring it and then returning that score. In actuality, what I needed to return was the best move that corresponded with the best value.</p><p>I decided to write a test to see if the computer could pick the best move and win.</p><pre>@Test<br><strong>public void </strong>computerPlaysWinningMove() {<br>  UnbeatableComputer unbeatableComputer = <strong>new </strong>UnbeatableComputer(<strong><em>X</em></strong>);<br>  Board board = <strong>new </strong>Board(3, <em>asList</em>(<br>        <strong><em>EMPTY</em></strong>, <strong><em>X</em></strong>, <strong><em>O</em></strong>,<br>        <strong><em>O</em></strong>, <strong><em>X</em></strong>, <strong><em>X</em></strong>,<br>        <strong><em>EMPTY</em></strong>, <strong><em>EMPTY</em></strong>, <strong><em>O</em></strong>));<br>  <em>assertThat</em>(unbeatableComputer.findBestMove(board, <strong>true</strong>, -1), <em>is</em>(7));<br>}</pre><p>I removed the nested if statement and instead had an if condition, checking if the game was over. If it was then it returned the player’s current move.</p><pre><strong>public int</strong> findBestMove(Board board, Boolean maximisingPlayer, int playerMove) {<br>  Mark playerMark = <strong>mark </strong>== Mark.<strong><em>O </em></strong>? Mark.<strong><em>X </em></strong>: Mark.<strong><em>O</em></strong>;<br>  <strong>if</strong> (board.gameIsOver()) {<br>    return playerMove;<br>  } <strong>else if</strong> (maximisingPlayer) {<br>    int bestValue = -10;</pre><pre>    List&lt;Integer&gt; possibleMoves = board.availableMoves();<br>    for (int move : possibleMoves) {<br>      board = board.updateMove(move, <strong>mark</strong>);<br>      <strong>int</strong> score = findBestMove(board, <strong>false</strong>, move);     <br>      bestValue = bestValue &gt; score ? bestValue : score; <br>      board = board.updateMove(move, Mark.<strong><em>EMPTY</em></strong>);           <br>    }<br>    <strong>return</strong> bestValue;<br>  } <strong>else</strong> {<br>    <strong>int</strong> bestValue = +10;<br>    List&lt;Integer&gt; possibleMoves = board.availableMoves();          <br>    for (int move : possibleMoves) {<br>      board = board.updateMove(move, playerMark);<br>      <strong>int</strong> score = findBestMove(board, <strong>true</strong>, move);<br>      bestValue = bestValue &lt; score ? bestValue : score;<br>      board = board.updateMove(move, Mark.<strong><em>EMPTY</em></strong>);<br>    }<br>    <strong>return</strong> bestValue;       <br>  }    <br>}</pre><p>After changing my code the test went green and I was feeling more confident that the algorithm was working as it should.</p><p>My next test was to check if the computer could block a move when given a state where X was about to win and the test passed.</p><p>I then wrote another test to see if the computer could block a fork and again the algorithm chose the correct move.</p><p>Everything seemed to be working as it should but I wanted to integrate the unbeatable player to my game flow and play against it to test it in action.</p><p>Unfortunately, things were not all as they appeared. I go on to explain this further is part two of this blog post <a href="https://medium.com/@katerinaCodes/conquering-minimax-part-2-e83ba2154251">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ed34434e884" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[For Loops vs Java Streams]]></title>
            <link>https://medium.com/@katerinaCodes/for-loops-vs-java-streams-d5456bc3f1ad?source=rss-19ac9a6e729f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5456bc3f1ad</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javastreams]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[for-loop]]></category>
            <dc:creator><![CDATA[Katerina]]></dc:creator>
            <pubDate>Thu, 15 Mar 2018 15:29:25 GMT</pubDate>
            <atom:updated>2022-07-19T21:01:19.647Z</atom:updated>
            <content:encoded><![CDATA[<p>My first programming language was Ruby. It was a great first language to start with because of its friendly syntax which let’s you focus on writing code to solve a problem.</p><p>One of the best things about Ruby is the Enumerable methods built into the language. What are the Ruby Enumerable methods? They are built in functions which you can use to manipulate data in various ways.</p><p>Instead of having to write the syntax of a <strong>for loop</strong> to go through each number in an array and add 1 to it, you can use the Enumerable method <strong>.map </strong>and give it a block of code to work with:</p><pre>numbers = [1, 2, 3]</pre><pre>numbers.map { |number| number + 1 }</pre><pre>=&gt; [2, 3, 4]<br></pre><p>Ruby makes it easy to manipulate data using the Enumerable functions. They are extremely powerful when you know what Enumerable function you need and what you want it to do.</p><p>To achieve similar outcomes in Java, it’s a little more tricky. What you can do in a relatively pain free way in Ruby takes a lot more lines of code in Java.</p><p>In the example below, you will see a standard loop in Java. As you can see, it’s a lot more complex than Ruby. However, there is a way you can attempt to simplify the loop and that’s with Java Streams.</p><pre>private int boardSize = 3;<br>private int gridSize = 9;</pre><pre>private List&lt;Mark&gt; createGrid() {</pre><pre>  List&lt;Mark&gt; spaces = new ArrayList&lt;&gt;();<br>  for (int i = 0; i &lt; gridSize; i++) <br>    spaces.add(EMPTY);<br>  }</pre><pre>  return spaces;<br>}</pre><pre>-  -  -  -  -  -  -  -  -<br><strong>Simplified using streams:<br></strong>-  -  -  -  -  -  -  -  -</pre><pre>public List&lt;Mark&gt; createGrid() {<br>  return Stream.generate(() -&gt; EMPTY)<br>               .limit(gridSize);<br>               .collect(Collectors.toList());     <br>}</pre><p>In the example above, the streams seem to simplify the code and make it more human to read. In Java, there are no Enumerable methods but the operations that you can use on streams provide similar functionality.</p><p>To use the stream operations you have to convert your array to a stream. In this example I’m generating a new stream. It’s created with each space equal to <strong>EMPTY</strong> and the limit of the array being <strong>9</strong>.</p><p>I then need to convert the data in the stream back to an array which is why using <strong>.collect</strong> is necessary at the end. This is another upside for Ruby which let’s you manipulate an array without converting it to a stream first.</p><pre>public boolean hasAvailableMoves() {<br>  int count = 0;<br>  for (Mark space : this.grid) {<br>    if (spaceIsTaken(space)) {<br>      count++;<br>    }        <br>  }<br>  return count != grid.size();   <br>}</pre><pre>-  -  -  -  -  -  -  -  -<br><strong>Simplified using streams:<br></strong>-  -  -  -  -  -  -  -  -<br> <br>public boolean hasAvailableMoves() {<br>  return this.grid.stream()<br>                  .anyMatch(space -&gt; space.equals(EMPTY));     <br>}</pre><p>The example above is another way that using streams simplified my original code. I had a for loop which checked each space in the grid to see if it was taken or empty. If the space was taken then the counter incremented by 1.</p><p>At the end I checked whether the counter was the size of the grid. If it was then there would be no spaces left. If the counter is less than the grid size then there are spaces left.</p><p>When converting this loop to a stream, I was able to use the anyMatch() operation. This checks a given condition and returns <strong>true </strong>if any elements in the array meet that condition.</p><p>This eliminated code like the counter and the general syntax for the loop which overcomplicated the method.</p><p>Yet, although streams can simplify your code in some places, they can overcomplicate it too. This is exactly what happened when I converted my nested for loops to streams.</p><p><strong>*Disclaimer*</strong></p><p><em>I am aware that these for loops are pretty horrible to look at. However, for the sake of this example it’s necessary to show the nested for loops in this way.</em></p><pre>private int boardSize = 3;</pre><pre>private List&lt;Line&gt; rowLines() {         <br>  List&lt;Line&gt; rows = new ArrayList&lt;&gt;();         <br>  for (int i = 0; i &lt; grid.size(); i += boardSize) {<br>    ArrayList&lt;Mark&gt; rowElements = new ArrayList&lt;&gt;();<br>    for (int j = 0; j &lt; boardSize; j++) {<br>      rowElements.add(grid.get(i + j));<br>    }<br>    rows.add(new Line(rowElements));<br>  }         <br>  return rows;     <br>}</pre><pre>-  -  -  -  -  -  -  -  -  -<br><strong>&quot;Simplified&quot; using streams:<br></strong>-  -  -  -  -  -  -  -  -  -</pre><pre>private List&lt;Line&gt; rowLines() {<br>  List&lt;Line&gt; rows = new ArrayList&lt;&gt;();     <br>  IntStream.<em>iterate</em>(0, i -&gt; i &lt; grid.size(), i -&gt; i + boardSize)<br>           .forEach(i -&gt; rowElements(rows, i));<br>  return rows;<br>}<br><br>private void rowElements(List&lt;Line&gt; rows, int i) {<br>  List&lt;Integer&gt; indicesForRow = <em>range</em>(0, size).boxed()<br>                                              .collect(<em>toList</em>());<br>  List&lt;Integer&gt; rowIndices = indicesForRow.stream()<br>                                          .map(element-&gt; element+i)<br>                                          .collect(<em>toList</em>());<br>  List&lt;Mark&gt; rowMarks = rowIndices.stream()<br>                                  .map(element -&gt; grid.get(element))<br>                                  .collect(<em>toList</em>());<br>  rows.add(new Line(rowMarks));<br>}</pre><p>It’s difficult to know where to begin when describing the code above. The original for loops and the streams themselves are both very complicated.</p><p>In the first loop, to get the rows we need the elements 0, 3 and 6, the row index need to start at 0 and go up by the board size each time.</p><p>Once we have the a way of getting each row then there needs to be a way of getting each of elements in that row, which is what second loop does. Starting at 0 then incrementing by 1 each time until it no longer is less than 3.</p><p>So it creates a dynamic array for the elements at index 0, 1 and 2.</p><pre>| 1 | 2 | 3 |<br>  -   -   -  <br>| 4 | 5 | 6 |<br>  -   -   - <br>| 7 | 8 | 9 |</pre><p>Lastly, in the empty <strong>rows</strong> array it adds the result of each index from the first loops and each index from the second.</p><pre>rows = asList(0, 3, 6);<br>rowElements = asList(0, 1, 2);</pre><pre><strong>rowElements.add(grid.get(i + j));</strong></pre><pre>The first element from the row indices which is 0 will enter the second loop then get added to the first element from the second loop which is also 0 =&gt;  0 + 0 = 0. The result of the addition is added to the rowElements array.</pre><pre>0 + 0 = 0<br>0 + 1 = 1<br>0 + 2 = 2</pre><pre>Once exiting the second loop, a new instance of a Line is created and all the values from rowElements are added to the rows array.</pre><pre><strong>rows.add(new Line(rowElements));</strong></pre><p>This is done for each row until finally the first loop is exited and the rows array is full of three other arrays containing each of the row elements.</p><p>There’s no one size fits all and streams are not always helpful. In the above case I find the for loop more understandable. Perhaps by extracting some of the for loops into named methods could help improve clarity in a way that the streams fail to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5456bc3f1ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursion strikes back —]]></title>
            <link>https://medium.com/@katerinaCodes/recursion-strikes-back-beffe120008e?source=rss-19ac9a6e729f------2</link>
            <guid isPermaLink="false">https://medium.com/p/beffe120008e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[factorials]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Katerina]]></dc:creator>
            <pubDate>Thu, 01 Mar 2018 09:42:23 GMT</pubDate>
            <atom:updated>2018-03-01T09:54:36.024Z</atom:updated>
            <content:encoded><![CDATA[<h3>Factorial sequence in Java</h3><p>Two of my stories this week were to experiment with recursion in Java. I got introduced to recursion when I was programming in Ruby and wrote <a href="https://medium.com/@katerinaldg/recursion-recursion-recursion-9fe87ada4a3c">this blog post</a> with a basic example of how recursion works.</p><p>My first story was to write a program to work out the <a href="https://github.com/Katerina-codes/factorial_kata_java/blob/master/src/test/factorial/FactorialTest.java">factorial</a> of a given number. Wikipedia defines a factorial as follows:</p><pre>the <strong>factorial</strong> of a <a href="https://en.wikipedia.org/wiki/Non-negative_integer">non-negative integer</a> <em>n</em>, denoted by <em>n</em>!, is the <a href="https://en.wikipedia.org/wiki/Product_(mathematics)">product</a> of all positive <a href="https://en.wikipedia.org/wiki/Integer">integers</a> less than or equal to <em>n</em>.</pre><pre>5! = 5 X 4 X 3 X 2 X 1 = 120.</pre><p>I test drove the code which gave me a basis to start from and I started with zero. The factorial of zero equals one which to be honest is quite confusing. When looking up why this is the case, most of the internet seems to say “because it is”. I believe the actual reason for this is so that when doing 1! the factorial can be one and not zero.</p><pre>public class FactorialTest {<br>  @Test<br>  public void zero() { <br>    assertEquals(1, factorial(0));    <br>  }<br>}</pre><p>For the factorial of zero and one the code was very simple, I needed to return that number.</p><pre>private int factorial(int i) {<br>  return 1;<br>} </pre><p>I then did a basic if statement to handle two:</p><pre>private int factorial(int i) {<br>  if (i &lt; 2) {<br>    return 1;<br>  } else {            <br>    return 2        <br>  }     <br>}</pre><p>When it came to doing the factorial of three I was forced to write the actual formula is:</p><pre>until current number is equal to 1<br>current number * (current number - one)  </pre><p>My task was to use recursion to get the factorial. This meant I needed to call the same method from within my method whilst reducing the current number. To stop my method from recursing I needed a base case which was:</p><p><strong><em>i &lt;= 1</em></strong></p><p>My code for this formula looked like this:</p><pre>private int factorial(int i) {<br>  return i &lt;= 1? 1 : i * (factorial(i - 1));<br>}</pre><p>I enjoyed doing this factorial program as it made recursion seem a little less scary. I then went on to do a Fibonacci program using recursion. This program is a little bit more complicated still relatively easy to break down.</p><p>You can read about my Fibonacci program <a href="https://medium.com/p/e3f0ecbfd55b/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beffe120008e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fibonacci in Java]]></title>
            <link>https://medium.com/@katerinaCodes/fibonacci-in-java-e3f0ecbfd55b?source=rss-19ac9a6e729f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3f0ecbfd55b</guid>
            <category><![CDATA[fibonacci]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Katerina]]></dc:creator>
            <pubDate>Thu, 01 Mar 2018 09:39:00 GMT</pubDate>
            <atom:updated>2018-03-01T09:39:00.519Z</atom:updated>
            <content:encoded><![CDATA[<pre>The Fibonacci number sequence starts with 0 and 1 then every subsequent number is the sum of the previous two. Thus, the first 10 numbers in the sequence are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.</pre><p><a href="https://medium.com/@katerinaldg/fibonacci-is-no-friend-of-mine-f2ca393706d7">I wrote about the Fibonacci sequence</a> early in my apprenticeship and at the time I was not a fan of how it was realised in code. This was probably because I overcomplicated the process of how to get the Fibonacci sequence.</p><p>Having recently finished doing the <a href="https://medium.com/p/beffe120008e">factorial sequence in Java</a>, I felt a lot more comfortable when doing the <a href="https://github.com/Katerina-codes/fibonacci_java">Fibonacci sequence in Java</a>.</p><p>The formula for the sequence is:</p><pre><strong><em>Fn = Fn-1 + Fn-2</em></strong></pre><p>I started with zero again for this:</p><pre>@Test<br>public void zero() {<br>  assertEquals(0, fibonacci(0));    <br>}</pre><p>The code for Fibonacci zero and one was the same:</p><pre>private int fibonacci(int i) {<br>  return i;<br>}</pre><p>When it gets to to Fibonacci three which is the sum of Fibonacci 2 (number 1) and Fibonacci 1 (number 1) then I was forced to write the recursive formula.</p><pre>until the current number is less than 1<br>current number = current number - 1 + current number - 2</pre><p>The code for this would be as follows:</p><pre>private int fibonacci(int i) {<br>  return i &lt;= 1 ? i : fibonacci(i - 1) + fibonacci(i - 2);    <br>}</pre><p>In the original code I wrote to solve this problem, I used an if statement. I then changed then replaced the if statement with a turnery operator. This seemed to be a more concise way to achieve the same thing and in this case it made the code quicker to read and digest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3f0ecbfd55b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Danger of Static]]></title>
            <link>https://medium.com/@katerinaCodes/the-danger-of-static-5099327a8ed5?source=rss-19ac9a6e729f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5099327a8ed5</guid>
            <category><![CDATA[learning-to-program]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[static-code]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Katerina]]></dc:creator>
            <pubDate>Thu, 18 Jan 2018 09:04:43 GMT</pubDate>
            <atom:updated>2018-01-18T09:06:32.527Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I have been looking into Static fields and methods in Java and the controversy which seems to surround them. To help me understand more about why static can be dangerous to use I decided to make a small program and test out some ideas.</p><p>The examples I am using are deliberately contrived so I can highlight the issues that coincide with using static code.</p><p>I made a Pony class on which I created a static class variable called <strong>age</strong> and gave it the value of <strong>10</strong>. My test was green, the method returned what I expected.</p><pre><strong>public class </strong>Pony {<br><br>    <strong>public static int </strong><em>age </em>= 10;<br><br>    <strong>public int </strong>doubleAge() {<br>        <strong>return </strong><em>age </em>*= 2;<br>    }<br>}</pre><pre><br>My test for this was very simple:<br></pre><pre>@Test<br><strong>public void</strong> doublePonyAge() {<br>    Pony pony = <strong>new </strong>Pony();<br><br>    <em>assertEquals</em>(20, pony.doubleAge());<br>}</pre><p>I then created a Unicorn class and had it use Pony’s static <strong>age</strong> class variable inside its own method <strong>triplePonyAge()</strong>.</p><pre><strong>public class </strong>Unicorn {</pre><pre><strong>    public int </strong>triplePonyAge() {<br>        <strong>return </strong>Pony.<em>age </em>*= 3;        <br>    }</pre><pre>}</pre><pre>My test for this was also very simple:</pre><pre>@Test<br><strong>public void </strong>triplePonyAge() {<br>    Unicorn unicorn = <strong>new </strong>Unicorn();<br><br>    <em>assertEquals</em>(30, unicorn.triplePonyAge());<br>}</pre><p>However, my test didn’t pass because my assertion was wrong. In my Pony test I had called the function <strong>doublePonyAge()</strong> which manipulated <strong>age </strong>by using<strong> *=</strong>. The value of age was no longer 10, it was 20. Therefore, <strong>triplePonyAge()</strong> actually returned 60 not 30 as I had asserted.</p><p>Things went from being relatively simple to suddenly being out of hand. There were very few methods and it was the earliest stage of my program but already it was difficult to keep track of the state of the <strong>age</strong>. By making <strong>age</strong> static, I was giving classes the ability to manipulate it at will which created global state for <strong>age</strong>.</p><p>On a program this small, it’s not too problematic to fix but at scale, it’s easy to see how this can become nightmarish and difficult to keep track of what the state is and should be.</p><p><strong>The main take aways I took from this small program were:</strong></p><ol><li>Mutable state can be confusing and if it can be avoided, it should be.</li><li>Use static in moderation. There was no need for my Unicorn class to access pony’s <strong>age</strong> and manipulate it. The less classes know about each other the less opportunities there are for your code to do something unexpected. To fix this issue by A<strong>ge</strong> class variable should have been non-static and classes should only be able to interact with it, nothing more.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5099327a8ed5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>