1

So I'm struggling to understand which way of returning a class instance in getter methods is better

Here is version 1

Products.js

class Products {}
module.exports = {Products}

Price.js

class Price {}
module.exports = {Price}

index.js

const { Products} = require('./Products.js')
const { Price} = require('./Price.js')

class General {
  get products() {
    return new Products()
  }

  get price() {
    return new Price()
  }
}

Here is version 2

Products.js

class Products {}
module.exports = new Products()

Price.js

class Price {}
module.exports = new Price()

index.js

const Products = require('./Products.js')
const Price = require('./Price.js')

class General {
  get products() {
    return Products
  }

  get price() {
    return Price
  }
}

Deep inside I have a feeling that it's more correct to initialize the instance of the class only when I'm trying to access it (version 1). However I couldn't find any pros or cons of each approach.

Can someone please confirm that one of this approaches can be considered as a bad practice? Maybe one of this methods has performance issues...

Also as far as I understand when exporting an instance of the class it's becoming a singleton which is an anti pattern as well

anotheruser
  • 582
  • 1
  • 7
  • 23
  • 2
    Yes, generally you'll want to go with the first approach. The second doesn't allow you to create multiple instances, [it's basically creating singletons](https://stackoverflow.com/q/48366563/1048572) indeed and you shouldn't be using `class` syntax for that. Of course, in your artificial example it's hard to tell which one is more appropriate since your classes have no data and no methods. – Bergi Aug 05 '20 at 07:04

0 Answers0