mardi 15 novembre 2016

Design Pattern or Dependency Injection for Telescope Constructor

I have a class DownloadFile, having following properties

  1. Two(2) Mandatory parameters
  2. Three(3) Optional parameters
  3. All parameters are immutable

1) CURRENT DESIGN (TELESCOPING CONSTRUCTOR PATTERN)

Constructor:

DownloadFile (String name, String url, String from, String by, Boolean isDownloaded)

Mandatory parameters:

  1. name
  2. url

Optional parameters:

  1. from
  2. by
  3. isDownloaded

I am calling my DownloadFile class from 20 different locations (when user click a button on list, any activity started, service, on push notification, on specific alarm, any broadcast receive etc etc).

new DownloadFile(name, url, from, by, false);

Problem:

Whenever I want to add new parameter, I need to change the class + 20 different calling locations

for example, I want to add third mandatory parameter (size)

New Mandatory parameters:

  1. name
  2. url
  3. size

2) OPTION 1 (BUILDER PATTERN)

Good explanation of Builder Pattern is present here

As Joshua Bloch states in Effective Java, 2nd Edition:

The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

Problem:

Problem remains same, if there is addition in mandatory parameter, I need to change the class + 20 different calling locations


3) OPTION 2 (DEPENDENCY INJECTION - Dagger2)

Google advised to avoid dependency injection frameworks like Roboguice, while Dagger 2 is the only DI advised by Google.

I haven't used and looked into Dagger2 before, on quick I found the basic tutorial for hands on and this answer by one of its founder


Questions:

  1. Whether Dagger 2 will solve the problem of this ever increasing parameter constructor? (DownloadFile code example would be great)
  2. Any other design pattern for such requirement.

Aucun commentaire:

Enregistrer un commentaire