<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Jules</title>
    <description>The latest articles on DEV Community by Jules (@jules001).</description>
    <link>https://dev.to/jules001</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F325573%2F439b0bfa-453c-49c6-8481-16c0bfa5588e.jpg</url>
      <title>DEV Community: Jules</title>
      <link>https://dev.to/jules001</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/jules001"/>
    <language>en</language>
    <item>
      <title>Making my Ruby 'Legacy Code' SOLID</title>
      <dc:creator>Jules</dc:creator>
      <pubDate>Tue, 07 Apr 2020 10:57:57 +0000</pubDate>
      <link>https://dev.to/jules001/making-my-ruby-legacy-code-solid-5f6i</link>
      <guid>https://dev.to/jules001/making-my-ruby-legacy-code-solid-5f6i</guid>
      <description>&lt;p&gt;Several weeks ago I was working on a TicTacToe game in Ruby, but then I moved on to Java for a while. Now I've returned, full of type-security and  compiler error handling, and hopefully some transferrable things too. There's plenty to look at, but I'll just be working through a single example for each SOLID principle.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dependency Inversion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I'm starting with the 'D' in SOLID because when I came back to this project I noticed how tightly coupled the whole thing was, making any change very difficult. Most classes instantiated others instead of having them injected, so that was the first thing I changed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvxg9bvbvkhghtgxq1b5r.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvxg9bvbvkhghtgxq1b5r.gif" alt="Small knot" width="245" height="230"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Take a look at this test for my &lt;code&gt;Game&lt;/code&gt; class. It makes an instance of &lt;code&gt;Game&lt;/code&gt;, refers to both &lt;code&gt;Board&lt;/code&gt; and &lt;code&gt;ConsoleInOut&lt;/code&gt;, and fixes the &lt;code&gt;gets&lt;/code&gt; result of &lt;code&gt;ConsoleInOut&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Before&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;require 'game'

describe Game do
    it 'Asks for board size input' do
        allow_any_instance_of(ConsoleInOut).to receive(:gets).and_return('4')
        game = Game.new
        expect(game.board.board_size).to eq 4
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;How do we know that &lt;code&gt;Game&lt;/code&gt; contains instances of these classes? How do we change their input and output? We don't and we can't (unless you count &lt;em&gt;allow_any_instance_of&lt;/em&gt; as changing input).&lt;br&gt;
We have an opaque bundle of prima-donna classes that insist the tests be written around them. Let's change that by instantiating all of &lt;code&gt;Game&lt;/code&gt;'s dependencies externally and then injecting them on instantiation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;After&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;require 'game'

describe Game do
    before(:each) do
        @inOut = ConsoleInOut.new('', '')
        @player_x = Player.new('Player 1', 'X')
        @player_o = Player.new('Player 2', 'O')
    end

    it 'Asks for board size input' do
        board = Board.new(@inOut, 4)
        game = Game.new(@inOut, @player_x, @player_o, board)
        expect(game.board.board_size).to eq 4
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we know exactly what &lt;code&gt;Game&lt;/code&gt; contains, because we passed them in, and this allows us to change the parameters of these classes beforehand. For example, when we pass in a &lt;code&gt;ConsoleInOut&lt;/code&gt; instance, we can replace STDIN with a string to simulate input, and STDOUT with a string so that the test output isn't polluted by every print method.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Single Responsibility&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Classes shouldn't have more than one responsibility, plain and simple. There are more technical explanations out there, but it's enough so say that my &lt;code&gt;ConsoleInOut&lt;/code&gt; class is both getting input and validating it.&lt;/p&gt;

&lt;p&gt;It works, but if I were to swap out &lt;code&gt;ConsoleInOut&lt;/code&gt; for, say, &lt;code&gt;WebInOut&lt;/code&gt;, I'd need to reimplement validation as well as Input/Output.&lt;/p&gt;

&lt;p&gt;Since &lt;code&gt;Game&lt;/code&gt; will always get the same input, there's no reason to ever change validation, so let's go ahead and put it in the &lt;code&gt;Game&lt;/code&gt; class that handles interactions between classes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Before&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ConsoleInOut
    def initialize(input, output)
        @input = input
        @output = output
    end

    def get_input
        #
    end

    def print(to_print)
        #
    end        

    def select_move(max_turns)
        print("Please enter a free number from 1-#{max_turns}")
        player_input = gets.chomp.to_i
        valid_player_input(player_input, max_turns)
    end

    def valid_player_input(player_input, max_turns)
        player_input &amp;gt;= 1 &amp;amp;&amp;amp; player_input &amp;lt;= max_turns ? player_input : 
        select_move(max_turns)
    end

    # And some similar select/validate methods
end

class Game

    # And the rest of the Game

    def submit_move
        player_input = @inOut.select_move(@board.max_turns)
        @board.make_move(current_player.mark, player_input - 1)
        @board.view_board
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;After&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ConsoleInOut
    def select_move
        player_input = gets.chomp.to_i
    end

    # Remove valid_player_input, rest is the same
end

class Game

    # The rest is the same

    def submit_move
        valid_move = false
        until(valid_move)
            @inOut.print("Please enter a free number from 1-#{@board.max_turns}\n")
            player_input = @inOut.select_move(@board.max_turns)
            valid_move = @board.is_square_free?(player_input - 1)
        end
        @board.make_move(current_player.mark, player_input - 1)
        @board.view_board
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now &lt;code&gt;ConsoleInOut&lt;/code&gt; just gets input for &lt;code&gt;Game&lt;/code&gt;, without knowing or caring what happens next. &lt;code&gt;Game&lt;/code&gt; is now a bit bigger, but more complete, and validation is functionality that shouldn't ever need changing. As a bonus, if anything goes wrong with input and validation, it's easier to place the blame.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi3ccgbxui0ilgmfzl6b1.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi3ccgbxui0ilgmfzl6b1.gif" alt="One job" width="268" height="244"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Open/Closed&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I'm going to be very daring and use a metaphor now:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;A gaming console or desktop computer is complete in itself.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It doesn't need a particular screen to work, just &lt;em&gt;a&lt;/em&gt; screen, and the HDMI port lets you plug it into a huge range of screens without changing anything else.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If one screen breaks, the console still works, just find a new screen.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;But if you took out the port and built-in a screen, it would be less modifiable, and the screen breaking would be serious.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Your code should have more 'ports' and fewer 'built-ins'. Metaphor over, promise that's the only one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So...&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the case of a program, it should be be complete and closed to changes, yet open for new features to be added.&lt;/p&gt;

&lt;p&gt;If I were to add a Computer Player to my game, it would require rewriting the game so that the Computer could choose to make a move without console input.&lt;/p&gt;

&lt;p&gt;In order to make the program open to extension, it is necessary to create a seam by moving the responsibility of selecting a move to the &lt;code&gt;Player&lt;/code&gt; class. Then, the core program will not require changes.&lt;/p&gt;

&lt;p&gt;Take the code above as a 'before' example for &lt;code&gt;Game&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Before&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Player
    attr_reader :id, :mark
    def initialize(id, mark)
        @id = id
        @mark = mark
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;After&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class HumanPlayer
    attr_reader :id, :mark
    def initialize(id, mark, inOut)
        @inOut = inOut
        @id = id
        @mark = mark
    end

    def make_move
        @inOut.select_move
    end
end

class Game

    # The rest is the same

    def submit_move
        valid_move = false
        until(valid_move)
            @inOut.print("Please enter a free number from 1-#{@board.max_turns}\n")
-----&amp;gt;      player_input = current_player.make_move
            valid_move = @board.is_square_free?(player_input - 1)
        end
        @board.make_move(current_player.mark, player_input - 1)
        @board.view_board
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now that the instance referred to by &lt;code&gt;current_player&lt;/code&gt; is responsible for returning a move, we can just swap out a now &lt;code&gt;Human_Player&lt;/code&gt; class to extend the program with a Computer player. See below.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Liskov Substitution&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Java, you can make sure that one class is substitutable for a similar one with interfaces or abstract classes. Ruby doesn't have that, but as a colleague is fond of saying, "we can keep the interface in our heads". An interface contains a list of methods that a class doing this particular job must have, but leaves the implementation up to each class. So instead of having an interface file and having the compiler enforce it, we will just imagine that that's going on.&lt;/p&gt;

&lt;p&gt;See the &lt;code&gt;HumanPlayer&lt;/code&gt; class and its tests below to see what we're working with.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Human Player&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class HumanPlayer
    attr_reader :id, :mark
    def initialize(id, mark, inOut)
        @inOut = inOut
        @id = id
        @mark = mark
    end

    def make_move
        @inOut.select_move
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Tests&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;require 'human_player'
require 'console_in_out'

describe HumanPlayer do

    before(:each) do
        inOut = ConsoleMock.new('3', '')
        @player = HumanPlayer.new('Player 1', 'X', inOut)
    end

    it 'Stores player name' do
        expect(@player.id).to eq('Player 1')
    end

    it 'Stores player name' do
        expect(@player.mark).to eq('X')
    end

    it 'Can make a move' do
        expect(@player.make_move(9)).to eq(3)
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;HumanPlayer&lt;/code&gt; class stores information (id and mark), and has a &lt;code&gt;make_move&lt;/code&gt; method. If this class implemented an interface, that interface might look like this. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Player Interface&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Player
    def initialize(id, mark)
    end

    def make_move(max_turns)
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;With the same methods, but no body, you can implement the functionality however suits you, and replace a generic &lt;code&gt;Player&lt;/code&gt; instance with any instance that fits this pattern.&lt;/p&gt;

&lt;p&gt;I've also added &lt;code&gt;max_turns&lt;/code&gt; to &lt;code&gt;make_move&lt;/code&gt; as I'm anticipating the computer using the &lt;code&gt;rand&lt;/code&gt; method in the initial implementation, so &lt;code&gt;HumanPlayer&lt;/code&gt; needs this to make the classes substitutable.&lt;/p&gt;

&lt;p&gt;Note: It's worth passing in an instance of the &lt;code&gt;Board&lt;/code&gt; class so that the computer has knowledge of the Board state, but for the sake of this example I'm keeping it short.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Computer Player&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ComputerPlayer
    attr_reader :id, :mark
    def initialize
        @id = 'Computer'
        @mark = 'O'
    end

    def make_move(max_turns)
        rand(max_turns)
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;To summarise, it doesn't matter how &lt;code&gt;Player&lt;/code&gt; or &lt;code&gt;ComputerPlayer&lt;/code&gt; work, just that they contain the same core methods. Want to add methods to one or the other? Fine, they will still conform to the Liskov Substitution Principle as long as they both have &lt;code&gt;make_move&lt;/code&gt; and store id and mark, since other classes refer to these.&lt;/p&gt;

&lt;p&gt;If I want to change how &lt;code&gt;HumanPlayer&lt;/code&gt; or &lt;code&gt;ComputerPlayer&lt;/code&gt; makes a move, I can do this without modifying &lt;code&gt;Game&lt;/code&gt;, and I can add a third option without changing &lt;em&gt;anything&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;We're nearly done.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interface Segregation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I don't have a specific code example for this principle, as this is a small program with two (imaginary) interfaces. The 'imaginary' is important; Ruby doesn't have interfaces, so if the idea is still unfamiliar to you, feel free to move on to the next section.&lt;br&gt;
Otherwise, I will briefly cover the idea behind the Interface Segregation Principle.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The Interface Segregation Principle states that more, smaller interfaces are better than fewer, larger interfaces. This is to prevent the forced implementation of unused methods by a client. In the case that the In/Out interface grew too large, it may be possible that a class implementing it didn't use all of its methods, but had to add them anyway to avoid compiler errors. Why should you add code that isn't used? You shouldn't, meaning this bloated interface should be broken up so that each class only contains methods it uses.&lt;/p&gt;

&lt;p&gt;It's also helpful to have smaller classes and interfaces to follow the Open/Closed Principle mentioned earlier; with fewer modifications necessary and more seams available, any future change is much easier.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;It's All Connected&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Interestingly there's overlap between the SOLID principles, so each of these improvements doesn't just improve the program in one way; having a Liskov Subsitution approved In/Out interface makes dependencies more manageable, as well as making the program open to extension. Furthermore, exporting &lt;code&gt;make_move&lt;/code&gt; functionality to a &lt;code&gt;Player&lt;/code&gt; better follows the Open/Closed Principle, narrows the responsibility of &lt;code&gt;Game&lt;/code&gt;, and paves the way for a Liskov Substitutable &lt;code&gt;computer_player&lt;/code&gt; class.&lt;/p&gt;

</description>
      <category>ruby</category>
      <category>solid</category>
    </item>
    <item>
      <title>Error handling in Java</title>
      <dc:creator>Jules</dc:creator>
      <pubDate>Fri, 20 Mar 2020 10:27:11 +0000</pubDate>
      <link>https://dev.to/jules001/error-handling-in-java-4d6b</link>
      <guid>https://dev.to/jules001/error-handling-in-java-4d6b</guid>
      <description>&lt;p&gt;Compiled languages are very needy, but at least you know before you deploy the code that you've accounted for most edge cases. However, this definitely comes under 'don't just do what the IDE suggests', which has caused me problems before now, so let's establish some appropriate error handling.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What's to be done&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Certain methods are more likely to fail than others, so to compile you have to use error-handling; in this case either &lt;code&gt;try/catch&lt;/code&gt; or &lt;code&gt;throws&lt;/code&gt; will get the job done.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Database {
    Connection connection;
    public Database(String databaseUrl) {
        Class.forName(org.postgresql.Driver);
        connection = DriverManager.getConnection(databaseUrl, "postgresUser", "postgresPassword");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Attempting to connect to a Postgresql database above will cause two compiler problems:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;forName() Unhandled exception: java.lang.ClassNotFoundException&lt;/li&gt;
&lt;li&gt;getConnection() Unhandled exception: java.sql.SQLException&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These can be solved together or separately with the solutions I mentioned above.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Try/catch&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Database {
    Connection connection;
    public Database(String databaseUrl) {
        try {
            Class.forName(org.postgresql.Driver);
            connection = DriverManager.getConnection(databaseUrl, "postgresUser", "postgresPassword");
        } catch(ClassNotFoundException | SQLException e) { // or just (Exception e)
            e.printStackTrace();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Throws&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Database throws ClassNotFoundException, SQLException { // or, again, just Exception
    Connection connection;
    public Database(String databaseUrl) {
        Class.forName(org.postgresql.Driver);
        connection = DriverManager.getConnection(databaseUrl, "postgresUser", "postgresPassword");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;But which! When?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let's quickly go over why this happens. The reason we need to handle anything is that there is a chance that one of the methods we're using will call &lt;code&gt;throws&lt;/code&gt;. The &lt;code&gt;forName()&lt;/code&gt; method comes with &lt;code&gt;throws&lt;/code&gt; built in, so we either have to say that the method in which we use it (in this case, &lt;code&gt;Database&lt;/code&gt;) could throw an error, or catch it.&lt;/p&gt;

&lt;p&gt;If we choose &lt;code&gt;throws&lt;/code&gt;, we're allowing the error to move on, and unless it is handled by another method - like a method that calls &lt;code&gt;Database&lt;/code&gt; - it will cause the program to terminate with an error message.&lt;/p&gt;

&lt;p&gt;However, when we use &lt;code&gt;try/catch&lt;/code&gt; we're saying:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Yes, this code is risky but &lt;code&gt;try&lt;/code&gt; it anyway&lt;/li&gt;
&lt;li&gt;If it throws an error we'll &lt;code&gt;catch&lt;/code&gt; it and do this instead. Usually 'do this instead' is an error message for the user.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And on top of &lt;code&gt;try/catch&lt;/code&gt; is &lt;code&gt;finally&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Whatever happens, we will do this afterwards&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;So...&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To condense this, &lt;code&gt;throw&lt;/code&gt; passes responsibility up to the next method to be handled (or ends the program if not handled eventually), and catch handles exceptions in a meaningful way now.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When to let it throw&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Tests are a good time. In JUnit, you can assert that a method throws an error in whatever case, and if you didn't plan for it to throw, then your tests won't pass and you'll find out quickly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Checked vs. Unchecked Exceptions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So far, everything we've covered has been about checked exceptions, which are exceptions found by the compiler before the program is run. There are also unchecked exceptions or 'Runtime Exceptions', which are only found when the program is running.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Checked Exception Examples&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Iterate {
    public static void main(String args[]) {
        String arr[] = {"Primo", "Two", "Third"}
        System.out.println(arr[10]);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The above will compile, but then throw an &lt;code&gt;IndexOutOfBoundsException&lt;/code&gt; as we're trying to access the tenth element of an array with only three items.&lt;/p&gt;

&lt;p&gt;Similarly, if you call an instance that hasn't been instantiated and get a &lt;code&gt;NullPointerException&lt;/code&gt;, that would be an unchecked exception. These exceptions should still be handled, you just won't have them pointed out by the compiler.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Checked exceptions are picked up by the compiler and must be handled. They tend to involve interactions outside of the program (reading files, database queries, input).&lt;/p&gt;

&lt;p&gt;Unchecked exceptions happen during runtime and should be handled, but won't prevent compilation. They are mostly problems within the program (null, type incompatibility, out-of bounds, dividing by zero).&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Repository Pattern</title>
      <dc:creator>Jules</dc:creator>
      <pubDate>Tue, 17 Mar 2020 11:25:49 +0000</pubDate>
      <link>https://dev.to/jules001/repository-pattern-42n8</link>
      <guid>https://dev.to/jules001/repository-pattern-42n8</guid>
      <description>&lt;p&gt;Design Patterns are a new idea to me, but the concept is easy enough to understand; it's a general, reusable solution to a commonly occurring problem. The idea came from an architect, Christopher Alexander, and has been adopted in software.&lt;/p&gt;

&lt;p&gt;All OO languages can work with classes to store and manipulate data, but a pattern would be a particular way of using objects to create and manipulate other objects that has been proven to work for a specific purpose. Let's take a look at the Repository Pattern.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What's a Repository?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A Repository has access to a collection of objects of a single class, on which you can perform CRUD operations.&lt;/p&gt;

&lt;p&gt;Eric Evans explained it in his book &lt;code&gt;Domain Driven Design&lt;/code&gt;: &lt;em&gt;A Repository represents all objects of a certain type as a conceptual set. It acts like a collection, except with more elaborate querying capability&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface ContactRepository() {

    void createContact(Contact contact)
    void removeContact(Contact contact)
    void updateContact(Contact contact)
    List query(Specification specification)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this Interface, notice that the methods used are CRUD methods, that they all take an object as their argument, and that the object is the same for each of them.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;query&lt;/code&gt; method is an exception. Assuming that you are working with a large set of data, potentially in a database, it's not feasible to load them all, all of the time. Instead, you load a specific one or group that match a query.&lt;br&gt;
To implement this, you need a &lt;code&gt;Specification&lt;/code&gt; object. If you wanted to query by date, the business layer could pass a Date object to the repository, which then returns the results matching that query.&lt;/p&gt;

&lt;p&gt;You would likely need other methods for functionality like returning objects before or after a specific date, and that's fine; just make more methods.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Business Objects and the Business Layer&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The data you are returning is known as a &lt;code&gt;business object&lt;/code&gt;, as it is complete in a business sense. Take an account or a user, both are complete ideas that may need to be understood and accessed by the &lt;code&gt;business layer&lt;/code&gt;. Importantly, the business layer doesn't care about how the data persists - so it could be in-memory or a DB - the only thing it cares about is storing and retrieving objects, which it does through the repository.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How is the Repository Pattern distinct from other patterns?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As previously stated, the Repository Pattern receives objects and queries using those objects, and only works with a single, complete business object.&lt;br&gt;
If instead you were using the Data Access Object (DAO) Pattern, you might not use a complete business object, so you might return more than a single type of object, and you might not query with objects, but with a variable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you're working with data like accounts, you can access those accounts from a class (business layer) by creating an intermediary class (repository) that understands accounts and only accounts. It CRUDs accounts, and can return them to the first class, which doesn't need to know how anything works as long as it gets what it wants.&lt;/p&gt;

&lt;p&gt;Business Layer &amp;lt;---&amp;gt; Repository &amp;lt;---&amp;gt; Storage&lt;/p&gt;

</description>
    </item>
    <item>
      <title>On the Open-closed principle (Decoupling &amp; Abstraction)</title>
      <dc:creator>Jules</dc:creator>
      <pubDate>Tue, 10 Mar 2020 12:30:55 +0000</pubDate>
      <link>https://dev.to/jules001/on-the-open-closed-principle-decoupling-abstraction-2eok</link>
      <guid>https://dev.to/jules001/on-the-open-closed-principle-decoupling-abstraction-2eok</guid>
      <description>&lt;p&gt;Here, I'll be tracking the abstraction of a Contact Manager that I've been decoupling, similar to the example in my post on Interfaces. The aim of this is to reach a point when I have a core program that needs no modification to add new functionality, but instead can be extended with new classes, per the second of the SOLID principles.&lt;/p&gt;

&lt;p&gt;As a program grows, it's important to keep an eye on its structure and spot opportunities for abstraction.&lt;br&gt;
If a class gains a few more functions, you might find, for example, that the single mention of the string name of a field becomes a regular reference, and that it's worth promoting a string to a variable, or a series of constants to a class.&lt;/p&gt;

&lt;p&gt;Unless it's important, I'll use abstract methods with no bodies. Below is the Contact class from my program, which stores data and modifies it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1 - Contact&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Contact {

public String FirstName;
// plus five more fields

public Contact(String firstName // five more here too) {
   this.FirstName = firstName;
    // plus five more fields
}

public updateFirstName(firstName) {
    if (!firstName.matches(String.valueOf(ValidateInput.blankString))) {
        FirstName = firstName;
    }
}
// plus five more almost identical update methods
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Immediately there are a couple of problems here. The first is that I've got six methods doing the same thing with only one variable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Abstraction Concept&lt;/strong&gt;: Repetition indicates that there's room for abstraction, so let's generalise these methods.&lt;/p&gt;

&lt;p&gt;The second is that the Contact class is responsible for both storing and modifying its own state. That's a lot of responsibility for what should be the computer equivalent of a card with six lines on it.&lt;/p&gt;

&lt;p&gt;It also means that the 'structure' of the program is really just a series of inseparable classes, as &lt;code&gt;ContactManager&lt;/code&gt; relies on &lt;code&gt;Contact&lt;/code&gt; when it tells it to update itself.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Abstract-ification Sequence&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ContactManager {

private ConsoleIO consoleIO;
private ArrayList&amp;lt;Contact&amp;gt; contactList;

public ContactManager(ConsoleIO consoleIO, ArrayList&amp;lt;Contact&amp;gt; contactList) {
   this.consoleIO = consoleIO;
   this.contactList = contactList;
}

public void updateField(String value, Contact contact, int field) {
    if (!value.matches(String.valueOf(ValidateInput.blankString))) {
        switch (field) {
            case 1: contact.FirstName = value; break;
            case 2: contact.LastName = value; break;
            case 3: contact.Address = value; break;
            case 4: contact.PhoneNumber = value; break;
            case 5: contact.DOB = value; break;
            default: contact.Email = value; break;
        }
    }
}
// and a lot of other methods
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And now &lt;code&gt;Contact&lt;/code&gt; is just&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Contact {

public String FirstName;
// same as before, 5 more

public Contact(String firstName) {
   this.FirstName = firstName;
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Much better. Now six methods are one, and the Contact class is 18 lines long, with the sole responsibility of storing information.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 2 - ConsoleIO&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Note: If you don't know about interfaces, scroll back up and see the other post in my Abstraction series.&lt;/p&gt;

&lt;p&gt;ConsoleIO is my class for handling input and output, specifically in the console.&lt;/p&gt;

&lt;p&gt;To implement the InputOutput interface I made, ConsoleIO needed four methods:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;display&lt;/li&gt;
&lt;li&gt;getStringInput&lt;/li&gt;
&lt;li&gt;getMenuInput&lt;/li&gt;
&lt;li&gt;confirmInput&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;My ConsoleIO class had the required four methods to implement the InputOutput interface, but it also had methods that validated the input. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ConsoleIO implements InputOutput{

public ConsoleIO()

public void display()

public String getStringInput()

public int getMenuInput()

public String getInput()

public static Boolean validateInput()

public static Boolean validName()

public static Boolean validNumber()

public static Boolean validDOB()

public static Boolean validEmail()

public static Boolean isBlank()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What had started as a method or two grew to six, and this class never really needed to know the rules for valid input. If this were a whiteboard, I'd draw a big circle around everything with &lt;code&gt;valid&lt;/code&gt; in it (and that last one too, close enough).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Abstractionise&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ConsoleIO implements InputOutput{

public ConsoleIO()

public void display(String message)

public String getStringInput()

public int getMenuInput()

public String getInput()
    // this method calls validation methods
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;ConsoleIO&lt;/code&gt; is back down to its core methods, and below we have a new class that doesn't even need to be initialised, since everything's static.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ValidateInput {

public final static Pattern blankString = Pattern.compile("^$");

public static Boolean validateInput(){
    // this one calls the ones below as appropriate
}

public static Boolean validName()

public static Boolean validNumber()

public static Boolean validDOB()

public static Boolean validEmail()

public static Boolean isBlank()

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Decoupling&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It's getting a lot easier to look at these classes and tell what they do. &lt;code&gt;ConsoleIO&lt;/code&gt; doesn't know what makes input valid, and &lt;code&gt;ValidateInput&lt;/code&gt; doesn't know where the input comes from or goes back to.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Decoupling Concept:&lt;/strong&gt; If a class isn't designed to handle other classes (like &lt;code&gt;ContactManager&lt;/code&gt; handles &lt;code&gt;Contact&lt;/code&gt;s), then it should know nothing about how it works. The less it knows, the less it relies on low-level details.&lt;br&gt;
Passing information from &lt;code&gt;ConsoleIO&lt;/code&gt; to &lt;code&gt;ValidateInput&lt;/code&gt; should be seen as a black-box, where input goes in, mysterious (see: abstract) doings occur, and then output comes out.&lt;/p&gt;

&lt;p&gt;It might seem that this isn't much of an improvement; that I've just moved methods from class 1 to class 2 and that class 1 still needs the methods of class 2. However, the value comes in that I can swap &lt;code&gt;ConsoleIO&lt;/code&gt; for a different InputOutput interface-based class like '&lt;code&gt;WebIO&lt;/code&gt;', and I don't need to repeat the validation methods.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Abstraction Concept:&lt;/strong&gt; Abstraction doesn't have to make a difference now, the value comes in facilitating future change. I've made room for future classes, but I don't need to know how they work.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;End Goal&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;While this program isn't finished, the examples I gave were basic changes that made incremental improvements now, and make future change much easier.&lt;/p&gt;

&lt;p&gt;The aim of this program is to reach a point where each class only knows just enough to do its part, so that I could swap out any class with another that follows an appropriate interface.&lt;/p&gt;

&lt;p&gt;What this achieves is maximum room for extension, without needing to anticipate any specific functionality. Using this on the web? Swap out ConsoleIO with the new WebIO.&lt;/p&gt;

</description>
      <category>java</category>
    </item>
    <item>
      <title>Interfaces Explained</title>
      <dc:creator>Jules</dc:creator>
      <pubDate>Mon, 09 Mar 2020 12:56:17 +0000</pubDate>
      <link>https://dev.to/jules001/interfaces-explained-3gje</link>
      <guid>https://dev.to/jules001/interfaces-explained-3gje</guid>
      <description>&lt;p&gt;In the quest to write Better Code, you will encounter many abstract concepts, the explanations of which are themselves often abstract. The idea of an Interface is a simple one when kept grounded in code, so that's how I'm addressing it here.&lt;/p&gt;

&lt;p&gt;Below is an interface in a Contact Manager I've been making in Java. It's a command-line application that stores information in memory. Instead of &lt;code&gt;class&lt;/code&gt; it says &lt;code&gt;interface&lt;/code&gt;, its methods have no body, and it contains no variables, although it can have final static fields.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface InputOutput {

    void display(String message);

    String confirmInput(String field, boolean isAnUpdate);

    int getNumberInput();

    String getInput(String detail);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;What does an Interface do?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Nothing. It's just a blueprint that you must adhere to.&lt;/p&gt;

&lt;p&gt;If I were to remove it and all mentions of it from my project, nothing would change. This isn't surprising, as the four methods it contains have no body. Because they're abstract/blueprint methods.&lt;/p&gt;

&lt;p&gt;However, since my ConsoleIO class (see Example 2) 'implements InputOutput', it must contain the methods  that the InputOutput interface contains. In other words, we're stating that InputOutput was used as a model around which the ConsoleIO class was made.&lt;/p&gt;

&lt;p&gt;It could also contain methods not specified in the interface, but it has to have those core ones.&lt;/p&gt;

&lt;p&gt;Example 2 shows the class that the InputOutput interface was modelled after (in this case, I made the class and extracted an interface after, but in the future I might start with an interface). It contains the same four methods, as well its own instance method and some variables. The difference is that the methods have bodies now, implementing details of the relevant functionality however I see fit.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 2&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ConsoleIO implements InputOutput {

private final InputStream input;
private final OutputStream output;
private final BufferedReader reader;
public final PrintStream printer;

public ConsoleIO(InputStream input, OutputStream output) {
    reader = new BufferedReader(new InputStreamReader(input));
    printer = new PrintStream(output);
    this.input = input;
    this.output = output;
}

public void display(String message) {
    printer.println(message);
}

public String confirmInput(String field, boolean isAnUpdate) {
    Boolean validInput = false;
    String userInput = null;
    while (!validInput) {
        userInput = getInput(field);
        validInput = ValidateInput.validateInput(field, userInput, isAnUpdate);
    }
    return userInput;
}

public int getNumberInput() {
    String userInput;
    try {
         userInput = reader.readLine();
    } catch (IOException e) {
        return - 1;
    }
    try {
        return Integer.parseInt(userInput);
    } catch (NumberFormatException e) {
        return 0;
    }
}

public String getInput(String detail) {
    display("Please enter your " + detail + ":");
    String userInput = null;
    try {
        userInput = reader.readLine();
    } catch (IOException e) {
        display("Cannot read line" + e);
    }
    return userInput;
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Let's Get Abstract&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;An interface doesn't handle anything concrete. It doesn't specify how the methods it contains are to be implemented, only that they should exist.&lt;/p&gt;

&lt;p&gt;The interface is a plan for future classes that will implement the same functionality in a different context.&lt;br&gt;
In this case, it's an InputOutput interface, so if in the future I add a class to my program so that it works online as well as in the command-line, it will need methods to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Display output&lt;/li&gt;
&lt;li&gt;Confirm input&lt;/li&gt;
&lt;li&gt;Get string input&lt;/li&gt;
&lt;li&gt;Get menu input&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Polymorphism&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 3&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Save {
   void saveNumber(String phoneNumber)
}

class File implements Save
    public void saveNumber(String phoneNumber) {
        // However you implement saving to a file
    }
}

class Database implements Save
    public void saveNumber(String phoneNumber) {
        // However you implement saving to a database
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Interfaces help create systems that implement polymorphism. The idea of polymorphism is that classes are interchangeable, so swapping an instance of class &lt;code&gt;File&lt;/code&gt; for one of &lt;code&gt;Database&lt;/code&gt; wouldn't matter, as they have the same methods.&lt;/p&gt;

&lt;p&gt;Let's say &lt;code&gt;Phonebook&lt;/code&gt; calls the &lt;code&gt;write&lt;/code&gt; method for either of these, injecting the relevant class as &lt;code&gt;destination&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;destination.saveNumber("5550123");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It would work either way, and the program wouldn't know or care where it's saving to.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Closing&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Interfaces are abstract because they serve as plans or reminders rather than having any real functionality. Languages like Ruby don't even have interfaces, but it helps to keep the idea of them in your mind when designing your system.&lt;/p&gt;

</description>
      <category>java</category>
    </item>
    <item>
      <title>Java Primitives vs. The Rest</title>
      <dc:creator>Jules</dc:creator>
      <pubDate>Tue, 03 Mar 2020 12:24:24 +0000</pubDate>
      <link>https://dev.to/jules001/java-primitives-vs-the-rest-7fl</link>
      <guid>https://dev.to/jules001/java-primitives-vs-the-rest-7fl</guid>
      <description>&lt;p&gt;"Friends don't let friends use Integer."&lt;/p&gt;

&lt;p&gt;Related to my last post about not making everything static and recursing through chained methods, a colleague offered the above maxim. And, also related, it was something low priority, but on my radar to look up when I had more time (because that's going to happen). The final connection was that I was once again making things harder for myself by using the wrong tool for the job.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why were you using Integer Jules?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Because I didn't know about the primitive &lt;code&gt;int&lt;/code&gt;. These distinctions don't exist in Ruby, so they didn't exist to me. Somebody had pointed out that using Integer would create issues, but it became an afterthought because it was 'working' now.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So what's the difference?&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Integer five = 5;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Integer is an object reference. When I declare &lt;code&gt;five&lt;/code&gt; as an Integer, I'm making a new object, with a value of 5, that I am passing by reference whenever I refer to &lt;code&gt;five&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int five = 5;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;int&lt;/code&gt; type is a primitive, which stores an actual value, instead of the reference to an object where the value is stored. This means slightly better performance when using primitives.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Does it really make a difference?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;An excerpt from Joshua Bloch's &lt;em&gt;Effective Java&lt;/em&gt; gives the following example:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static void main(String[] args) {
    Long sum = 0L; // uses Long, not long
    for (long i = 0; i &amp;lt;= Integer.MAX_VALUE; i++) {
        sum += i;
    }
    System.out.println(sum);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The above code takes 43 seconds to run because reference type Long is used. If you replace Long with long, it takes 6.8 seconds. Think of all of the objects you're creating just to refer to once.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 2&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Integer x = 1;
Integer y = 1;
return x == y; // false

int a = 1;
int b = 1;
return a == b; // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If using reference types, you end up comparing objects instead of values unless &lt;code&gt;.equals()&lt;/code&gt; is used.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So why use reference types?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Reference types let you work with useful methods like Map, List, and Set (pretty much any class method), which require an object. Objects like Integer also allow for &lt;code&gt;null&lt;/code&gt; values, should you need them.&lt;/p&gt;

&lt;p&gt;The important thing is to consider your needs, such as whether your program is going to require the option to use null with numbers, or whether you need to use certain class methods. Many class methods could be replicated to work with primitives if necessary, but you have options both with and without as it is.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;In summary, you have high-performance options in primitives, and options with greater functionality in reference types.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;More principles please&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It's easy to get so caught up in small details that you miss the big ideas, so I've found immense value already in the simplicity of "Friends don't let friends use Integer", and the more rounded "Only use Integer where int can't do the job" that has emerged from doing some research.&lt;/p&gt;

&lt;p&gt;I suppose that another good principle here is "Read the docs" as somebody already considered that it might be useful to have a basic understanding of the language so yeah, I'm going to go and read the docs over at &lt;a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/" rel="noopener noreferrer"&gt;https://docs.oracle.com/javase/tutorial/java/nutsandbolts/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Anyway, thanks for reading, and if you've got anything to add I'd love to hear it!&lt;/p&gt;

&lt;p&gt;P.S.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Extra Note Regarding Ruby&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The addition of new kinds of variables is not just helping me work with Java, but is also giving me insight into the kind of tradeoffs that you might make when working with a language like Ruby. In benchmark tests, Ruby is always near the bottom, and it's easy to see why when every bit of data is an object. But it is very nice to work with.&lt;/p&gt;

</description>
      <category>java</category>
    </item>
    <item>
      <title>Java 'Static' keyword - Intro: How (not) to use it</title>
      <dc:creator>Jules</dc:creator>
      <pubDate>Mon, 02 Mar 2020 11:38:31 +0000</pubDate>
      <link>https://dev.to/jules001/java-static-keyword-how-not-to-use-it-as-a-beginner-134l</link>
      <guid>https://dev.to/jules001/java-static-keyword-how-not-to-use-it-as-a-beginner-134l</guid>
      <description>&lt;p&gt;When do I use the static keyword? What does it do? Doesn't matter, the IDE is telling me where to add it!&lt;/p&gt;

&lt;p&gt;With that attitude, my Main class ended up looking like this:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Main {
    static Contact contact = new Contact();
    static Input input = new Input();

public static void main(String[] args) {
    showMenu();
}

public static void showMenu() {
    int menuChoice;
    menuChoice = input.menuChoice();
    switch (menuChoice) {
        case 1: updateContact();
        default: break;
    }
}

static void updateContact() {
    updateContactFields();
    showContact();
}

static void updateContactFields() {
    // lots of update calls
}

static void showContact() {
    // Lots of prints
    showMenu();
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It was a train-wreck for lots of reasons, but the static everything was causing problems I wasn't aware of.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bad move Jules&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I had priorities, and finding out what all of these (not so) generic keywords meant was low. Anyway, the program worked, and if I made a new method, IntelliJ told me that I couldn't reference a non-static method from a static context, so all of the methods became static.&lt;/p&gt;

&lt;p&gt;In the back of my head however, there was something bothering me;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The main method in a Java class must be static&lt;/li&gt;
&lt;li&gt;Every method I was using was directly or indirectly called through the main method&lt;/li&gt;
&lt;li&gt;Methods called by other classes didn't have to be static, but also could 
be&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So why was I adding this all of the time?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Blocker&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Eventually, a combination of using recursion where loops were better and making my entire class static caused problems with state that I couldn't debug. Someone familiar with Java took a quick look and asked me if I knew what static did.&lt;/p&gt;

&lt;p&gt;They described it, in Ruby terms, as making something a Class method or variable. I needed instance at most, but had unintentionally made everything global.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution/Example 2&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Main {

    Input input = new Input();
    ArrayList&amp;lt;Contact&amp;gt; contactList = new ArrayList&amp;lt;&amp;gt;();

public static void main(String[] args) {
    Main main = new Main();
    main.showMenu();
}

public void showMenu() {
    boolean complete = false;
    while (!complete) {
        printMenuOptions();
        int userInput = input.menuChoice();
        switch (userInput) {
            case 1: {
                newContact();
                break;
            }
            case 2: {
                updateExistingContact();
                break;
            }
            case 3: {
                showContact();
                break;
            }
            default:
                complete = true;
                break;
        }
    }
}

void printMenuOptions() {
    // logs
}

void newContact() {
    contactList.add(new Contact(input.confirmInput("first name"), input.confirmInput("last name"), input.confirmInput("address"), input.confirmInput("phone number"), input.confirmInput("DOB in dd/mm/yyyy format"), input.confirmInput("email")));
}

void updateExistingContact() {
    if (checkForContacts()) {
        displayContacts();
        try {
            updateContactFields(contactList.get(Integer.parseInt(input.confirmInput("contact choice")) - 1));
        } catch (Exception e) {
            System.out.println("No such contact");
        }
    }
}

boolean checkForContacts() {
    if (contactList.size() == 0) {
        System.out.println("There are no contacts yet");
        return false;
    } else {
        return true;
    }
}

void updateContactFields(Contact contact) {
    // logs and update calls
}

void showContact() {
    if (checkForContacts()) {
        displayContacts();
        Contact contact = null;
        try {
            contact = contactList.get(input.contactChoice() - 1);
        } catch (Exception e) {
            System.out.println("No such contact");
            showMenu();
        }
        printContactDetails(contact);
    }
}

void printContactDetails(Contact contact) {
    // lots of logs
}

void displayContacts() {
    System.out.println("Please select a contact");
    for (int i = 0; i &amp;lt; contactList.size(); i++) {
        System.out.println(i + 1);
    }
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;(Note: there's extra functionality here too)&lt;/p&gt;

&lt;p&gt;To avoid calling methods from the static method &lt;code&gt;main&lt;/code&gt;, you just:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Make an instance of the Main class in the main method&lt;/li&gt;
&lt;li&gt;Call any methods from that instance of Main (e.g. main.displayContacts())&lt;/li&gt;
&lt;li&gt;Now you only have to make things static where it's good practice&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;When should things be static?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I'm glad you asked: Let's say I have a list of contacts, and each of these contacts has several properties. In case they share a common property, the variable can be static to save memory.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Contact {
    String name;
    static String country = "Arstotzka";
    int age;
    // and so on
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If I have 10 Contact instances, the &lt;code&gt;name&lt;/code&gt; variable will be assigned memory 10 times. On the other hand, &lt;code&gt;country&lt;/code&gt; is static, so it's only given memory once, however many instances there are. It doesn't have to be static, but it's more efficient, memory-wise, to make it so.&lt;/p&gt;

&lt;p&gt;Notes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It can still be changed, but it's less likely to be changed than non-static variables.&lt;/li&gt;
&lt;li&gt;Static variables must also be initialised with a value, as you are saying that the variable and its value is inherent to the class.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Class Methods&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Class methods are used without instantiating the class, as was the case in Example 1. Main was never instantiated, so if I called any methods, they had to be class level instead of object level.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 3&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Contact {
    String name;
    static String country = "Arstotzka";
    int age;
    // and so on

    static void updateCountry() {
        country = "Republia";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The static method in Example 3 updates the static variable &lt;code&gt;country&lt;/code&gt;, so every instance of Contact will now have the string value 'Republia' instead of 'Arstotzka'.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Recap&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Static variables are class level variables, so are inherited by instances, and must be initialised before making an instance&lt;/li&gt;
&lt;li&gt;Static methods are class methods, and are called without the class being instantiated&lt;/li&gt;
&lt;li&gt;If you want to use instance methods, you need to instantiate your class (just now made the connection between instance variables/methods and instances of classes)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is far from exhaustive, but is information that would have saved me a lot of time and pain if I had done the research earlier.&lt;/p&gt;

&lt;p&gt;Let me know your thoughts, whether you think this is clear and useful, or I've missed something big and made some bad assertions!&lt;/p&gt;

</description>
      <category>java</category>
    </item>
    <item>
      <title>Thoughts on Java, Part 1</title>
      <dc:creator>Jules</dc:creator>
      <pubDate>Tue, 25 Feb 2020 09:01:55 +0000</pubDate>
      <link>https://dev.to/jules001/thoughts-on-java-part-1-3j5a</link>
      <guid>https://dev.to/jules001/thoughts-on-java-part-1-3j5a</guid>
      <description>&lt;p&gt;Tracking my thoughts and understanding of Java as my understanding grows.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Impressions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Words that are jumping out include 'structured' and 'arbitrary'. I've already written about my first impressions of type-safety, but this moves into new territory, like the different classes of strings.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Progress&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It's harder to predict how long tasks will take; Some things are very similar in implementation to Ruby, but with strings it's Apples and Oranges. Some strings are mutable, some are immutable, and trivial tasks like pushing strings to arrays has made me aware of the StringBuffer class, which does not return a string equal to that of the String class.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Closing&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Working with Java has meant dealing with things I didn't know existed, so assuming that the OO similarities make up for being static, typed, and compiled was wishful thinking. I'm starting from the beginning again, only the beginning is harder here. It's a lesson in humility.&lt;br&gt;
I'm learning a lot though, and I think that once the basics are down, things will seem clear, and I'll be a better programmer for having learned to do it this way.&lt;/p&gt;

</description>
      <category>java</category>
    </item>
    <item>
      <title>Why is Software/Tech such an attractive industry?</title>
      <dc:creator>Jules</dc:creator>
      <pubDate>Sun, 23 Feb 2020 14:56:23 +0000</pubDate>
      <link>https://dev.to/jules001/why-is-software-tech-such-an-attractive-industry-39c3</link>
      <guid>https://dev.to/jules001/why-is-software-tech-such-an-attractive-industry-39c3</guid>
      <description>&lt;p&gt;&lt;strong&gt;Symptoms of a good thing&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Things like remote-working and flexible hours are symptomatic of an industry that is good for workers, but you could stick those perks to an unattractive industry and not change it for the better. So...&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Causes&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Novelty. Engineering is not new, but the medium is. That's not to say that there are no old ideas holding practitioners back, but there's a lot of forward focus. Computing courses don't have modules on the Michelangelos and Da Vincis of programming, so we move forward, challenging current and old practices.&lt;/p&gt;

&lt;p&gt;Possibility. If I were to begin a woodworking, blacksmithing, architectural, or pretty much any other making-things based project right now, I would have to make considerations for budget, materials, tools, and other limiting factors.&lt;br&gt;
With my mid-range computer in front of me, it's more a 'the only limit is your imagination' kind of scenario, with notable exceptions like data science.&lt;br&gt;
I can start my project on GitHub, use a free IDE to program in a free language and all of its free libraries, use some free (or free for the first thousand calls a day) web-services to host a website, keep a database, authenticate requests, and even do some machine learning tasks.&lt;/p&gt;

&lt;p&gt;Accessibility. Do you have a computer? With an internet connection? Good enough. &lt;br&gt;
As well as having an open source community with all of the tools you need for a long time, there are blog posts guiding you through getting a website hosted for free in half an hour. There are many websites dedicated to teaching you how to program for free, with some high-quality paid courses for not a lot of money. Stuck on a problem? Ask Stack Overflow.&lt;/p&gt;

&lt;p&gt;Intangibility. Like I said, this isn't woodworking, or anything physical (unless you want to work with RaspberryPi or another microprocessor), so the work is wherever you are. Want someone to help from the other side of the world? Timezones are your biggest barrier, big deal. No work in your city? Work remotely.&lt;br&gt;
All of these things are easier said than done, but for many other industries these points are non-starters, or at best a Friday treat.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sum it up&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A new and unique combination of possibility, low barrier to entry, and minimal physical restrictions make for something that is only limited by the people within it, and they're usually willing to help.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Thoughts on Craft, Part 1</title>
      <dc:creator>Jules</dc:creator>
      <pubDate>Sun, 23 Feb 2020 14:56:08 +0000</pubDate>
      <link>https://dev.to/jules001/thoughts-on-craft-part-1-30a0</link>
      <guid>https://dev.to/jules001/thoughts-on-craft-part-1-30a0</guid>
      <description>&lt;p&gt;A series tracking my thoughts on Software Craftsmanship as they develop.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Get some words down there&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Hackathons, hackjams, meetups, conferences, and so on. Open Source communities, Hacker News, heated discourse on whether Agile actually works, stuff like that.&lt;/p&gt;

&lt;p&gt;That's all stuff that makes me think that people care about what they do, and care about being better, however good they already are. I've attended talks from people who claim to exclusively pair-program, and others who love working with Clojure despite the fact that it's Clojure. There are a lot of talks generally, with lots of passion and ideas flowing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Boil it down, now&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;What I'm getting at is that Software Development presents more as a vocation or a life choice than a career. There's a thriving community, where experienced professionals give up free time to learn and teach.&lt;/p&gt;

&lt;p&gt;Nothing I've listed is unique to this industry, but it's all so pervasive that it makes a unique industry.&lt;/p&gt;

</description>
      <category>craft</category>
      <category>craftsmanship</category>
    </item>
    <item>
      <title>Type-Safety, it's pretty nice</title>
      <dc:creator>Jules</dc:creator>
      <pubDate>Fri, 21 Feb 2020 17:22:46 +0000</pubDate>
      <link>https://dev.to/jules001/type-safety-it-s-pretty-nice-lh5</link>
      <guid>https://dev.to/jules001/type-safety-it-s-pretty-nice-lh5</guid>
      <description>&lt;p&gt;Okay, short one.&lt;br&gt;
I'm used to programming in Ruby where anything goes and you fix stuff later. The ultimate procrastination.&lt;/p&gt;

&lt;p&gt;That said, it's surprising how useful I'm finding strongly-typed methods and variables; it's like having comments everywhere saying what my program's doing and makes me think about design more. When I can see that this method returns a string, but the one it calls is boolean-y, I'm encouraged to consider how they interact more.&lt;/p&gt;

&lt;p&gt;Even if it doesn't change what I do now, it saves a lot of time when refactoring, and the tests don't even have to run for me to find out that square pegs don't go in round holes.&lt;/p&gt;

&lt;p&gt;Long and short, restrictions keep things structured, and Java's working out well (enough).&lt;/p&gt;

&lt;p&gt;Done.&lt;/p&gt;

</description>
      <category>java</category>
    </item>
    <item>
      <title>The Right Way vs. the Easy Right Way</title>
      <dc:creator>Jules</dc:creator>
      <pubDate>Fri, 21 Feb 2020 09:35:42 +0000</pubDate>
      <link>https://dev.to/jules001/the-right-way-vs-the-easy-right-way-61n</link>
      <guid>https://dev.to/jules001/the-right-way-vs-the-easy-right-way-61n</guid>
      <description>&lt;p&gt;&lt;strong&gt;360 No Gradle&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I've always leant towards doing things the 'right' way even if it's slightly harder than doing it the easy way, so imagine my joy when I'm assigned a Java project without the use of an IDE or package managers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How's that working out?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Nothing's working and I don't know why.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Will you ever do it again?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Probably not.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What about Java itself?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It's early to say, but the language differences don't seem as big as the general project management differences (when compared to Ruby or JavaScript).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Notes for anyone trying the same thing&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Look up setting CLASSPATH to .jar files (for junit and hamcrest)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Wrap it up&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;What I've picked-up here is that the barrier to entry for test-driving Java programs is much higher when done the hard way. If IntelliJ or Gradle/Maven cuts any of that out in the future (and according the web results, things always 'just work' when using those tools) then I can mark that experiment as done and move on.&lt;/p&gt;

</description>
      <category>java</category>
      <category>testing</category>
    </item>
  </channel>
</rss>
