Home > OS >  Is it a good practice intatiating or registering multiple objects at the same time
Is it a good practice intatiating or registering multiple objects at the same time

Time:11-27

I am creating a NodeJS boilerplate, as it was a framework, and I want to "register" the routes or endpoints when the application starts. I want to have an array of route classes and then instantiate them. Similar to what NestJs does with their Controllers. Then I want to loop through the collection and create instances of each Route passed in the array. Something as the following:

class RegisterRoutes() {
  routes: [FirstRoute, SecondRoute];

  instatiateRoutes() {
    for (route in routes) {
      new route()
    }
  }
}

Is this a good practice?

CodePudding user response:

If you wanted to support nested routes, would you consider using a tree and then you can recurse through it to build your routes?

CodePudding user response:

It depends on when they are going to be used your example unfortunately is not a real-world example so it's hard to say which is better for you.

What you have got there is a method that sets them up for you but nothing calling it, if they always need to be set up no if no but then the best way is to get them set up at "end of compile" time. E.G

class RegisterRoutes() {
  routes: [new route(), new route()];
}

Or if you're not always needing them but need other methods from the RegisterRoutes class (which I doubt by its name) then the method you have got is better.

  • Related