DEV Community

Cover image for Refactoring: Dependency Injection for Reusable Functions
John Peters
John Peters

Posted on • Updated on

Refactoring: Dependency Injection for Reusable Functions

// In this reusable View component,
// the context of its table
// is injectable with 
// context from elsewhere. 
// This means as a child
// View, others can inject
// the context.

 setTableData(context: any) {
  this.showTable = true;
  this.cdf.detectChanges();
  // Use the reusable function here
  funcSetTableData(
   context, // outside data
   this.paginator, // view 
   this.pageSize,  // number
   this filter,    // string
   this.sort,      // view
  );
  // Back to the view component here
}

Enter fullscreen mode Exit fullscreen mode

Notice that the reusable function is taking in four "this." values. Two of them are Views contained in this View and the other two are string and numeric values respectively. We are "injecting" the reusable function with local values.

From the perspective of this View Component, this is close-coupling; however, the function itself doesn't care where the parameters come from.

Functions just require the proper parameters to work. This means that functions themselves are not close-coupled.

If we create another material table View which re-uses this function it will inject its own required proper dependencies.

We created the function, funcSetTableData when we spotted a possible refactor while thinking about reusability. The number of 'this.' parameters was a clue too.

Had we not moved it into a function library it would have only been known to this View. This is the mal effect of "close-coupling" and not thinking of reusability.

Top comments (0)