Typescript on the client-side: what is the best way to eliminate circular dependencies when using the factory method design pattern?

In my code, I have implemented the factory method pattern. However, some instances using this pattern end up with circular dependencies. Removing these dependencies has proven to be a challenge for me. To illustrate, consider the following example:

// factoryMethod.ts
import Instance1 from './Instance1';
import Instance2 from './Instance2';
import Instance3 from './Instance3';
import { Instance, InstanceName } from './Instance';

export const getInstanceByName = (
  instanceName: InstanceName
): Instance => {
  switch (instanceName) {
    case 'Instance1':
      return Instance1;
    case 'Instance2':
      return Instance2;
    case 'Instance3':
      return Instance3;
    default:
      throw new Error();
  }
};

// extremelyHelpfulUtilityFunction.ts
import { getInstanceByName } from './factoryMethod';

export const extremelyHelpfulUtilityFunction = (instanceName: InstanceName): number => {
  // An illustrative utility function
  return getInstanceByName(instanceName).num
}

// Instance.ts
export interface Instance {
  doSomething: () => number;
  num: number;
}

export type InstanceName = 'Instance1' | 'Instance2' | 'Instance3';

// Instance1.ts
import { extremelyHelpfulUtilityFunction } from './extremelyHelpfulUtilityFunction';

const i: Instance = {
  doSomething: (): number => {
    return extremelyHelpfulUtilityFunction('Instance2') + extremelyHelpfulUtilityFunction('Instance3'); // circular dependency
  },
}
export default i;

// Other instances defined below, you get the idea.

As I compile this code using rollup, it raises a warning about the circular dependencies present. Although the code functions correctly, I am determined to eliminate this warning. How can I refactor the code so that InstanceX can access InstanceY without creating a circular dependency?

Answer №1

It seems that the main issue lies within the extremelyHelpfulUtilityFunction needing to be aware of getInstanceByName. I suggest a different approach where the factory method's result is predetermined by the caller and passed as an argument to the utility function.

Here is my proposal:

// InstanceA.ts
const instanceA: Instance = {
  doSomething: (): number => {
    return (new InstanceB()).toNumeric() + (new InstanceC()).toNumeric()
  },
}

The function toNumeric should be defined in Instance.ts and customized in its subclasses, utilizing the utility function with appropriate arguments. For example:

// InstanceB.ts
const instanceB: Instance = {
  doSomething: ...,
  toNumeric: (): number => {
    return extremelyHelpfulUtilityFunction(5678)
  }
}

If you were to create a proper class for InstanceB instead of using an object, the code would look like this:

// InstanceB.ts
class InstanceB extends Instance {
  num = 5678;
  doSomething: ...
  toNumeric(): number {
    return extremelyHelpfulUtilityFunction(this.num)
  }
}
export default new InstanceB();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to host two Node.js socket.io projects on one URL

My Nodejs server is hosted on Amazon Lightsail. I have successfully connected to it and configured Apache for Nodejs. I am working with 2 Nodejs socket.io projects and I want to access both of them using a single URL. Below are the links in Nextjs: const ...

What is the best way to implement dynamic comment display similar to Stack Overflow using Asp.net and Jquery?

I have created a small web application using Asp.net and C#. Currently, I am able to retrieve comments by refreshing the entire page. However, I would like to achieve this functionality without having to do a full refresh. For instance Let's say the ...

.Certain IDs on a website may not respond to clicks due to various reasons

I have created a JavaScript file to automatically click a button on a website using a Chrome extension. When testing the code using Chrome Script snippet, I noticed that it worked for some IDs but not for others. Can someone please help me with this issue? ...

Extract JSON data from Python API

Currently, I am delving into web programming and have created a Python API that queries an SQL database to return a JSON. The functionality of the API is as expected. In parallel, I've developed a controller where I execute a GET request to utilize t ...

Vue.js does not support the usage of external JSON files directly within HTML documents

I'm encountering issues fetching data from an external JSON file for a specific variable. I suspect that the problem lies in using Vue.js within the HTML, as it seems to be having trouble interpreting my code correctly.:joy: jsfiddle Additionally, I ...

how to share global variables across all components in react js

Operating a shopping cart website requires transmitting values to all components. For instance, when a user logs into the site, I save their information in localStorage. Now, most components need access to this data. My dilemma is whether I should retriev ...

Stop a loop that includes an asynchronous AJAX function

Embarking on my Javascript journey as a beginner, I find myself facing the first of many questions ahead! Here is the task at hand: I have a directory filled with several .txt files named art1.txt, art2.txt, and so on (the total count may vary, which is ...

Tips for changing the size and color of SVG images in a NextJS application

Looking to customize the color and size of an svg image named "headset.svg". Prior to this, I used next/image: <Image src={'/headset.svg'} alt='logo' width={30} height={30} className='object-contain' /> The s ...

Unable to showcase the content inside the input box

I am having trouble displaying a default value in an input field. Here is how I attempted to do it: <input matInput formControlName="name" value="Ray"> Unfortunately, the value is not appearing as expected. You can view my code o ...

The useEffect hook is executed only once and will not fetch data again upon refreshing the page

There's this component in my project that fetches data from a website and attempts to extract its keys. The issue I'm facing is that it functions correctly the first time, but upon refreshing the page or saving the project in VSCode (which trig ...

Is there a way to eliminate the border of an image attribute pulled from an input field?

Seeking assistance with a persistent issue I'm facing. I have an input for an image and a script to display the selected image. However, when the input is empty, a frustrating black border appears around the image attribute. How can I remove this bord ...

Error encountered while deploying to Heroku: cross-env not detected in Node.js application

As I attempt to deploy my project on Heroku, the following error persists despite all my efforts. Please assist me in resolving this issue: { "name": "storybooks", "version": "1.0.0", "des ...

Choose children input textboxes based on the parent class during the onFocus and onBlur events

How can I dynamically add and remove the "invalid-class" in my iti class div based on focus events in an input textbox, utilizing jQuery? <div class="form-group col-md-6"> <div class="d-flex position-relative"> & ...

Tips for maintaining accessibility to data while concealing input information

Is it possible to access data submitted in a form even if the inputs were hidden by setting their display to none? If not, what approach should be taken to ensure that data can still be sent via form and accessed when the inputs are hidden? ...

The inner workings of JavaScript functions

I am curious about how JavaScript functions are executed and in what order. Let's consider a scenario with the following JavaScript functions: <span id=indicator></span> function BlockOne(){ var textToWrite = document.createTextNode ...

Manipulating a dynamic array within an Angular repeater using the splice method

Encountering an issue with deleting an object from an array using splice. The array, dynamically created through a UI, is stored in $scope.productAttributes.Products. Here's an example of the array structure... [ { "ProductLabel":"Net", "Code ...

Utilizing ng-change in an AngularJS directive with isolated scope to transition towards a component-based architecture. Let's evolve our approach

I've been struggling to get ng-change to trigger in my directive with an isolated scope. I'm working on transitioning from ng-controller to a more component-based architecture, but it's turning out to be more difficult than I anticipated. I ...

What are the steps to fix the error stating that 'loginError.data' is an unknown type?

Recently delving into typescript, I decided to test the waters with nextjs, rtk query, and antd. However, while attempting to access error within useLoginMutation using the property error.data.message, it was flagged as type unknown. To tackle this issue, ...

How to update an object property in React using checkboxes

I am currently navigating the world of react and have encountered a challenging issue. I am in the process of developing an ordering application where users can customize their orders by selecting different ingredients. My approach involves using checkboxe ...

The value of req.session.returnTo is not defined

I have implemented passport for user authentication using discord oauth2. I want the users to be redirected back to the original page they came from instead of being directed to the home page or a dashboard. Even though I tried saving the URL in the sessi ...