vendredi 29 septembre 2017

Constructor argument vs get method argument

The problem:

Say we have EmailInterface like this

interface EmailInterface {
  public function getContent(): string;
}

The interface is nice and I like it, but the thing is that 90% percents of concrete emails classes look like this

class NewPostEmail implements EmailInterface {
   private templateEngine;
   public function __construct(TemplateEngine templateEngine) {
     this.templateEngine = templateEngine;
   }
   public function getContent(): string {
     return this.templateEngine.render('some-template');
   }
}

Which makes me wonder about declaring the interface this way:

interface EmailInterface {
   public function getContent(TemplateEngine templateEngine): string;
}

I have faced this dilemma several times and still do not what is better to do. In the first case my interface is perfect and independent, on the other hand every component which need to create an EmailInterface needs to get the TemplateEngine and pass it along, which I do not really like since it makes the code cumbersome.

Is there a pattern for the second approach? I'd like very much to hear about the other ways to solve the problem.

Aucun commentaire:

Enregistrer un commentaire