I have a class DownloadFile, having following properties
- Two(2) Mandatory parameters
- Three(3) Optional parameters
- All parameters are immutable
1) CURRENT DESIGN (TELESCOPING CONSTRUCTOR PATTERN)
Constructor:
DownloadFile (String name, String url, String from, String by, Boolean isDownloaded)
Mandatory parameters:
- name
- url
Optional parameters:
- from
- by
- 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:
- name
- url
- 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:
- Whether Dagger 2 will solve the problem of this ever increasing parameter constructor? (DownloadFile code example would be great)
- Any other design pattern for such requirement.
Aucun commentaire:
Enregistrer un commentaire