How to avoid circular dependency from abstracting navigation in desktop application?

I am trying to abstract some functionality from my desktop application (JavaFX) for changing views.

So, what I am thinking is:

Navigator interface with methods like goToAccountsOverview(), goToAccountDetails(Account account) etc. The implementation will depend on a ViewFactory to create the Views and a DisplayingViewChanger to change the view that is being displayed.

There will be multiple navigator interfaces depending on the state of the application, starting with:

  • NotConnectedStateNavigator (goToConnectToDatabase(), goToCreateDatabase() etc)

  • ConnectedStateNavigator (goToAccountsOverview(), goToAccountDetails(Account account) etc)

So each state will have its own navigator and view factory and a common view changer. The view factories and navigators will not share a common interface (createView(ViewEnum v) and goToView(View view) respectively).

While implementing this I run into a problem. An example of the problem is this:

In the AccountsOverviewView there is a table with all the accounts. Each account has a button to view the details. Pressing that button should navigate to the AccountDetailsView with the ViewModel of the account (I am using some sort of MVVM).

To do that it would call connectedStateNavigator.goToAccountDetails(accountVM) which would call viewChanger.changeView(connectedStateViewFactory.createAccountDetailsView(accountVM)).

So the AccountsOverviewView needs the ConnectedStateNavigator, which needs the ConnectedStateViewFactory, which needs to be able to construct the original AccountsOverviewView, which needs the ConnectedStateNavigator etc.

Some code to explain it better:

public class AccountsOverviewView {     public AccountsOverviewView(ConnectedStateNavigator navigator, ...) {         (...)         accountDetailsButton.onClick(e -> navigator.goToAccountDetails(account));         (...)     } }  public class ConnectedStateNavigator {     public ConnectedStateNavigator(ConnectedStateViewFactory viewFactory, ...) { ... }        public void goToAccountDetails(Account account) {         viewChanger.changeView(viewFactory.createAccountDetailsView(account));     } }  public class ConnectedStateViewFactory {     public ConnectedStateViewFactory(ConnectedStateNavigator navigator, ...) { ... }      public View createAccountsOverviewView() {         return new AccountsOverviewView(new AccountsOverviewViewModel(navigator, ...));     }      public View createAccountDetailsView(Account account) { ... } } 

How could I design this better to avoid this cyclic reference? Is using a setter or an asynchronous event system the only solution?

Custom module causing “Circular dependency” error after upgrading to Magento 2.3.2

I have a custom module with a plugin for Magento\Framework\Encryption\Encryptor that seems to be causing issues after upgrading to Magento 2.3.2 (from 2.3.1.) When I disable the module, everything works fine. When I enable it, I get “No commands in the namespace” for any namespace I try to use. When I run bin/magento list I get a more detailed error message:

In ServiceManager.php line 1130:    An abstract factory could not create an instance of magentosetupconsolecommandbackupcommand(alias: Magento\Setup\Console\Command\BackupCommand).   In ServiceManager.php line 941:    An exception was raised while creating "Magento\Setup\Console\Command\BackupCommand"; no instance returned   In Di.php line 865:    Missing instance/object for parameter maintenanceMode for Magento\Setup\Console\Command\BackupCommand::__construct   In ServiceManager.php line 1130:    An abstract factory could not create an instance of magentoframeworkappmaintenancemode(alias: Magento\Framework\App\MaintenanceMode).   In ServiceManager.php line 941:    An exception was raised while creating "Magento\Framework\App\MaintenanceMode"; no instance returned   In Developer.php line 55:    Circular dependency: Magento\Framework\Logger\Monolog depends on Magento\Framework\Cache\InvalidateLogger and vice versa. 

I’m fairly certain that it’s the plugin on Encryptor causing this, because when I remove that plugin from di.xml the error goes away.

I’ve also tried commenting out all of the methods from the plugin, so that it’s just an empty class, but the error persists. It appears to be the bare fact that there is a plugin registered for that class that is causing the error.

Any ideas why this might be? I’m not sure why enabling a plugin would appear to cause an error somewhere else entirely, especially when that plugin doesn’t even have any methods in it.

Circular dependence and many references to the same object

I have tried to design a class diagram for my first game. But then I realized that there are some ugly parts.

First, there is reference from StateSystem to State and from State to StateSystem. The StateSystem object contains references to State instances and one of them is always current. StateSystem calls it’s update and render functions. But every instance of State also has to have a reference back to StateSystem, so it can change state to another one. I’d like to know how to avoid the circular dependence in this case.

Secondly, I don’t know where to hold reference(s) to the Input object. Generally, all classes which belong to the UI (green classes) need a reference to the same instance (only existing instance) of Input due to mouse collision detection. Input contains stored information about pressed keys, mouse coordinates and so on. Should I store the reference in every object that needs it?

Moreover, what about TextureManager class? The only thing it does is store Texture instances via string IDs (and preparing it for OpenGL) and when needed, it returns a texture according to a given ID. Should I consider using, for example, the Builder pattern and let only the “director” object own the texture manager and create concrete textures for objects?

Circular References

I have always ‘designed’ systems so that each process was a discrete ‘program’ – so setting up a customer would be a discrete executable program, as would setting up a supplier or maintaining the codes used in the system. Each ‘program’ then had an callable function to allow it to start any of the other programs or to attach notes/documents to the ‘object’ being maintained.

However, I have just been setting up a small system for my own use and decided to ‘funtionalise’ the programs – so each program became a function call. So now a ‘program’ is called rather than executed. This then gives me circular references: Function A -> Function B -> Function C -> Function A.

The question is then, if I require the ability to be able to start any ‘program’ from any other, is the only way to do this without circular references, what I had initially – i.e. each program is a discrete executable in its own right?

How to resolve Circular Dependency when one Helper class is depends on other Helper Class

Having one module named Override\Search in which two helper classes are there.

1. Override\Search\Helper\Data.php  2. Override\Search\Helper\Util.php 

Both helper are depends on each other, thus giving circular dependency error.

Exception #0 (LogicException): Circular dependency:  

Try 1: – using their namespaces in header as follows but still facing same error:

use \Override\Search\Helper\Data as Override_MainHelper; 

Try 2: – Adding initializing in constructor as below

public function __construct(         //Other classes         \Override\Search\Helper\Data $  searchHelperMain     ) {         //Other classes         $  this->_searchHelperMain = $  searchHelperMain;     } 

Following class is Main Data.php

<?php namespace Override\Search\Helper; use \Magento\Store\Model\StoreManagerInterface; use \Magento\Backend\Model\Url; use \Override\Search\Helper\Util; use \Psr\Log\LoggerInterface; use \Magento\Catalog\Model\Product; use Magento\Config\Model\ResourceModel\Config\Data\Collection; use \Magento\Framework\App\RequestInterface;  class Data extends \Magento\Framework\App\Helper\AbstractHelper {     /**      * @var \Magento\Store\Model\StoreManagerInterface      */     protected $  _storeModelStoreManagerInterface;     /**      * @var \Magento\Backend\Model\Url      */     protected $  _backendModelUrl;     /**      * @var \Override\Search\Helper\Util      */     protected $  _searchHelperConfig;     /**      * @var \Psr\Log\LoggerInterface      */     protected $  _psrLogLoggerInterface;     /**      * @var \Magento\Catalog\Model\Product      */     protected $  _catalogModelProduct;     /**      * @var \Magento\Tax\Helper\Data      */     protected $  _taxHelperData;      /**      * @var \Magento\Eav\Model\Entity\Type      */     protected $  _modelEntityType;      /**      * @var \Magento\Eav\Model\Entity\Attribute      */     protected $  _modelEntityAttribute;      /**      * @var \Magento\Framework\Locale\CurrencyInterface      */     protected $  _localeCurrency;      /**      * @var Magento\Directory\Model\CurrencyFactory      */     protected $  _currencyFactory;      /**      * @var Magento\Config\Model\ResourceModel\Config\Data\Collection      */     protected $  _configDataCollection;     /**      * @var \Magento\Store\Model\Store      */     protected $  _frameworkModelStore;     protected $  _data_features_response;     protected $  _data_enabled_feature_response;     public function __construct(         \Magento\Store\Model\StoreManagerInterface $  storeModelStoreManagerInterface,         \Magento\Backend\Model\Url $  backendModelUrl,         \Override\Search\Helper\Util $  searchHelperConfig,         \Psr\Log\LoggerInterface $  psrLogLoggerInterface,         \Magento\Catalog\Model\Product $  catalogModelProduct,         \Magento\Catalog\Helper\Data $  taxHelperData,         \Magento\Eav\Model\Entity\Type $  modelEntityType,         \Magento\Eav\Model\Entity\Attribute $  modelEntityAttribute,         \Magento\Directory\Model\CurrencyFactory $  currencyFactory,         \Magento\Framework\Locale\CurrencyInterface $  localeCurrency,         \Magento\Config\Model\ResourceModel\Config\Data\Collection $  configDataCollection     ) {          $  this->_storeModelStoreManagerInterface = $  storeModelStoreManagerInterface;         $  this->_backendModelUrl = $  backendModelUrl;         $  this->_searchHelperConfig = $  searchHelperConfig;         $  this->_psrLogLoggerInterface = $  psrLogLoggerInterface;         $  this->_catalogModelProduct = $  catalogModelProduct;         $  this->_taxHelperData = $  taxHelperData;         $  this->_modelEntityType = $  modelEntityType;         $  this->_modelEntityAttribute = $  modelEntityAttribute;         $  this->_localeCurrency = $  localeCurrency;         $  this->_currencyFactory = $  currencyFactory;         $  this->_configDataCollection = $  configDataCollection;     }     //Other Functions  } 

Following class is Main Util.php

<?php namespace Override\Search\Helper;  use \Magento\Framework\App\Config\ScopeConfigInterface; use \Magento\Framework\UrlInterface; use \Magento\Store\Model\StoreManagerInterface; use \Override\Search\Model\Product\Sync; use \Magento\Framework\Model\Store; use \Override\Search\Model\Api\Action\Features; use \Override\Search\Helper\Data; //use \Override\Search\Helper\Data as Override_MainHelper;  class Util extends \Magento\Framework\App\Helper\AbstractHelper {     /**      * @var \Override\Search\Helper\Data      */     protected $  _searchHelperMain;      public function __construct(         //Other classes         \Override\Search\Helper\Data $  searchHelperMain     ) {         //Other classes         $  this->_searchHelperMain = $  searchHelperMain;     }      //Other Functions  } 

Having some idea about proxy and factories class but not sure what are pros and cons of those features except some lazy loading stuff and dependency injection.

Circular dependency: Magento\Backend\Helper\Data depends on Magento\Backend\Model\Url and vice versa

What is suitable here that can cover backward compatibility as well i.e. 2.1.x and 2.2.x and 2.3.x? Proxy or Factories or any 3rd way?

Doubt about package-by-feature and circular dependencies

I am implementing a library that:

  1. Takes some input data (I put data structures and classes in the parsing package)
  2. Stores the data in a structure (I put data structures and classes in the storage package)
  3. Present the data in some meaningful way (chart package)

I divided my code this way because if I want to add another data representation (for example a table package) I can reuse parsing and storage packages.

I am though worried about circular dependencies:

  • My Parser should store input data in a dedicated data structure class, Record, this means that DataStorage has to know how to get data from it and that Parser should know how data insertion is performed in DataStorage class.
  • I am also concerned that the chart – and eventually table as well – package should know a bit more about how to get data from my DataStorage class.

Are my concerns valid? If yes, how could I solve the issue? I was thinking to expose some Interfaces in a contracts/interfaces package in such a way that specific classes such as Record and DataStorage would implement them and there wouldn’t be a circular dependency anymore.

Would this solution be considered a good practice or are there any better alternatives?

Circular dependency – is there a good design to eliminate

I was writing some code and came across a scenario that I was thinking about doing a circular dependent class, which I have not done before. I then looked circular dependencies up and whether they are impermissible, and found that it is achievable but not desirable. But I have some dilemma regarding how to implement it without circular dependencies so I thought I should see if there are other suggestions available.

Imagine that you are building an index for a number of files, and those files have a number of attributes, including an attribute that records what files the particular file references.

Attempting to set up some classes mimicking such structure, I have written a number of classes.

  1. subClassA includes defining attributes of a file, let’s call this attribute set A

  2. subClassB includes classification attributes of a file, let’s call this attribute set B

  3. fileObject is an object representing a file, and has one subClassA object and one subClassB object.

  4. fileSet is an object representing a particular set of files, and is essentially a collection of fileObjects

As I was creating subClassB, I realized that the information related to reference files within subClassB is really just fileSet with limited subClassA information. Is it wise then to simply circular reference within subClassB a fileSet object? Or if that is a terrible idea, how should one go about storing the information? Technically, we can create another collection class object under fileObjectthat will store a bunch of subClassA objects, but I don’t really favor that as I would need to duplicate certain functions of fileSet within that new class definition (for example, functions that checks those object, combines those objects, and etc). But if I do it where I have two separate collections with one hosting subClassA attributes and subClassB attributes (like, skipping fileObject altogether, and directly record subClassA and subClassB into a fileSet object), it seems that I am introducing more complexities as I now need to find a way to link these subClassA and subClassB attributes together from a pooled up mess.

With the given scenario, should I just go with circular dependency? Or is there a better way to do it altogether?

Circular Buffer Implementation

I’m implementing a “live analytics” feature and I need to always keep track of the last N items that were added to a collection so I figured I’d make a circular buffer since I couldn’t find one.

I tried to figure out to use Interlocked but couldn’t find out how to use Increment or CompareExchange in an obviously correct way – so I took the lock.

Review/advice is appreciated.

public class CircularBuffer<T> {     private readonly T[] _data;     private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();     private int _i = 0;     private bool _isOneCycleFinished = false;     private readonly int _size;      public CircularBuffer(int size)     {          if (size < 0)         {             throw new ArgumentException($  "{nameof(size)} cannot be negative");         }         _i = 0;         _data = new T[size];         _size = size;     }      public IEnumerable<T> Latest()     {         try         {             _lock.EnterReadLock();             if (!_isOneCycleFinished)             {                 return _data.Take(_i).ToList();             }             return _data.Concat(_data).Skip(_i).Take(_size).ToList();         }         finally         {             _lock.ExitReadLock();         }     }       public void Add(T t)     {         try         {             _lock.EnterWriteLock();             _i = (_i + 1)%_size;             if (!_isOneCycleFinished && _i == 0)             {                 _isOneCycleFinished = true;             }             _data[_i] = t;         }         finally         {             _lock.ExitWriteLock();         }     } } 

How to avoid circular references in JavaScript?

I have two classes. A Bot class and a Client class.

Heres a relevant section of the Bot class.

class Bot {     constructor(client) {         this.client = client;         this.client.on(ChatEvent.NEW_MESSAGE, this.processMessage.bind(this));         this.client.on(ChatEvent.EDIT, this.processMessage.bind(this));     }      async processMessage(msg) {}     saveData(name, data){} } 

As you can see the Bot constructor accepts a Client instance.

Here’s a relevant section of the Client class.

class Client {    async getSites() {         let sites ='sites', sites);         if(rep){           return sites;         }         resp = await request({             [...]         });         sites = JSON.parse(resp);'sites', sites);         return sites;      } } 

The Client class needs to access the Bot instance in the line and

How can I do this without a circular reference?

Ideally I would want to be able to do:

const bot = new Bot(new Client([...])); 

The following way might work, but it uses a circular references:

bot = new Bot(); bot.client = new Client(bot); 

Is circular reference with Typescript array properties bad design?

I understand that having circular dependency can be bad design. However, I have a question regarding a certain class structure.

As an example:


import {Boat} from './boat';  export class Ocean {     boats: Array<Boat> = [];      getWaterLevel() {         return 5;     }      createBoats() {         for (let i = 0; i < 10; i++) {             const boat = new Boat();             boat.ocean = this;             boat.engineRunning = true;    ;         }     } } 


import {Ocean} from './ocean';  export class Boat {     engineRunning: boolean;     ocean: Ocean;      canMove() {         return this.ocean.getWaterLevel() > 5 && this.engineRunning;     } } 

In Typescript this can’t be done without a circular reference problem from the imports. I’ve also read people conclude that its a sign of bad design. The only other solution I could see is to create a third layer which is something like OceanBoat and manage the two resources. Is this bad design or a bad limitation of Typescript?