Ozrix Ozrix - 2 years ago 93
Javascript Question

Instantiating objects in Typescript, honoring loose coupling

I'm no OOP expert, and am (since learning about loose coupling) struggling to find an answer to the question of in what way to instantiate objects to bootstrap an application written in Typescript.

Is it okay to create a "

" class, whose sole purpose is to instantiate, set up, and pass around all the objects used in an application? By depending on the
classes, does this approach violate the OOP principles? If so, what would the entry point of the application look like?


import {Foo} from "./foo-class";
import {Bar} from "./bar-class";

interface IOptions {
amountOfFooObjects: number;

class Main {
private fooObjects: Foo[] = [];

constructor(options: IOptions) {

private buildFoo(options) {
for (let i = 0; i < options.length; i++) {
this.fooObjects.push(new Foo(new Bar()));
let main = new Main({ amountOfFooObjects: 10 });

Answer Source

OO-wise what you're doing is fine, it's similar to how it is in java for example (except for the static main function).

You can however do things a bit differently with typescript/javascript.
As your Main class is supposed to be a singleton, as I assume you intend to have only one instance of it, you can just create it as an object:

let main = {
    fooObjects: [],
    init: function(options: IOptions) {
    buildFoo: function(options: IOptions) {
        for (let i = 0; i < options.amountOfFooObjects; i++) {
            this.fooObjects.push(new Foo(new Bar()));
main.init({ amountOfFooObjects: 10 });

You can also have an interface for it if you want to force types:

interface Main {
    fooObjects: Foo[];
    init: (options: IOptions) => void;
    buildFoo: (options: IOptions) => void;

let main: Main = {

But since you're in a module you can simply:

let fooObjects: Foo[] = [];
function init(options: IOptions) {

function buildFoo(options: IOptions) {
    for (let i = 0; i < options.amountOfFooObjects; i++) {
        this.fooObjects.push(new Foo(new Bar()));

And then expose (export) what you wish.

However, if you wish to extend this Main class of yours, like provide different implementations for it, then stick with what you have now.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download