0

I have a class like this:

class X {
  X (databaseconn, httpclient) {
    this.httpclient = httpclient
    this.databaseconn = databaseconn
  }

  public func1(a, b) {
    // ...
  }

  public func2(x, y, z) {
    // ...
  }

  // ...

  public funcN(p, q, r) {
    // ...
  }
}

There are very few methods in the class that operate on the injected httpclient (either directly or through some other method). Creating and injecting it, therefore, seems unnecessary and wasteful to me.

What pattern should be followed when there is a rarely used dependency such as the httpclient in this case?

  • 2
    Possible duplicate of [How to determine if a class meets the single responsibility principle?](http://softwareengineering.stackexchange.com/questions/154723/how-to-determine-if-a-class-meets-the-single-responsibility-principle) – gnat Nov 27 '16 at 07:45
  • You mean object-oriented design patterns? Depends on the case, your question is very abstract, whats the concern of the class? – Grim Nov 27 '16 at 08:26
  • 2
    Why not simply create a base class that *does not have* an `httpclient`? Searching for a pattern here seems a bit overkill to me... – tofro Nov 27 '16 at 09:33

1 Answers1

2

You need to decide if httpclient is a dependency of the object or of the methods - and this depends on the class.

For example - let's say you have a Message class that needs smtpclient for it's send method. Let's also say we have a MailReceiver class that checks for new emails and needs smtpclient for it's poll method. Both classes' other methods don't need smtpclient. Is it a dependency of the object or of the methods?

In Message's case, it's a dependency of the method. An email message is an email message even before you send it, and you may want to send it via multiple SMTP clients. So you don't pass smtpclient to the c'tor - you pass it directly to the send method.

For MailReceiver, on the other hand, it's a dependency of the object. A mail receiver needs to receive the mails from somewhere. So you pass smtpclient to the c'tor, and poll just has it.

Don't think in terms of "unnecessary" and "wasteful" - think what makes sense for the object model.

Idan Arye
  • 12,032
  • 31
  • 40