<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java &#8211; Chris Philbin&#039;s Blog</title>
	<atom:link href="https://www.chrisphilbin.net/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.chrisphilbin.net</link>
	<description>Perfection Through Persistence.</description>
	<lastBuildDate>Wed, 04 Sep 2024 00:36:25 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.2</generator>
	<item>
		<title>A Brief Overview of Garbage Collection in Java</title>
		<link>https://www.chrisphilbin.net/a-brief-overview-of-garbage-collection-in-java/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 04 Sep 2024 00:19:39 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://www.chrisphilbin.net/?p=555</guid>

					<description><![CDATA[Garbage collection, or the concept of essentially &#8220;cleaning up&#8221; no longer referenced spots in memory, is something that we take for granted when writing code in Java since this is&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Garbage collection, or the concept of essentially &#8220;cleaning up&#8221; no longer referenced spots in memory, is something that we take for granted when writing code in Java since this is more or less done for us by the Java Virtual Machine (JVM). Languages like C and C++ on the other hand require that the developer also handle their own garbage clean up. Some argue that handling your own garbage collection gives you maximum control, while others argue that a developer&#8217;s time can be better spent elsewhere if the language already takes care of this for you, especially if system memory is no longer something that was very limited in years prior.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img fetchpriority="high" decoding="async" width="892" height="480" src="https://www.chrisphilbin.net/wp-content/uploads/2024/09/garbage_collection.jpg" alt="" class="wp-image-560" style="width:577px;height:auto" srcset="https://www.chrisphilbin.net/wp-content/uploads/2024/09/garbage_collection.jpg 892w, https://www.chrisphilbin.net/wp-content/uploads/2024/09/garbage_collection-300x161.jpg 300w, https://www.chrisphilbin.net/wp-content/uploads/2024/09/garbage_collection-768x413.jpg 768w" sizes="(max-width: 892px) 100vw, 892px" /><figcaption class="wp-element-caption">&#8220;Who&#8217;s going to pick up this mess?&#8221;</figcaption></figure></div>


<p>At a high level, automatic garbage collection in Java works by:</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li><strong>Reference Counting:</strong> The number of references to a given spot in memory are tracked.</li>



<li><strong>Mark/Sweep:</strong> Objects that have 0 references are &#8220;swept&#8221; away, whereas objects that have 1 or more references to them remain.</li>



<li><strong>Copying:</strong> Objects that still have references are copied from one memory space to another, leaving behind the old space for reuse. </li>



<li><strong>Generational:</strong> This technique divides the heap into generations (young, old, and permanent) and applies different collection strategies to each generation.</li>
</ul>



<p>So what constitutes an object as young, old, or permanent?</p>



<ul class="wp-block-list">
<li><strong>Young:</strong> Objects that have newly been created and haven&#8217;t yet gone through one garbage clean up cycle.</li>



<li><strong>Old: </strong>These are objects that have survived multiple garbage collection cycles and are considered therefore to be &#8220;old&#8221;.</li>



<li><strong>Permanent:</strong> Generally, classes and methods are considered to be permanent spots of memory in a Java application.</li>
</ul>
</div></div>



<p>But there&#8217;s a catch when it comes to how automatic garbage collection works in Java: there&#8217;s <strong>no guarantee when it will run</strong>, and there&#8217;s multiple reasons why this is:</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li><strong>Dynamic nature of memory usage:</strong> Java&#8217;s object-oriented nature and dynamic memory allocation make it difficult to predict when memory will be released.</li>



<li><strong>Avoiding frequent pauses:</strong> Garbage collection can significantly impact application performance. By not guaranteeing a specific timing, the JVM can optimize garbage collection to minimize disruptions. (Though difference garbage collection algorithms can be selected, but even then, it&#8217;s still not technically guaranteed as to when garbage collection will run)</li>



<li><strong>Real-time constraints:</strong> Some applications, like real-time systems, require deterministic behavior. In these cases, developers might need to implement their own memory management strategies or use specialized JVMs.</li>
</ul>
</div></div>



<p>So how can you hook into garbage collection? Well, objects created in Java inherit from the Object class, which means that all objects have certain methods that we can override: finanlize() is a method that is invoked by the garbage collector prior to the object being destroyed.</p>



<p>This <em>might</em> be a good place for you to invoke some business logic that you need to perform upon the object being deleted from memory, but remember: There is no guarantee when garbage collection will run, and therefore the logic that you put in the finalize() method of your object shouldn&#8217;t really be mission critical as it may or may not run when you expect it to. Also, garbage collection is generally an expensive task and we should really let the JVM do its things since it&#8217;s already highly optimized. (There really are very few reasons why you should be doing your own garbage collection in Java, and if you&#8217;re on the fence as whether or not it&#8217;s something you explicitly need to handle, you probably don&#8217;t.)</p>



<p>Furthermore, handling your own garbage collection is generally frowned upon, and if you do need to handle some kind of clean up activities for when objects are no longer needed, you should probably be building this logic into a service or a method that lives on the object that is going to be destroyed, or if you&#8217;re using Spring or Spring Boot, this is probably already managed for you to an extent. </p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>OOP-101: Polymorphism &#8211; What is it, why use it, and an example</title>
		<link>https://www.chrisphilbin.net/oop-101-polymorphism-what-is-it-why-use-it-and-an-example/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sun, 16 Jun 2024 13:41:40 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://www.chrisphilbin.net/?p=510</guid>

					<description><![CDATA[In the world of object-oriented programming (OOP), polymorphism is a powerful concept that allows for flexibility and code reusability. Essentially, polymorphism means &#8220;having many forms.&#8221; (Poly meaning &#8216;many&#8217; as opposed&#8230;]]></description>
										<content:encoded><![CDATA[
<p>In the world of object-oriented programming (OOP), polymorphism is a powerful concept that allows for flexibility and code reusability. Essentially, polymorphism means &#8220;having many forms.&#8221; (Poly meaning &#8216;many&#8217; as opposed to &#8216;mono&#8217;, meaning one) In programming, it translates to the ability of code to work with objects of different types while treating them through a single interface.</p>



<p>Imagine having a remote control for your entertainment system. You can press the &#8220;play&#8221; button regardless of whether you&#8217;re playing a DVD or Blueray, streaming a movie, or listening to music. The remote acts as the interface, and the specific devices receiving the command handle the action in their own way (They are the objects). Polymorphism works similarly.</p>



<p><strong>Why is Polymorphism Important?</strong></p>



<p>Polymorphism offers several advantages:</p>



<ul class="wp-block-list">
<li><strong>Flexibility:</strong> Code can adapt to different object types without needing to be rewritten for each specific case.</li>



<li><strong>Maintainability:</strong> As your program evolves, adding new object types becomes easier since the core logic remains unchanged.</li>



<li><strong>Readability:</strong> Code that leverages polymorphism is often cleaner and easier to understand because it focuses on the functionality rather than the specifics of each object type.</li>
</ul>



<p><strong>A Use Case: Animal Sounds</strong></p>



<p>Let&#8217;s consider a scenario where you want to create a program that simulates animal sounds. You can define an abstract base class Animal with a method makeSound() that makes a generic animal noise. Now, create derived classes like Dog, Cat, and Bird that inherit from Animal and override the makeSound() method to produce their unique sounds (bark, meow, chirp, etc.).</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
// Base class
public class Animal {
  public void makeSound();
}

// Derived class - Dog
class Dog extends Animal {
  @Override
  public void makeSound() {
    System.out.println(&quot;Woof!&quot;);
  }
}

// Derived class - Cat
class Cat extends Animal {
  @Override
  public void makeSound() {
    System.out.println(&quot;Meow!&quot;);
  }
}

// Derived class - Bird
class Bird extends Animal {
  @Override
  public void makeSound() {
    System.out.println(&quot;Chirp!&quot;);
  }
}

public class AnimalSoundSimulator {
  public static void main(String&#x5B;] args) {
    Animal&#x5B;] animals = {new Dog(), new Cat(), new Bird()};
    for (Animal animal : animals) {
      animal.makeSound();
    }
  }
}
</pre></div>


<p>The above example is somewhat contrived and simplistic in nature, but it does convey the core concepts of polymorphism fairly well.<br><br>We have a base class of Animal, which defined a makeSound() method, and then several classes that extend the base class and then overwrite the behavior of the makeSound() method.<br><br>The animalSoundSimulator class simply defined a new collection of Animal objects (Since they all extend the Animal class, we can consider them to be Animals), and then loop over the collection and invoke makeSound() on each animal to see polymorphism in action.</p>



<p><strong>Bonus: Extends vs. Implements</strong></p>



<p>You&#8217;ll notice in the above that all of the classes like Cat, Dog, and Bird all <em>extend</em> the Animal class. This means that Cat, Dog, and Bird all, at a minimum, have <em>at least</em> the functionality of the class that they are extending, and in order for the magic to take place, you must override the methods that are defined in the class that is being extended. (The @Override annotation ensures that the method is being truly overwritten and not just overloaded, in which case strange behavior might occur and it might be difficult to debug.) </p>



<p>However, when it comes to <em>implementing</em> an Interface, the classes that are implementing the interface must conform to the methods outlined in the interface, however Overriding the methods defined in the interface is not a requirement. Also note that in the case of implementing an interface, the class that is doing the implementing must implement all of the behavior defined in the interface itself &#8211; Think of it as a contract of behavior.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Spring Boot: Using @Autowired vs constructor dependency injection</title>
		<link>https://www.chrisphilbin.net/spring-boot-using-autowired-vs-constructor-injection/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 03 Feb 2024 13:34:27 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=463</guid>

					<description><![CDATA[Spring Boot affords us a lot of tools right out of the box as developers. It even ships with a dynamic HTML template engine called Thymleaf to allow us to&#8230;]]></description>
										<content:encoded><![CDATA[
<p><a href="https://spring.io/">Spring Boot</a> affords us a lot of tools right out of the box as developers. It even ships with a dynamic HTML template engine called <a href="https://docs.spring.io/spring-framework/reference/web/webmvc-view/mvc-thymeleaf.html">Thymleaf</a> to allow us to not have to rely on Javascript frameworks such a React, Vue, or Angular if we wanted to go down that route.</p>



<p>Spring Boot heavily relies on annotations, similar to decorators when building an Angular front end application. Annotations are essentially metadata that are used to add context to what a class, method, or field does. This helps Spring Boot automatically configure Beans, manage dependencies, and handle other application configuration that we&#8217;d have to otherwise do manually when compiling our application.</p>



<p>One of these annotations is <strong><a href="https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/autowired.html">@Autowired</a></strong>. This annotation is a way for us to achieve dependency injection with next to no boilerplate code needed. It almost seems like magic because of how easy it is, and with that level of abstraction comes several caveats and pit falls when comparing this method of dependency injection versus traditional constructor injection.</p>



<p>Let&#8217;s first take a look at some of the benefits of using the @Autowired annotation:</p>



<ul class="wp-block-list">
<li><strong>Reduce boilerplate code</strong><br>This is probably an obvious advantage and is the reason why some people tend to use @Autowired for any and every dependency needed: It&#8217;s so easy! All you need to do is simply add the @Autowired annotation to whatever field, constructor parameters, or setter methods you want to inject and you&#8217;re done! This also somewhat improves code readability because it reduces the amount of boilerplate code you have to write.</li>



<li><strong>Loose Coupling</strong><br>By injecting components at runtime we can achieve loose coupling which is a great advantage when it comes time to test our application via unit testing. Though you will likely have to mock or provide the appropriate test beans when running the unit tests. </li>



<li><strong>Automatic dependency lookup</strong><br>Spring Boot will find and manage the appropriate beans to inject based on their types and their annotations. You won&#8217;t have to create or locate the required Beans yourself while can reduce the likelihood of errors and added complexity. (More on why this could be bad in a little bit)</li>
</ul>



<p>And let&#8217;s discuss some of the drawbacks when using @Autowired:</p>



<ul class="wp-block-list">
<li><strong>Implicit dependencies</strong><br>Sure, @Autowired helps to reduce the amount of boilerplate required, it also can make it more difficult to truly discern what the class is doing and what exactly it relies on in order to function as intended. This could pose as a real challenge for future developers who are tasked with maintaining/enhancing the application in the future &#8211; they will have to take more time to reason about the code you&#8217;ve written.</li>



<li><strong>Less control</strong><br>By reducing the amount of boilerplate code needed, one of the trade offs is giving up some level of control. What if for some reason you have multiple beans of the same type? Spring Boot might not pick the correct bean and as a result cause the application to break or not function correctly. You can get around this by specifying qualifiers, but if you&#8217;re going down that route, why not rely on constructor injection?</li>



<li><strong>Circular Dependencies</strong><br>It is very easy to get yourself into a situation where service A depends on service B, which depends on service A. You have to be very careful not to create a circular dependency and you also have to ensure the order in which bean creation is taking place is correct. This is easier said than done in a large application with dozens and dozens of services, controllers, and repositories.</li>
</ul>



<p>With that said, when should we be using the @Autowired annotation to handle dependency injection? It&#8217;s hard to come up with an iron clad rule &#8211; If you&#8217;re building a small CRUD application and are just working towards an MVP and you don&#8217;t have many services, then probably using constructor injection is the way to go in this case. If you&#8217;re working on a larger enterprise-level application, then most likely you will want to avoid using @Autowired in most cases. If you have a service that relies on half a dozen or more other services, there might be no other sensible way aside from using @Autowired &#8211; though this indicates code smell: Why does this service rely on so many other dependencies to function? Is it doing too much and can be broken into smaller chunks?</p>



<p>Finally, let&#8217;s discuss some of the advantages of using traditional constructor dependency injection, as well as some of its draw backs (You can probably guess what they are based off of the pros and cons of using @Autowired)</p>



<p>Benefits of constructor-based dependency injection:</p>



<ul class="wp-block-list">
<li><strong>Clear dependencies</strong><br>Dependencies are declared directly in the constructor, which makes them clearly visible and identifiable. This will allow for better readability in the future and reduces the risk of missing or hidden dependencies. Sometimes being more verbose is better, and this is one of those cases.</li>



<li><strong>Fail-Fast</strong><br>If a mandatory dependency is missing, the constructor initialization fails which prevents the creation of half-baked objects. Even better, you avoid the wrong bean being injected if you wind up with two beans with the same name/type.</li>



<li><strong>Encourages immutability:</strong><br>If you&#8217;re using the functional programming paradigm when building your application or want to stay true to true OOO principles, using constructor-based dependency injection as opposed to @Autowired is basically a must.</li>



<li><strong>Testability</strong><br>Generally, constructor-based dependency injection is easier to test. You can more easily mock dependencies during unit testing by passing mock objects into the constructor.</li>
</ul>



<p>And finally, let&#8217;s take a brief look at some of the drawbacks of using constructor-based dependency injection (Hint: there really aren&#8217;t many):</p>



<ul class="wp-block-list">
<li><strong>Boilerplate code</strong><br>This is probably the biggest one for most people &#8211; it requires a lot more code than just simply using @Autowired to handle dependency injection, but in most cases the additional code is worth it. You could even explore using <a href="https://projectlombok.org/">Lombok</a> if you wanted to still use constructor-based dependency injection but keep the amount of boilerplate code at bay. Just be careful because you&#8217;re introducing yet another layer of abstraction by using Lombok. You have to find the right balance for your code base and the team you&#8217;re working with.</li>



<li><strong> Limited Flexibility</strong><br>There is really no way to handle optional dependencies when using constructor injection so situations that require dynamic configuration changes might pose a problem. The answer to this is just more code in the way of more objects and classes. Again, this is a trade-off between how easy the code is to read and maintain and how quickly you can get the code working.</li>
</ul>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Inversion of Control (IoC): An Overview</title>
		<link>https://www.chrisphilbin.net/inversion-of-control-ioc-an-overview/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Thu, 06 Jul 2023 13:16:00 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=402</guid>

					<description><![CDATA[The goal of this article is to provide an overview in simple terms of the concept of Inversion of Control (IoC), what it is, why it&#8217;s important, and a basic&#8230;]]></description>
										<content:encoded><![CDATA[
<p>The goal of this article is to provide an overview in simple terms of the concept of Inversion of Control (IoC), what it is, why it&#8217;s important, and a basic example of how it is implemented in a simple Java program consisting of a few classes and an interface.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://chrisphilbin.net/wp-content/uploads/2023/07/uno_reverse_card-1024x576.png" alt="" class="wp-image-417" width="409" height="229"/></figure></div>


<p>At it&#8217;s most basic, the concept of IoC sets out to reverse the control between two classes via a third party (When developing modern Java applications this is usually Spring!). If we have two classes &#8211; a User class, and a Database class, the User class would directly <em>depend</em> on the Database class in order to save any data to the database. What if we change databases in the future and migrate away from MongoDB to Postgres? Sure, in a small application this wouldn&#8217;t be too difficult, but what about in an enterprise-level application with hundreds of thousands of lines of code and dozens of developers working on the same code base at the same time? We can do better! <em>Enter Inversion of Control.</em></p>



<figure class="wp-block-pullquote"><blockquote><p>&#8220;Depend on abstractions, not on concretions.&#8221;</p></blockquote></figure>



<p>Before diving into an example, another key benefit to address regarding IoC is that without it, our application would be considered <strong><em>tightly coupled</em></strong>, and next to impossible to unit test. Why? Well, because in order to do so, you&#8217;d have to mock an entire database in the User/Database scenario from above, and that&#8217;s really not practical, nor is it in the spirit of unit testing. implementing IoC allows us to instead <strong><em>loosely couple</em></strong> our application and actually unit test our code without the need to mock an entire database.</p>



<p>First, let&#8217;s look at a tightly coupled example that does not implement IoC:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
//User.java

public class User {

    MongoDb database;

    public User() {
        database = new MongoDb();
    }

    public void add(String data) {
        database.save(data);
    }

}
</pre></div>

<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
//MongoDb.java

public class MongoDb {
    
    public void save(String data) {
        System.out.println(&quot;The data you provided has been saved! &quot; + data);
    }
}
</pre></div>


<p>A pretty straight forward example. When we create a new User object, we are creating an instance of a MongoDb object each and every time. That MongoDb instance comes with a save method that takes in a string and in this example just returns a mock string back, using the same data that was passed in.</p>



<p>In this example, performing a unit test is extremely difficult because our User objects directly rely on an instance of MongoDb! There&#8217;s really no way for us to pass in a mock instance of the database since it&#8217;s being created at the <em>same time</em> as the User object &#8211; hence the term <strong><em>tightly coupled</em></strong>.</p>



<p>Also, if in the future the decision is made to utilize another database, it&#8217;s not easily done since we&#8217;ve essentially hard-coded the User class to depend directly on the MongoDb class. All of the subsequent methods in the User class would have to be updated.</p>



<p>Let&#8217;s take a look at an example employing the IoC paradigm in which we pass in MongoDb as an argument to the User constructor&#8230; Sounds like unit testing would be a little easier if we&#8217;ve already been given a database! We&#8217;re going to reverse the flow of control and instead of the User class controlling the database, we&#8217;re going to tell it what to do by passing a pre-existing database into its constructor&#8230; We&#8217;re inverting the control!</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
//User.java

public class User {

    MongoDb database;

    public User(MongoDb database) {
        this.database = database;        
    }

    public void add(String data) {
        database.save(data);
    }

}
</pre></div>


<p>Every time a user Object is created, we&#8217;re passing in a pre-existing instance of a MongoDb instance! Unit testing can be carried out since we&#8217;re being given a database each time we create a User! (In unit testing we&#8217;re only testing a single unit of code &#8211; imagine having to mock a database and hope you got its implementation right so you don&#8217;t run into unexpected bugs?)</p>



<p>Let&#8217;s take the above example a step further. We&#8217;re on the right track in terms of abstracting away where a new instance of MongoDb is being created, thus allowing us to unit test our code. But what if our team decides to migrate away from MongoDB and use MySQL instead?</p>



<p>Here we go again! The User class is expecting a MongoDb instance to be passed in! Let&#8217;s fix this by implementing a generic database interface that will force its behavior on whatever class we implement it in. Remember: <strong>an interface is a contract of behavior</strong>, so where ever it is implemented, we are guaranteed to, at the very minimum, have access to whatever the interface defines.</p>



<p>Let&#8217;s create a generic interface that all databases will implement:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
//Database.java

public interface Database {
    void save(String data);
}
</pre></div>


<p>Where ever we implement this interface, we&#8217;re guaranteed to <em>at least</em> have a save method that doesn&#8217;t return anything, but takes in a String. Now let&#8217;s update our existing MongoDb class to implement this new interace:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
//MongoDb.java

public class MongoDb implements Database {
    
    public void save(String data) {
        System.out.println(&quot;The data you provided has been saved! &quot; + data);
    }
}
</pre></div>


<p>The change is subtle, but this is good as we&#8217;re getting closer to a really robust solution. Now the MongoDb class implements the Database interface. It <em>must</em> have a save method that doesn&#8217;t return anything and takes in a string as an argument. If not, the code will not compile.</p>



<p>Finally, let&#8217;s update our User class to now rely on a generic Database object rather than a MongoDb class, a MySql class, Oracle class, etc.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
//User.java

public class User {

    Database database;

    public User(Database database) {
        this.database = database;        
    }

    public void add(String data) {
        database.save(data);
    }

}
</pre></div>


<p>We can clearly see that our User class doesn&#8217;t really care about what kind of database is being passed in&#8230; So as long as it implements the Database interface, we are good to go and can utilize it in the class! We have achieved <strong><em>loose coupling</em></strong> and our program is much more robust than when we began our example.</p>



<p></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
