<?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>Chris Philbin&#039;s Blog</title>
	<atom:link href="https://www.chrisphilbin.net/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.1</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>Javascript&#8217;s Temporal Dead Zone (TDZ)</title>
		<link>https://www.chrisphilbin.net/javascripts-temporal-dead-zone-tdz/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Thu, 15 Aug 2024 01:12:43 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">https://www.chrisphilbin.net/?p=544</guid>

					<description><![CDATA[Not to be confused with the &#8220;temporal pincer movement&#8221; from Christopher Nolan&#8217;s 2020 movie Tenet, but perhaps equally confusing, is the concept in Javascript known as the Temporal Dead Zone,&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Not to be confused with the &#8220;temporal pincer movement&#8221; from Christopher Nolan&#8217;s 2020 movie Tenet, but perhaps equally confusing, is the concept in Javascript known as the Temporal Dead Zone, or the TDZ.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" width="931" height="561" src="https://www.chrisphilbin.net/wp-content/uploads/2024/08/tdz.webp" alt="" class="wp-image-551" style="width:577px;height:auto" srcset="https://www.chrisphilbin.net/wp-content/uploads/2024/08/tdz.webp 931w, https://www.chrisphilbin.net/wp-content/uploads/2024/08/tdz-300x181.webp 300w, https://www.chrisphilbin.net/wp-content/uploads/2024/08/tdz-768x463.webp 768w" sizes="(max-width: 931px) 100vw, 931px" /><figcaption class="wp-element-caption">Neil trying to explain the Temporal Dead Zone</figcaption></figure></div>


<p>To put it simply, the TDZ is a phase in a variable&#8217;s lifecycle where it <em>technically exists</em>, however it cannot be accessed or used &#8211; This phenomenon mostly applies to variables defined with the keyword <strong>let</strong> or <strong>const</strong>, but not <strong>var</strong> (And function definitions, too), thanks to the concept of hoisting (More on &#8216;hoisting&#8217; in a moment &#8211; there are a few caveats, which is why I said &#8216;mostly&#8217;).</p>



<p>Let&#8217;s take a look at a contrived example to see the TDZ in action:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
function myFunction() {
    console.log(x);
    let x = &quot;Hello, world!&quot;;
}

myFunction();
</pre></div>


<p>The above will result in the following being logged to the JS console:</p>



<pre class="wp-block-code"><code>ReferenceError: Cannot access 'x' before initialization</code></pre>



<p>The JS interpreter knows that x exists, however it cannot access it before it&#8217;s been initialized &#8211; x is in the temporal dead zone. Think of it this way: You&#8217;re going to make a dish that requires bread crumbs. You can see through the clear doors of the cabinet that you have bread crumbs available, but you cannot physically touch them until the doors have been opened. You know they exist, but you just can&#8217;t get to them yet. They too are in the temporal dead zone.</p>



<p>Let&#8217;s take a look at the same example from above, but using the <strong>var</strong> keyword to handle the variable declaration:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
function myFunction() {
    console.log(x);
    var x = &quot;Hello, world!&quot;;
}

myFunction();
</pre></div>


<p>The above works&#8230; Kind of. <strong>Undefined</strong> is logged to the console, indicating that x has been initialized, but has yet to be assigned any value. Interesting. Now is a good time to touch on the concept of hoisting.</p>



<p>In JS, hoisting is the concept where all variables (Those declared using var, let, and const) and function declarations get &#8220;hoisted&#8221; (think: &#8220;pulled to the top&#8221;) of the current scope. Note how I said declarations &#8211; NOT assignments.</p>



<p>Variables defined with <strong>var</strong> can be accessed before they are initialized, and they can be re-declared in the same scope, whereas variables defined with <strong>let </strong>and <strong>const</strong> cannot be accessed before they are initialized (They too are hoisted, but they are in the TDZ), and they cannot be re-declared in the same scope.</p>



<p>This is why in the last example from above where using <strong>var</strong> resulted in undefined being returned and not a ReferenceError like in the <strong>let</strong> example. x was declared, however it was not assigned any value, hence it was undefined.</p>



<p>So variables declared with the keyword <strong>var</strong> can be &#8220;used&#8221; before they&#8217;re actually assigned a value, just expect them to return undefined until they are actually assigned a value, whereas variables defined with <strong>let</strong> and <strong>const</strong> will result in a ReferenceError since they live in the temporal dead zone.</p>



<p>So why is the TDZ a thing when it comes to variables defined with either <strong>let</strong> or <strong>const</strong>?</p>



<p>Both <strong>let </strong>and <strong>const</strong> were introduced in 2015 with ES6, and the concept of the TDZ was born in order to enhance code readability and enforce some level of standardization by encouraging developers to initialize and define variables at the same time. <strong>var </strong>still exists because backwards compatibility needed to be kept in mind so older code didn&#8217;t break. As of 2024, <strong>let </strong>and <strong>const </strong>are the preferred key words to use when defining a variable.</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>Using the async pipe within Angular templates to perform control flow</title>
		<link>https://www.chrisphilbin.net/using-the-async-pipe-within-angular-templates-to-perform-control-flow/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 18 Oct 2023 23:47:44 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=438</guid>

					<description><![CDATA[If you&#8217;re working on a small to mid-sized Angular app, chances are you&#8217;re probably not using a state management library like NgRx to handle your app&#8217;s state. And that&#8217;s probably&#8230;]]></description>
										<content:encoded><![CDATA[
<p>If you&#8217;re working on a small to mid-sized Angular app, chances are you&#8217;re probably not using a state management library like <a rel="noreferrer noopener" href="https://ngrx.io/" target="_blank">NgRx</a> to handle your app&#8217;s state. And that&#8217;s probably alright if you&#8217;re only working with maybe a dozen or so components.</p>



<p>If that&#8217;s the case, then you&#8217;re probably relying on services to manage state as it&#8217;s the out-of-the-box method presented to us by the Angular team. </p>



<p>The gist of services is to abstract away any business logic from our components, and subscribing to any state that we need to use within the component.</p>



<p>One common task that we routinely find ourselves doing when relying solely on services for state management is creating semaphore variables to determine whether or not a certain piece of state is loading and as a result displaying some kind of message or icon to the user letting them know that it may be a moment before the data is ready. Error handling also mimics this same pattern where we&#8217;re using Subjects or BehaviorSubjects and subscribing to them over and over again. Based on the truthiness of a variable like &#8220;hasErrors&#8221;, we can display a message letting the user know something unexpected happened and it requires their attention.</p>



<p>The async pipe provided to us by Angular out of the box is a great way to get around having to set up numerous subscriptions within our component TS files, and comes in especially handy when you&#8217;re working on a small to mid-sized application that doesn&#8217;t have extremely complex state and control flow. </p>



<p>Let&#8217;s take a look at the traditional way of setting up a simple service and a method to fetch some data from an external API, and then subscribe to that data from within a component:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import { Injectable } from &#039;@angular/core&#039;;
import { BehaviorSubject, of } from &#039;rxjs&#039;;
@Injectable({
  providedIn: &#039;root&#039;,
})
export class CounterService {
  count$: BehaviorSubject&lt;number&gt; = new BehaviorSubject&lt;number&gt;(0);
  isLoading$: BehaviorSubject&lt;boolean&gt; = new BehaviorSubject&lt;boolean&gt;(false);
  constructor() {}
  increase() {
    this.isLoading$.next(true);
    setTimeout(() =&gt; {
      this.count$.next(this.count.value + 1);
      this.isLoading$.next(false);
    }, 3500);
  }
}
</pre></div>


<p>The above service is somewhat contrived, but it&#8217;s a good example to show us how subscribing to the isLoading variable can be abstracted away using the async pipe within our component template files. Let&#8217;s take a look at how how we&#8217;d implement showing the user some kind of loading prompt within the use of the async pipe:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import { CounterService } from &#039;../services/counter.service&#039;;
import { Component, OnInit } from &#039;@angular/core&#039;;
@Component({
  selector: &#039;app-my-counter&#039;,
  templateUrl: &#039;./my-counter.component.html&#039;,
  styleUrls: &#x5B;&#039;./my-counter.component.scss&#039;],
})
export class MyCounterComponent implements OnInit {
  count: number;
  isLoading: boolean;
  constructor(public countService: CountService) {}
  ngOnInit(): void {
      this.countService.count$.subscribe((count) =&gt; {
        this.count = count;
      })
      this.countService.isLoading$.subscribe((isLoading) =&gt; {
        this.isLoading = isLoading;
      })
    this.countService.increase();
  }
}
</pre></div>


<p>Lines 21 &#8211; 23 are where things start to get really repetitive and you&#8217;ll find yourself setting up at least 3 subscriptions per component, assuming that each component always has some kind of meaningful external state (In our example the count variable), and semaphore variables for both loading and errors.</p>



<p>Also note: Line 14 we&#8217;re also marking the counterService <strong>public</strong> instead of <strong>private</strong> like we typically do when we handle dependency injection via the constructor&#8217;s parameters. If we did not do this, the counterService would not be available within the associated template file that we&#8217;re going to work with next.</p>



<p>Let&#8217;s abstract that away from our component TS files and implement it within our template files instead using the async pipe:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;div *ngIf=&quot;counterService.isLoading$ | async; else showCount&quot;&gt;
    Loading... Please wait!
&lt;/div&gt;
&lt;ng-template #showCount&gt;
    {{ counterService.count$ | async }}
&lt;/ng-template&gt;
</pre></div>


<p>What a difference! We no longer have to set up subscriptions within our component TS files but can instead lean on the async pipe to manage the subscriptions and assignments for us!</p>



<p>The async pipe is great because it subscribes to the observable stream and takes whatever values comes across the stream and interpolates it within the template without us having to specifically initialize a local template variable and handle the assignment based on the subscription.</p>



<p>Just to be clear, this will work when working with not-so-complex states generally found in smaller to mid-sized apps. This pattern starts to break down once you start introducing things like role based authentication, really in depth control flow, or a more complex object with nested objects and other data structures and collections.</p>



<p></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Building the Javascript .map() function from scratch</title>
		<link>https://www.chrisphilbin.net/building-the-javascript-map-function-from-scratch/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Fri, 01 Sep 2023 19:51:39 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=283</guid>

					<description><![CDATA[Probably one of the most used and most powerful functions ( .reduce() might be the most important) in the Javascript language is the .map() function (And let&#8217;s not forget it&#8217;s&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Probably one of the most used and most powerful functions ( .reduce() might be <em>the</em> most important) in the Javascript language is the .map() function (And let&#8217;s not forget it&#8217;s somewhat closely related cousin .forEach()). Both of these functions allow us to iterate over an array and do something with each element one by one.</p>



<p><strong>First, what is the difference between map and forEach in Javascript?</strong></p>



<p>.map() &#8211; Iterates over a collection and does <em>something</em> to each item and then pushes that new element to a newly created array which is then returned once each element in the provided collection has been iterated over.</p>



<p>.forEach() &#8211; Still iterates over a collection and does <em>something</em> to each item but it does not push the returned value of the action to a new array. (Think: &#8220;for each element in this array, go off an fire of an XHR and get the response and do something with it&#8221;&#8230; Have fun with all of the promises!) </p>



<p><strong>Let&#8217;s recreate .map() from scratch</strong></p>



<p>When writing software we take for granted what is going on under the hood in the built in methods and functions Javascript provides to us (Really any language, for that matter). By re-creating .map() from scratch will give us a better understanding of how the code is behaving in our applications. From there we can start building on that knowledge to understand more advanced topics like how the reduce function works.</p>



<p>Remember: .map() allows us to go through each element in a collection (array) and does something to each element (it &#8216;maps it&#8217; to a new value based on the instructions we give it) and then returns an array with all the new values.</p>



<p>A few things stick out right away with the above breakdown:</p>



<ul class="wp-block-list">
<li>Our custom map function will have two parameters:
<ul class="wp-block-list">
<li>The input collection (array)</li>



<li>Instructions (a callback function) that we pass in</li>
</ul>
</li>



<li>Our custom map function will also need a way to iterate over each element &#8211; So we&#8217;ll have to employ some kind of loop to achieve this</li>



<li>We&#8217;re returning a new array &#8211; at some point we&#8217;re going to have to create a new array</li>
</ul>



<p>Ready? Here&#8217;s essentially what map is doing under the hood:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const arr = &#x5B;1, 2, 3, 4, 5];

const newMap = (input, mutator) =&gt; {
  let newArr = &#x5B;];
  for (let i = 0; i &lt; input.length; i++) {
    newArr.push(mutator(input&#x5B;i]));
  }
  return newArr;
};
const multiplyByTwo = (num) =&gt; {
  return num * 2;
};

const answer = newMap(arr, multiplyByTwo);

console.log(answer);
</pre></div>


<p>Line 1 we&#8217;re declaring a constant in memory with the label <strong>arr</strong> and assigning it the value [1, 2, 3, 4, 5].</p>



<p>Line 3 we&#8217;re defining a function in memory with the label <strong>newMap</strong>.</p>



<p>Line 10 we&#8217;re again defining a function in memory with the label <strong>multiplyByTwo</strong>.</p>



<p>And finally, line 14 we are declaring a constant in memory and assigning it the value to <strong>whatever the code to the right of the equals sign evaluates to &#8211; this is where we invoke/run the code above</strong>.</p>



<p>To the right of the equals sign on line 14 we run the newMap function and we provide it with two arguments: arr and the function multiplyByTwo.</p>



<p>We then create a new local execution context when we start running the newMap function where we setup our parameters:</p>



<p><strong>input</strong>: [1, 2, 3, 4, 5]<br><strong>mutator</strong>: (num) =&gt; { return num * 2 }</p>



<p>Next, we create a new empty array giving it the label <strong>newArr</strong>.</p>



<p>The provided array, now known as <em>input</em> in this local execution context, is then iterated over using a for loop. For each element in the collection, we then run the multiplyByTwo function with the input, which then returns the input number multiplied by 2 and that number is then pushed into the previously created new blank array (<strong>newArr</strong>).</p>



<p>Finally, once the for loop completes, the function then runs the last line of code which is to &#8220;spit out&#8221; (return) the newly created array and store that into the variable <strong>answer</strong> where we then console.log it to see it&#8217;s value.</p>



<p><strong>Closing thoughts</strong></p>



<p>Recreating the map function is a great exercise for newer developers because it allows you to &#8220;peel back the layers&#8221; of what&#8217;s going on under the hood in some of the code you&#8217;ve been working with for several months or years. Furthermore, doing this also gives you a better understanding of how functional programming in Javascript works and by understanding how .map() works under the hood you will have a much better understanding of how .reduce() is working which is the cornerstone of functional programming.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Demystifying the new keyword in Javascript</title>
		<link>https://www.chrisphilbin.net/javascript-new-keyword/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 26 Aug 2023 11:48:12 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=292</guid>

					<description><![CDATA[Javascript&#8217;s &#8216;new&#8217; keyword goes hand-in-hand with the object oriented programming paradigm in which the code written aims to mimic things and actions in the real world. A dog can run&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Javascript&#8217;s &#8216;new&#8217; keyword goes hand-in-hand with the object oriented programming paradigm in which the code written aims to mimic things and actions in the real world. A dog can run and jump, a user can login and logout. In the world of Javascript, a single &#8216;dog&#8217; would be an object, and the &#8216;run&#8217; action would be a method found on that object.</p>



<p>Object oriented programming seeks to combine data and actions that we can invoke on that data while making it easy for us programmers to switch between the two.</p>



<p>Consider the following scenario: We have a user and that user wants to login to our eCommerce app, browse around, place an order and perhaps leave a review for a product they purchased several weeks ago. </p>



<p>First, let&#8217;s take a look at a naive approach that you will see very quickly will not scale well and will lead to a lot of memory usage:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const user1 = {
    userId: &quot;00001&quot;,
    name: &quot;Thomas&quot;,
    displayName: &quot;tom123&quot;,
    email: &quot;thomas.smith@example.com&quot;,
    login: () =&gt; {
        //login business logic
        //maybe an API call, storing session info
        console.log(&quot;User has successfully logged in!&quot;)
    },
    logout: () =&gt; {
        //logout business logic
        //Another API call, removing session info
        console.log(&quot;User has successfully logged out!&quot;)
    }
}

console.log(user1.displayName) //returns &#039;tom123&#039;
user1.login() //logs the user in to the app
</pre></div>


<p>The above code is fairly straightforward. We create an object with several properties (userId, name, etc) and assigned it the label &#8216;user1&#8217; in memory. This also has a few methods attached as well: login and logout.</p>



<p>The object oriented &#8216;litmus test&#8217; is: <em>Can we run user1.login() and actually access both the object and the functionality that we want?</em></p>



<p>While the answer is &#8216;yes&#8217; for the above sample, it has several fairly obvious issues:</p>



<p>What if we have 100 users, or perhaps 100,000 users or even more? Every single user object will have to have copies of those two login and logout methods and waste a lot of memory in the process. Also, what if we have to change the business logic in either of those methods sometime in the future due to some enhancements the product team wants? You would be stuck trying to individually update thousands and thousands of methods and hope for no errors along the way.</p>



<p>This implementation will not scale well, however at its core this is exactly what we want in terms of features &#8211; it satisfied the object oriented litmus test of &#8216;Can we run user1.login() and actually access both the object and the functionality that we want?&#8217;</p>



<p>Let&#8217;s take a look at another implementation that uses Object.create() &#8211; Object.create(), if invoked without any arguments will return a blank object. If passed an argument that is itself an object with key/value pairs, it will do something pretty interesting that gets us pretty close to our ideal solution to implement an object oriented programming paradigm in Javascript.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const userFunctions = {
  login: () =&gt; {
    //login business logic
    //maybe an API call, storing session info
    console.log(&quot;User has successfully logged in!&quot;);
  },
  logout: () =&gt; {
    //logout business logic
    //Another API call, removing session info
    console.log(&quot;User has successfully logged out!&quot;);
  },
};

const user2 = Object.create(userFunctions);

console.log(user2.__proto__, &quot;user2 proto&quot;);

user2.userId = &quot;00002&quot;;
user2.name = &quot;Sam&quot;;
user2.displayName = &quot;Sam123&quot;;
user2.email = &quot;sam@example.com&quot;;

user2.login();
</pre></div>


<p>When we <strong>console.log(user2.__proto__)</strong> we get to see the magic that is going on behind the scenes. Javascript will append an __proto__ (double underscore proto, sometimes called &#8216;dunder proto&#8217;) to each object and it will then in turn give access to the login and logout functions. The litmus test holds true: When we call user2.login() Javascript looks to the __proto__ property when it doesn&#8217;t find the login() method immediately on user2. Once it finds it, it then invokes login() and the body of the function then runs.</p>



<p>Finally, we can clean this up a little further and utilize some more modern ES2015 features: The &#8216;new&#8217; keyword.</p>



<p>The &#8216;new&#8217; keyword in Javascript automates 3 key tasks for us:</p>



<ol class="wp-block-list">
<li>It auto-creates an empty object and assigns it to the label &#8216;this&#8217;</li>



<li>It sets up a hidden __proto__ property that points to the constructor function&#8217;s prototype object that contains all of the desired functionality</li>



<li>It automatically returns the newly created object that was stored in the &#8216;this&#8217; label in memory.</li>
</ol>



<p>Let&#8217;s see it in action:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
function CreateUser(userId, name, displayName, email) {
  this.userId = userId;
  this.name = name;
  this.displayName = displayName;
  this.email = email;
}

CreateUser.prototype.login = function () {
  console.log(&quot;User has successfully logged in!&quot;);
};

CreateUser.prototype.logout = function () {
  console.log(&quot;User3 has successfully logged out!&quot;);
};

const user3 = new CreateUser(&quot;00003&quot;, &quot;Mike&quot;, &quot;Mike123&quot;, &quot;mike@example.com&quot;);

console.log(user3.__proto__, &quot;user3 __proto__&quot;);

user3.login();
</pre></div>


<p>In this example, user3.__proto__ points to the prototype object on the CreateUser function &#8211; this happens thanks in part to the &#8216;new&#8217; keyword. This functionality is made possible because when you create a function in memory, not only does Javascript save the function body, but it also creates a &#8216;hidden&#8217; object that you can append key/value pairs to. This concept is sometimes referred to as a &#8220;function object combo&#8221;.</p>



<p>Javascript takes the above concepts even one step further by implementing classes, however that topic is better left for another article for another time. Thanks for reading and hopefully you&#8217;ve gained a better understanding of how the &#8216;new&#8217; keyword is working under the hood!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>The Differences Between Subjects and BehaviorSubjects in RxJS</title>
		<link>https://www.chrisphilbin.net/the-differences-between-subjects-and-behaviorsubjects-in-rxjs/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 16 Aug 2023 23:59:00 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[RxJS]]></category>
		<category><![CDATA[Typescript]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=315</guid>

					<description><![CDATA[If you&#8217;re just starting to dive into Angular you&#8217;ve probably quickly realized that it&#8217;s a lot different from the other major front end frameworks such as React and Vue. Angular&#8230;]]></description>
										<content:encoded><![CDATA[
<p>If you&#8217;re just starting to dive into Angular you&#8217;ve probably quickly realized that it&#8217;s a lot different from the other major front end frameworks such as React and Vue. Angular is a &#8220;convention over configuration&#8221; framework in the sense that the Angular development team has designed the framework in such a way to more or less <em>force</em> you into following a certain set of rules in order for it to work properly. (I&#8217;ve personally found Vue to be a happy medium in between Angular and React in this sense)</p>



<p>If you&#8217;re a less experienced front end developer and are looking to up your JavaScript game, forcing yourself to create a few Angular apps is a great way to really level up your JS skill set. React and Vue do a great job at abstracting things away so some things that happen just seem like magic. Angular still has abstractions however not to the extent of the other two so you&#8217;re forced to roll up your sleeves and up your JS game. (This is really just me saying the learning curve for Angular is more demanding that any other front end framework.)</p>



<p>Angular ships with RxJS and it&#8217;s a complete paradigm shift in that you no longer simply rely on fetch() or axios.get() to handle your HTTP requests in your app. RxJS instead allows us as developers to <em>subscribe</em> to a data stream and listen to it for any changes while the subscription is active. To be fair, you can implement RxJS in either a React or Vue app, but neither ships with it out of the box so it&#8217;s up to you the install it as a dependency and use it (Convention over configuration&#8230; Remember?)</p>



<p>Subjects and BehaviorSubjects are observables that can emit their values to multiple observers via subscriptions. On the surface we&#8217;re almost inclined to think that both a Subject and a BehaviorSubject do the same thing, but the differences are subtle and can make a pretty big impact on your application.</p>



<p>In simple terms: <strong>A Subject does not need to have an initial value when being created but a BehaviorSubject requires an initial value when being created.</strong> Therefore, a Subject will only emit upcoming values, whereas a BehaviorSubject will emit <em>one previous value and all upcoming values</em>.</p>



<p>Let&#8217;s set the stage for a pretty common example front end developers handle on a routine basis: showing or hiding a modal to let the user edit settings. As you can imagine, this is a good use case for a BehaviorSubject because we&#8217;ll want to set the initial value of &#8220;showModal&#8221; to &#8220;false&#8221;.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
// src/app/services/modal.service.ts

import { BehaviorSubject } from &#039;rxjs&#039;;

export class ModalService {
  showModal = new BehaviorSubject&lt;boolean&gt;(false);

  toggleModal() {
    this.showModal.next(!this.showModal.value);
  }
}
</pre></div>


<p>Had we not passed in a boolean value to the BehaviorSubject&#8217;s constructor, TypeScript would have immediately given us an error indicating that one argument was expected, but we&#8217;ve given it 0.</p>



<p>The above example sets up an Angular service that we can then import into any other component and utilize the toggleModal() method. Any subscriptions to this observable therefore will receive an initial value of &#8220;false&#8221; since BehaviorSubjects allow us to track and initial value and any subsequent changes in the future.</p>



<p>On the other hand, a Subject does not require an initial value. In sticking with the modal example from above, a good parallel use case for a Subject would be if upon the user opening a modal in the app we want to display a form containing the app&#8217;s settings that they can modify and then save. Let&#8217;s take a look:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
// src/app/services/settings.service.ts

import { Subject } from &#039;rxjs&#039;;
import { HttpClient } from &#039;@angular/common/http&#039;;

export class SettingsService {

  appSettings = new Subject&lt;Settings&gt;();

  constructor(private http: HttpClient) {}

  getAppSettings() {
  this.http.get&lt;Settings&gt;(&#039;https://www.myapp_api.com/settings&#039;)
    .subscribe((settings: Settings) =&gt; {
      console.log(settings, &#039;Settings received from API call.&#039;);
      this.settings.next(settings);
    )};
  }

}
</pre></div>


<p>Sure, there&#8217;s a little more code than the previous BehaviorSubject example but most of it is simply boiler plate code in order to set things up. The key takeaway here should be that when we create a new Subject, we do not have to supply its constructor method with an argument to set the initial value upon creation. We only have to indicate what kind of value will be occupying it in the future, which in this case is an object of type &#8220;Settings&#8221;.</p>



<p>We&#8217;ve defined a getAppSettings() method that we can again import into any other component and fetch our user&#8217;s app settings from the back end and then once the request comes back we will push the new value via the next() method and any subscriptions made will finally receive their first value. We will then have access to the app settings, now stored with the label <strong>appSettings</strong>, be it an object of settings or an array.</p>



<p>So what&#8217;s the tl;dr version of all of this? Pretty simple, actually:</p>



<p><strong>Use a BehaviorSubject if you need an initial value (The modal example above is a really good example) and use a Subject if you do not need an initial value.</strong></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>JavaScript closures: What are they?</title>
		<link>https://www.chrisphilbin.net/javascript-closures-what-are-they/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 02 Aug 2023 10:54:00 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=390</guid>

					<description><![CDATA[A closure in JavaScript is a pretty obscure concept to grasp, especially when starting out. They&#8217;re one of the more important building blocks and concepts in JS that enable many&#8230;]]></description>
										<content:encoded><![CDATA[
<p>A closure in JavaScript is a pretty obscure concept to grasp, especially when starting out. They&#8217;re one of the more important building blocks and concepts in JS that enable many other features in the language to work. (Like iterators and generators, and even paves the way for concepts like observable streams)</p>



<p>From<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures"> MDN</a>, a closure is as follows:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>A&nbsp;<strong>closure</strong>&nbsp;is the combination of a function bundled together (enclosed) with references to its surrounding state (the&nbsp;<strong>lexical environment</strong>). In other words, a closure gives you access to an outer function&#8217;s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.</p>
<cite>https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures</cite></blockquote>



<p>Essentially, we can think of a closure as a <strong><em>backpack</em></strong> that every function gets whenever it is defined. The contents of said backpack are dependent on where the function was defined &#8211; this is also known as its <strong><em>scope</em></strong>. This is what we mean when something is <strong><em>lexically scoped</em></strong>. In this backpack we will find the surrounding function&#8217;s variables, which will allow the inner function (the one that is carrying the backpack) to have access to the outer function&#8217;s scope/variables even after it&#8217;s finished executing. We can really start to leverage this feature of JavaScript when we return a function from another function.</p>



<p>Let&#8217;s take a look at a really basic example to get a better understanding at how this concept works in practice:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
function outerFunc() {
  let counter = 0;

  return function innerFunc() {
    console.log(`The value of counter is: ${counter}`);
    counter++;
  };
}

const runnerFunc = outerFunc();

runnerFunc();
runnerFunc();
runnerFunc();
runnerFunc();
runnerFunc();
runnerFunc();
</pre></div>


<p>And the output that&#8217;s logged to the console is:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
The value of counter is: 0
The value of counter is: 1
The value of counter is: 2
The value of counter is: 3
The value of counter is: 4
The value of counter is: 5
</pre></div>


<p>Line 6 from the code example above (Not the console.log output) is extremely important &#8211; <strong><em>the inner function is incrementing a variable that was defined in the outer function&#8217;s scope</em></strong>. When running functions, we&#8217;re used to them <strong>not</strong> being able to persist the variables/state from its previous execution context (the last time it was run), but somehow in this example the inner function was still able to access variables that belonged to the outer function&#8217;s scope even after it was finished running! Enter the concept of closures!</p>



<p>We can do some really interesting things with this newly found knowledge. Let&#8217;s take another look at a custom made generator function that we can pull values from one at a time. This is a big paradigm shift in that we normally iterate over a collection of objects and get the value one at a time that way using a tried and true for or while loop. Let&#8217;s have a look:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
function countUpUntil(x) {
  let counter = 0;
  function next() {
    if (counter &lt;= x) {
      return { value: counter++, done: false };
    }
    return { value: undefined, done: true };
  }

  return { next };
}

const iterator = countUpUntil(5);

console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(interator.next());
</pre></div>


<p>And let&#8217;s have a look at the output from the console:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
{ value: 0, done: false }
{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: 4, done: false }
{ value: 5, done: false }
{ value: undefined, done: true }
</pre></div>


<p>Now we&#8217;ve created a function in such a way that will only allow us to run it a certain amount of times! We can use this method to enable us to &#8220;pull&#8221; from a collection each time the function is run as opposed to us traversing the entire collection using a traditional for/while loop &#8211; an incredible paradigm shift that paves the way for concepts like observable streams, generator functions, and iterator functions, all of which are significant building blocks in the JavaScript ecosystem. </p>



<p>In the above code example, we again have an inner function, this time called <strong><em>next</em></strong>, that is accessing the variable with the label <strong><em>counter</em></strong> that was defined in the outer function&#8217;s execution context. In fact, we reference counter twice &#8211; we perform a conditional to see if counter is less than or equal to x (the number we want to &#8216;count&#8217; up until), and if the conditional is true, we then return an object that contains the value of count after it&#8217;s been incremented by 1, as well as a boolean letting us know whether or not the stream is done. When the conditional returns false, we get an object back with a value of undefined, and a truthy value for done letting us know the stream has finished giving us results. We can then implement logic elsewhere in our program to check for the truthy value.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Unit Testing Components in Angular</title>
		<link>https://www.chrisphilbin.net/unit-testing-components-in-angular/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Thu, 27 Jul 2023 00:58:43 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=365</guid>

					<description><![CDATA[Test-Driven development, or TDD, is a paradigm in which before any code is written, tests are first created based off of requirements/user stories. We can think of it similar to&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Test-Driven development, or TDD, is a paradigm in which before any code is written, tests are first created based off of requirements/user stories. We can think of it similar to a &#8220;to do&#8221; list of things that a piece of software must do in order to satisfy the requirements. Throughout the development process, these tests are run in order to ensure that no breaking changes or bugs have been introduced. </p>



<p>A <em><strong>unit test</strong></em> is a smaller piece of the TDD paradigm in which it sets out to test a single unit of code &#8211; in most cases a function or method &#8211; to ensure that when it runs in a controlled environment the code behaves as we intended it to do so.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" src="https://chrisphilbin.net/wp-content/uploads/2023/07/pencil-test.jpeg" alt="" class="wp-image-426" width="507" height="341"/></figure></div>


<p>When we say <strong><em>unit testing</em></strong> as it relates to Angular, in most cases we&#8217;re talking about testing a single component to ensure that its functionality works as intended and no breaking changes have been introduced. (We can also unit test services, directives, and pipes) By default, Angular comes out of the box with Jasmine and Karma to assist with unit testing. <a href="https://jasmine.github.io/index.html">Jasmine</a> is a testing framework that gives us things such as spies and pattern matching, whereas <a href="https://karma-runner.github.io/6.4/index.html">Karma</a> is a task runner that helps us with the execution of the tests.</p>



<p>When we generate a new component using the Angular CLI (<em>ng generate component users</em>) in addition to it generating our usual CSS, HTML template, and TS Class file, it also generates a .spec.ts file for us that scaffolds a basic test for us that ensures the component is at least successfully created. Certainly a great starting point!</p>



<p>Let&#8217;s take a look at what the CLI gives us after running the above <em>ng generate</em> command:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import { ComponentFixture, TestBed } from &#039;@angular/core/testing&#039;;

import { UsersComponent } from &#039;./users.component&#039;;

describe(&#039;UsersComponent&#039;, () =&gt; {
  let component: UsersComponent;
  let fixture: ComponentFixture&lt;UsersComponent&gt;;

  //SECTION 1
  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: &#x5B; UsersComponent ]
    })
    .compileComponents();
  });

  //SECTION 2
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(UsersComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  //SECTION 3
  it(&#039;should create&#039;, () =&gt; {
    expect(component).toBeTruthy();
  });
});
</pre></div>


<p>I&#8217;ve added several comments to act as section headers to better assist in explaining what&#8217;s going on.</p>



<p><strong>Section 1</strong><br>This beforeEach block runs before each test we define later on in the spec file. We&#8217;re setting up a Test Bed, which is a controlled Angular environment for our tests to run in. Notice how the configureTestingModule method takes in an object as its argument and within that object we have a declarations property that is an array. Where else have we seen this? When ever we declare a module using the @NgModule decorator, of course! We&#8217;re essentially setting up a mini-module to test our component in!</p>



<p><strong>Section 2</strong><br>This second beforeEach block is where we&#8217;ll actually be setting up an instance of the component we want to test.<br><br>TestBed.createComponent(UsersComponent) returns to us a TestBed with an instance of the UsersComponent, and on the very next line we&#8217;re setting our component variable to fixture.componentInstance property which is an instance of our component that we can now run tests on!<br><br>fixture.detectChanges() gives us access to any changes to the component &#8211; it&#8217;s essentially refreshing the component after we&#8217;ve run a method or made some changes to some of the component&#8217;s properites.<br><br><strong>Section 3</strong><br>Finally! What we&#8217;ve been waiting for! Section 3 is where we&#8217;re actually writing our tests &#8211; Remember before each of these tests run, sections 1 and 2 will run each time &#8211; hence the beforeEach blocks. This boiler plate test lets us know that the component is created successfully without any bugs that are preventing it from compiling/loading.</p>



<h2 class="wp-block-heading">Putting it all together</h2>



<p>Let&#8217;s take things a step further. Let&#8217;s create a test for a login form that should only attempt to authenticate a user if the username and password fields are filled out. This is a great example because not only is it a real world use case, but it&#8217;ll also show us how to incorporate spies into our unit tests. Our login form also relies on a service, in this case the authService, so it&#8217;ll also give us a chance to look at how we incorporate services into our tests as well.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
import { ComponentFixture, TestBed } from &#039;@angular/core/testing&#039;;
import { FormsModule, NgForm } from &#039;@angular/forms&#039;;
import { AppRoutingModule } from &#039;src/app/app-routing.module&#039;;
import { AuthService } from &#039;src/app/services/auth.service&#039;;

import { LoginComponent } from &#039;./login.component&#039;;

const authServiceStub = {
  login: () =&gt; {},
  signup: () =&gt; {},
  user: {
    subscribe: () =&gt; {},
  },
};

describe(&#039;LoginComponent&#039;, () =&gt; {
  let component: LoginComponent;
  let authService: AuthService;
  let fixture: ComponentFixture&lt;LoginComponent&gt;;

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: &#x5B;LoginComponent],
      imports: &#x5B;AppRoutingModule, FormsModule],
      providers: &#x5B;{ provide: AuthService, useValue: authServiceStub }],
    }).compileComponents();
  });

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    authService = TestBed.inject(AuthService);
  });

  it(&#039;Should not attempt to authenticate user if the form is invalid&#039;, () =&gt; {
    const authSpy = spyOn(authService, &#039;login&#039;);
    const testFormData = &lt;NgForm&gt;{
      valid: false,
      value: {
        email: &#039;&#039;,
        password: &#039;&#039;,
      },
    };
    component.onSubmit(testFormData);
    fixture.detectChanges();
    expect(authSpy).toHaveBeenCalledTimes(0);
  });
});
</pre></div>


<p>A few important things to take note of that differ from the boiler plate code the Angular CLI gives us:<br></p>



<ul class="wp-block-list">
<li>We create an object called authServiceStub that stubs out all of the methods/properties that our login component will interact with. In the majority of cases it&#8217;s alright to just create no-op functions. We can run them, but we don&#8217;t expect anything to happen. We can spy on them to see if they do or do not run, and how many times if they do run.</li>



<li>The login component relies on the AppRoutingModule as well as the FormsModule. These must be imported into our test module via the imports array.</li>



<li>We need to provide the AuthService to this module, but we don&#8217;t want to test the logic within the service itself when unit testing this component. At this point we don&#8217;t really care <em>how</em> the service&#8217;s login and signup methods work. We just want to ensure that our login component actually runs them when expected. We&#8217;ll more or less overwrite most of its functionality via the <em>useValue</em> property.</li>



<li>We inject the new mock AuthService into the TestBed so we can later interact with it and spy on its methods.</li>
</ul>



<p>Lastly, let&#8217;s take a look at the single <strong><em>it</em></strong> spec from above:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
  it(&#039;Should not attempt to authenticate user if the form is invalid&#039;, () =&gt; {
    const authSpy = spyOn(authService, &#039;login&#039;);
    const testFormData = &lt;NgForm&gt;{
      valid: false,
      value: {
        email: &#039;&#039;,
        password: &#039;&#039;,
      },
    };
    component.onSubmit(testFormData);
    fixture.detectChanges();
    expect(authSpy).toHaveBeenCalledTimes(0);
  });
</pre></div>


<p>We&#8217;re doing a few important things here:</p>



<ul class="wp-block-list">
<li>We&#8217;re creating a spy. We&#8217;re going to spy on the login method from our newly created authService that we injected into this test bed.</li>



<li>We&#8217;re setting up basic form data that we know should result in the login function not running.</li>



<li>We attempt to run the component&#8217;s onSubmit function with the testFormData as an argument and we&#8217;re refreshing to get any changes.</li>



<li>Finally, we&#8217;re checking to see how many times the login function was run thanks to the authSpy. We&#8217;re expecting this value to be 0. If it&#8217;s been run 1 or more times the test will fail and we know that we introduced breaking changes into our code. (Did we remove a conditional, perhaps?)</li>
</ul>



<h2 class="wp-block-heading">What about DOM elements?</h2>



<p>The above example didn&#8217;t verify that an error message was being presented to the user, which would be somewhat of an awkward user experience if we just left them guessing as to why nothing is happening while using the application. How would we go about creating a unit test that also ensures that some kind of error message is being shown to the user? Let&#8217;s take a look at another <strong><em>it</em></strong> block:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
  it(&#039;Should display a div that contains an error message in the event of a user error during login&#039;, () =&gt; {
    const testFormData = &lt;NgForm&gt;{
      valid: false,
      value: {
        email: &#039;&#039;,
        password: &#039;&#039;,
      },
      reset: () =&gt; {},
    };
    component.onSubmit(testFormData);
    fixture.detectChanges();
    const loginElement: HTMLElement = fixture.nativeElement;
    expect(loginElement.querySelector(&#039;#error-container&#039;)?.innerHTML).toContain(
      &#039;Must provide valid credentials&#039;
    );
  });
</pre></div>


<p>A lot of this is pretty similar to the previous example. The main difference is that after we attempt to submit the form with data that we know will cause it to fail, we run fixture.detectChanges() to &#8220;refresh&#8221; the component, and then we access the underlying HTML element via fixture.nativeElement. We then create an expect/toContain check that accesses the HTML element that has <strong>error-container</strong> as its ID and ensures that its innerHTML contains the string &#8220;Must provide valid credentials&#8221;.</p>



<h2 class="wp-block-heading">Wrapping things up</h2>



<p>Overall, unit testing can be challenging, but as an application grows and development teams have to move faster, it speeds up the overall development process and decreases errors going into production because you can immediately check to see if the changes you are making have unintended consequences elsewhere in the application. It&#8217;s also important to note that as a best practice, it&#8217;s best to write the majority of tests <em>before</em> writing any code in order to ensure you&#8217;re not introducing biases &#8211; It is <strong><em>test driven</em></strong> development, afterall!</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
