Michael Durrant
Michael Durrant

Reputation: 96554

Where to place a (class) dependency in another javascript class?

I have a class called Tour that has a method with a dependency on another class called City

I can put the dependency at the top of the file, as in

const City = require './City'
class Tour {
...

but it seems a bit odd to have the dependency listed before the class like that.
I can move it to the method where I use it, as in:

insertAfter(afterCityName, newCityName, appendAtEnd=true) {
  const City = require('./City');
  const cities = this.cities;
  ...

but having it within a method also seems not ideal.

Ideally I would think the constructor but every attempt I've made has been the wrong syntax, for examples:

constructor(cities=[]) {
  this.cities = cities;
  ...
  const City = require('./City');  // No, assigned but never used
  City = require('./City');  // No, City is not defined
  this.City = require('./City'); // No, City is not defined
}

How to place it in the constructor (and still Capitalize The Class) ?

Upvotes: 0

Views: 726

Answers (1)

tadman
tadman

Reputation: 211690

The convention I've seen and prefer is at the very top of the file. This makes it abundantly clear what your imports are. "Sneaky imports" in the middle of the file can lead to surprises.

When you're refactoring things and need to move files around it's easy to click through one file to the next quickly inspecting the top to check that the import paths are set correctly. This is not the case with inline imports.

Keep in mind require() is being retired, it's import from here on out, where import works best at the top of the file, as in:

import City from './City';

This style fits in well with other conventions like Python, Ruby, or C and C++ which use conventions like #include <city.h>.

Upvotes: 1

Related Questions