samedi 6 juin 2020

How to initialise a class with data which is not available at time of initialisation?

I had to write test for this controller class. The controller class' validate function will be called directly or the entry point. This controller uses SomeService class' doSomethingWithData. SomeService class needs data which is not available at time of Controller construction, but as validate function's argument.

// someservice.ts
class SomeService {
    data: string;

    constructor(data: string) {
        this.data = data;
    }

    doSomethingWithData() {
        // Code to Do something here.
    }
}

// Controller.ts
import SomeService from './someservice.ts';

class MyController {
      validate(event: string) {
           let service = new SomeServce(event);
           service.doSomethingWithData();
      }

}

To test it I wanted to use a mock service, so I re-written the controller as :

// Controller.ts
import SomeService from './someservice.ts';

class MyController {
      myservice: SomeService = new SomeService(/* Problem: What should I write here, this data would come in future as validate's argument /*);
      validate(event: string) {
           let service = new SomeServce(event);
           service.doSomethingWithData();
      }

}

To overcome this, I re-written service's constructor and controller usage

 // someservice.ts
class SomeService {
    data: string = '';

    initiateService(data: string) {
        this.data = data;
    }
    doSomethingWithData() {
        // Code to Do something here.
    }
}

// controller.ts
import SomeService from './someservice.ts';

class MyController {
      myservice: SomeService = new SomeService();
      validate(event: string) {
           service.initiate(event);
           service.doSomethingWithData();
      }

}

Is there any other way to pass the data to a service which is coming as a function argument? Like in this scenario. Is my temporary solution good enough? Is there any design pattern for this situation?

Aucun commentaire:

Enregistrer un commentaire